I'm trying to build a simple flash game in which I need to be able to restart the game if the user dies. However resetting all of the variables doesn't seem to be accomplishing anything. All of my game elements are stored in arrays and I thought that maybe setting each of them to the array constructor wasn't deleting the objects that they were pointing to and that they were left on the screen as a result. Does anyone know of a way to delete those elements (since I can't iterate over the list to delete them for obvious reasons) or does anyone know of a better way to reset a game in flash? For reference, here's the init function and the variable declarations at the top of my program that are supposed to start/reset the game.
public class Main extends MovieClip {
//put field variables here
static var hudLayer:Sprite; //layer used to represent HUD elements
static var gameLayer:Sprite; //layer used to represent objects in the game space
static var uiTextLayer:Sprite; //layer used to represent text that should appear ON TOP of the HUD
static var backgroundLayer:Sprite; //layer used to display the background image
static var players: Array; //array of all the player objects for reference
static var backgrounds:Array; //array of all the background objects
static var lines: Array; //array of all the lines
static var powerUps:Array; //array of all the powerups
static var enemies:Array; //array of all the enemies
static var miscellaneousObjects:Array; //array of miscellaneous objects that I'd like to be able to keep track of
var xCoords:Array, yCoords:Array; //Used to temporarily hold x and y coordinates when making new drawings
static var grav:Number; //coefficient representing the force of gravity
static var isPaused:Boolean; //manages pausing mechanic
static var timer:Timer; //used for time delayed updating of game elements
var pt:Point; //variable used by collision detection
var asteroidTiming:Number; //used to properly delay creating of asteroids on the screen
static var asteroidDelay:Number; //current delay between when asteroids are deployed, changes over course of execution
static var score:Number; //this should be self-explanatory
var scoreField:TextField; //used to display the score
static var myTextFormat:TextFormat; //used to format the text in the scoreField
static var inGameOver:Boolean; //used to determine if we're at the game over screen
[Frame(factoryClass="Preloader")]
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
public function init(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE, init);
//set up the Sprite Layers
backgroundLayer = new Sprite();
gameLayer = new Sprite();
hudLayer = new Sprite();
uiTextLayer = new Sprite();
addChild(backgroundLayer);
addChild(gameLayer);
addChild(hudLayer);
addChild(uiTextLayer);
//instantiate important variables
xCoords = new Array();
yCoords = new Array();
players = new Array();
backgrounds = new Array();
enemies = new Array();
powerUps = new Array();
miscellaneousObjects = new Array();
grav = .04;
addBackGround();
addPlayer(400, 50);
isPaused = false;
lines = new Array();
score = 0;
inGameOver = false;
//instantiate text fields
scoreField = new TextField();
scoreField.text = "Score: " + score;
hudLayer.addChild(scoreField);
scoreField.x = 20;
scoreField.y = 20;
scoreField.textColor = 0xFFFFFF;
myTextFormat = new TextFormat();
myTextFormat.size = 15;
scoreField.setTextFormat(myTextFormat);
//set up timer
timer = new Timer(5);
timer.addEventListener(TimerEvent.TIMER, function():void { update()});
timer.start()
asteroidTiming = 0;
asteroidDelay = 150;
//set up mouse listener
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownEvent);
//set up key listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyEvent);
//tests
}
Since I can't see all your code, I will guess that you are not using removechild() to get rid of display objects off the stage.
To create a object:
var object:DisplayObject = new DisplayObject();
To make it visible on the display list:
parent.addChild(object);
To remove it from the display list:
parent.removeChild(object);
To erase its memory:
object=null;
(These four things must be done in this order, for this to work properly. IF you make something null without removing it from the display list, you leave it there, still visible, with no way of referencing it. It like lost in your application.
You have to make sure you always use removeChild() before making a variable null, or overwriting the variable.
Related
I have a loop that runs and adds a TextField from an array to a Sprite, and draws that Sprite to a BitmapData object. When I reference a previously drawn TextField, nothing is drawn to the BitmapData.
public class Pocket extends Sprite
{
public var inventory:Array = [textField1, textField2, textField3]; //array of TextFields, populated by another class
public var order:Array = [0,1,2,1]; //array of ints indicating the order of which items in "inventory" should be displayed (the error lies when an element is repeated - in this case, 1
public function getItem(index:int):Array
{
var bitmaps:Array = new Array();
for(var i:int = 0; i < order.length; i++)
{
var bitmapData:BitmapData = new BitmapData(32, 32);
var background:Sprite = new Sprite();
background.graphics.beginFill();
background.graphics.drawRect(0,0,32,32);
background.graphics.endFill();
bitmapData.draw(background); //this always executes as expected
var sprite:Sprite = new Sprite();
sprite.addChild(inventory[order[i]]);
bitmapData.draw(sprite);
var bitmap:Bitmap = new Bitmap(bitmapData);
bitmaps.push(bitmap);
sprite.removeChild(inventory[order[i]]);
}
return bitmaps;
}
}
When the last element in order is called (1), the resulting Bitmap does not contain a textfield.
When the loop runs the first time, adding the TextField inventory[0] to a Sprite, the Sprite is drawn as expected. The second box is drawn, using inventory[1]. However, when I run the same code trying to draw inventory[1] a second time, nothing happens. The same would happen if I try to draw inventory[0], but if I use a TextField that has yet to be added to a Sprite (ex. inventory[2], should one exist), it draws as expected.
Any ideas?
Thanks in advance.
I am a student who's working for months on a game and now I've got stuck on a problem.
I am new to actionscript 3 but i learn fast.
I can load my menu screen ("startScreen.swf") into my game (firstgame) automatically and everything works fine when I click play or storyScreen or instructionsScreen. But the problem is that I want to return after pressing ESC button. I have tried many code but nothing works exactly how I want.
Example: I click on story and the swf (storyScreen.swf) loads and I can read the story and when I am finished, I want to press ESC to reload my swf (startScreen.swf) and all the functions in it. Like play and instructions.
You can find my code and empty space in the function (esc).
I know it is maybe easy to solve but I really don't know how. :(
public class FirstGame extends MovieClip
{
public var Player:MovieClip
private var leftKeyIsDown:Boolean;
private var RightKeyIsDown:Boolean;
private var aMissileArray:Array;
private var aEnemyArray:Array;
public var scoreTxt:TextField;
public var ammoTxt:TextField;
public var MenuEnd:EndGameScreen;
public var menuAgain:EndGameScreen;
private var MenuStart:mcStartGameScreen;
private var MenuStory:mcStartGameScreen;
private var MenuInstructions:mcStartGameScreen;
private var nScore:Number;
private var nAmmo:Number;
private var tEnemyTimer:Timer;
public function FirstGame()
{
//Create a loader object
var startLoader:Loader = new Loader();
//add event listener to listen for the complete event
startLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, startLoaded);
//load our loader object
startLoader.load(new URLRequest("startScreen.swf"));
}
public function startLoaded(e:Event):void
{
MenuEnd.hideScreen();
Player.visible = false;
scoreTxt.visible = false;
ammoTxt.visible = false;
//get a reference to the loaded movieclip
MenuStart = e.target.content as mcStartGameScreen;
//listen for start game event
MenuStart.addEventListener("START_GAME", playGameAgain);
//add it to the stage
addChild(MenuStart);
//get a reference to the loaded movieclip
MenuStory = e.target.content as mcStartGameScreen;
//listen for start game event
MenuStory.addEventListener("SHOW_STORY", storyGameScreen);
//add it to the stage
addChild(MenuStory);
//get a reference to the loaded movieclip
MenuInstructions = e.target.content as mcStartGameScreen;
//listen for start game event
MenuInstructions.addEventListener("SHOW_INSTRUCTIONS", instructionsGameScreen);
//add it to the stage
addChild(MenuInstructions);
}
private function instructionsGameScreen(e:Event):void
{
var instructionsLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("instructionsScreen.swf");
instructionsLoader.load(url);
addChild(instructionsLoader);
stage.addEventListener(KeyboardEvent.KEY_UP, esc);
}
private function storyGameScreen(e:Event):void
{
var storyLoader:Loader = new Loader();
var url:URLRequest = new URLRequest("storyScreen.swf");
storyLoader.load(url);
addChild(storyLoader);
stage.addEventListener(KeyboardEvent.KEY_UP, esc);
}
private function esc(e:KeyboardEvent):void
{
if (e.keyCode == 27)
{
//fscommand("quit");
/////////test//////////////////(new URLRequest(stage.loaderInfo.url), "FirstGame.swf");
}
}
private function playGameAgain(e:Event):void
{
//initialize variables
aMissileArray = new Array();
aEnemyArray = new Array();
nScore = 0;
nAmmo = 20;
Player.x = 262,95
Player.y = 323,30
Player.visible = true;
scoreTxt.visible = true;
ammoTxt.visible = true;
MenuStart.hideScreen();
MenuEnd.addEventListener("PLAY_AGAIN", playGameAgain);
MenuEnd.hideScreen();
updateScoreText();
updateAmmoText();
//trace("First Game Loaded");
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.addEventListener(Event.ENTER_FRAME, gameLoop)
//creat an timer object
tEnemyTimer = new Timer(1000)
//listen for the timer ticks/intervals
tEnemyTimer.addEventListener(TimerEvent.TIMER, addEnemy)
//start our timer
tEnemyTimer.start();
}
I believe you should be able to start a new request on the same loader object. Either way, you're dealing with object creation + cleanup. The crux of the solution I'm offering is that you reuse your loaders.
Your current code is somewhat repetitious, so I've modified it slightly to demonstrate how you could simplify the code. Some thoughts while reviewing your code:
You're adding the same object to the stage multiple times (ie.,
MenuStart, MenuStory, MenuInstructions); these are all pointers to
the same root swf you loaded (a.k.a., startLoader).
You've registered events the stage at multiple locations. Best
practice is to place these in your constructor as they are
persistent.
Because you want to reuse your loaders at a later point, keeping a
table with them makes it easier to reference.
Any time you find yourself programming the same code in similar ways,
it's a good indication that you can simplify with a single function
(simply change the arguments).
Give this a try:
public var Player:MovieClip
private var leftKeyIsDown:Boolean;
private var RightKeyIsDown:Boolean;
private var aMissileArray:Array;
private var aEnemyArray:Array;
public var scoreTxt:TextField;
public var ammoTxt:TextField;
public var MenuEnd:EndGameScreen;
public var menuAgain:EndGameScreen;
private var MenuStart:mcStartGameScreen;
private var MenuStory:mcStartGameScreen;
private var MenuInstructions:mcStartGameScreen;
private var nScore:Number;
private var nAmmo:Number;
private var tEnemyTimer:Timer;
private var screens:Object = {
"SHOW_INSTRUCTIONS":{
"loader":new Loader(),
"url":new URLRequest("instructionsScreen.swf")
},
"SHOW_STORY":{
"loader":new Loader(),
"url":new URLRequest("storyScreen.swf")
},
"START_GAME":{
"loader":new Loader(),
"url":new URLRequest("startScreen.swf")
}
}
public function FirstGame() {
var startLoader:Loader = loadScreen({"type":"START_GAME"});
//Register our event listeners
startLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, startLoaded);
stage.addEventListener(KeyboardEvent.KEY_UP, esc);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(Event.ENTER_FRAME, gameLoop)
}
private function loadScreen(e:Object):Loader {
screens[e.type].loader.load(screens[e.type].url);
addChild(screens[e.type].loader);
return screens[e.type].loader;
}
public function startLoaded(e:Event):void {
//initialize variables
aMissileArray = new Array();
aEnemyArray = new Array();
nScore = 0;
nAmmo = 20;
Player.x = 262, 95
Player.y = 323, 30
Player.visible = true;
scoreTxt.visible = true;
ammoTxt.visible = true;
MenuEnd.addEventListener("PLAY_AGAIN", playGameAgain);
MenuEnd.hideScreen();
updateScoreText();
updateAmmoText();
//creat an timer object
tEnemyTimer = new Timer(1000)
tEnemyTimer.addEventListener(TimerEvent.TIMER, addEnemy)
tEnemyTimer.start();
var swfRoot = screens.START_GAME.loader["content"];
swfRoot.addEventListener("START_GAME", loadScreen);
swfRoot.addEventListener("SHOW_STORY", loadScreen);
swfRoot.addEventListener("SHOW_INSTRUCTIONS", loadScreen);
}
private function esc(e:KeyboardEvent):void {
if (e.keyCode == 27) {
//fscommand("quit");
// Loop through our loaders, and reset them all.
for each (var entry:Object in screens) {
entry.loader.unloadAndStop();
removeChild(entry.loader);
}
// Reload the start screen
var startLoader:Loader = loadScreen({"type":"START_GAME"});
startLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, startLoaded);
}
}
The last thing I want to be guilty of is telling you how to run your project, however, I think you may be taking the wrong approach, here.
Instead of setting up the story and the game as separate swf files, what you would probably need to do is set up the story as a MovieClip, and the game as a MovieClip. (Yes, MovieClips can contain other symbols, including other MovieClips.) Then, you'll want to hide/show or add/remove these MovieClips from your stage using code.
If you need to know how to do this, let me give you the age-old admonishment: RTD (Read the Documentation). These are basic tasks that are covered both in the online Adobe Flash documentation, and across numerous tutorials online.
I hope that helps!
I am working on a Flash scene that reads from an XML file to "build" up an animation itself.
Reading the XML is no problem, that works like a charm. My issue is when I come to placing the assets (images) on to the stage.
My code is below:
import flash.display.Sprite;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.display.MovieClip;
var xmlLoader:URLLoader;
var builderXml:XML;
var container:MovieClip = new MovieClip();
var assetsArray:Array = new Array();
var bg:Sprite;
stage.addChild(container);
init();
function init():void
{
xmlLoader = new URLLoader();
xmlLoader.load(new URLRequest("build_me.xml"));
xmlLoader.addEventListener(Event.COMPLETE, processXML);
}
function processXML(e:Event):void {
builderXml = new XML(e.target.data);
for (var i:int = 0; i < builderXml.assets.*.length(); i++){
var image:MovieClip = new MovieClip();
var assetArray:Array = new Array();
image.x = builderXml.assets.asset[i].start.position.x;
image.y = builderXml.assets.asset[i].start.position.y;
trace(image.x);
assetArray.push(builderXml.assets.asset[i].source);
assetArray.push(builderXml.assets.asset[i].start.scale);
assetArray.push(builderXml.assets.asset[i].start.position.x);
assetArray.push(builderXml.assets.asset[i].start.position.y);
assetArray.push(builderXml.assets.asset[i].start.rotation);
assetArray.push(image);
assetsArray.push(assetArray);
var lc:LoaderContext = new LoaderContext();
lc.checkPolicyFile = false;
var loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
var _myURLRequest = new URLRequest(builderXml.assets.asset[i].source);
loader.load(_myURLRequest, lc);
function onImageLoaded(e:Event):void
{
loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onImageLoaded);
image.addChild(e.target.content);
}
container.addChild(assetsArray[i][5]);
}
trace(assetsArray);
}
My XML has 2 assets listed, one 1280 x 720 image for a backdrop and the other is a simple logo that I want to position, using set x and y coordinates.
The problem is that both assets are being added to the same movieclip, despite the fact I am creating a new MC instance inside the FOR loop.
How can I get the assets to adhere to separate movieclips that I can then store in the array (pretty sure I am storing the current MC properly in the array, just happens that the MC contains 2 images, not 1 a piece)
Also, why is it that I cannot access the variable "i" inside the "onImageLoaded" function? It sits inside the FOR loop...
You are using a global variable inside a listener, and expect it to not being changed when the listener would actually fire. Listeners are asynchronous, so you should track which of the loaders fired a Event.COMPLETE event so that you could retrieve a correct instance of image MC out of those prepared at the XML parsing step, and only then stuff the loader's content inside it. This my answer has a method of doing just that, the method you should use is similar to the one that's used to retrieve a corresponding progress bar over there.
I am successful in loading a single image and creating it using addChild(). Now I am trying to load multiple images into a sprite "Container" using a forEach loop increasing the X value for each image so they are displayed in a row. The imageloader is referenced to linkage within an XML document. If I testrun this code, this error pops up at the point when the image is loaded and I try to removeChild() the loadBar Animation.
ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller.
at flash.display::DisplayObjectContainer/removeChild()
Here is the AS3:
private function loadBG():void {
var artGrab:Number = 0;
var artX:Number = 0;
for each (var albumData:XML in mainXML.artist[artistID].album) {
imgURL = new URLRequest(mainXML.artist[artistID].album[artGrab].art);
imgLdr = new Loader();
//if you're loading a bigger image or need a preloader
imgLdr.contentLoaderInfo.addEventListener(Event.COMPLETE,onBGLoaded);
imgLdr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading);
//add loader animation "All Loader"
ldrAnim = new AllLoader();
albumContainer.addChild(ldrAnim);
ldrAnim.x = artX;
ldrAnim.y = 200;
imgLdr.load(imgURL);
artGrab++;
artX + 481;
ldrAnim.x + 481;
}
}
private function onLoading(evt:ProgressEvent):void {
var bytesToLoad:Number = imgLdr.contentLoaderInfo.bytesTotal;
var numberLoaded:Number = imgLdr.contentLoaderInfo.bytesLoaded;
ldrAnim.progBar.scaleX = numberLoaded / bytesToLoad;
var loadedPercent = Math.round(numberLoaded / bytesToLoad * 100);
ldrAnim.progPercent.text = loadedPercent + " %";
trace("Loading..." + loadedPercent + "%");
}
private function onBGLoaded(evt:Event):void {
trace("image loaded!");
//image setup
addChildAt(imgLdr,0);
//now that its 100% loaded, you can resize it , etc.
removeChild(ldrAnim);
//use cross multiplying of fractions to maintain aspect ratio
var origW = imgLdr.contentLoaderInfo.width;
var origH = imgLdr.contentLoaderInfo.height;
trace("orig width: "+ origW + "orig height: " + origH);
//set new width
imgLdr.width = 481;
var newH:Number = 481 * origH / origW;
imgLdr.height = newH;
//may wish to do positioning AFTER resizing
imgLdr.x = stage.stageWidth / 2 - imgLdr.width / 2;
imgLdr.x = 0;
imgLdr.y = 0;
imgLdr.width = 480;
imgLdr.height = 480;
imgLdr.alpha = 1;
imgLdr.z = 0;
}
Bless you for reading this all, I don't understand what is causing this error so comments are appreciated!
You need to have an array of animations for your loaders to hold with the loaders themselves, then when another ProgressEvent.PROGRESS event will arrive, query the array for event.target index, grab corresponding animation and adjust that, and stop relying on single-valued global vars once you put a single listener onto multiple different objects!
var animations:Vector.<AllLoader>;
var loaders:Vector.<LoaderInfo>;
private function loadBG():void {
var artGrab:int=0;
var artX:int=0;
animations=new Vector.<AllLoader>();
loaders=new Vector.<LoaderInfo>;
for each (var albumData:XML in mainXML.artist[artistID].album) {
imgURL = new URLRequest(mainXML.artist[artistID].album[artGrab].art);
imgLdr = new Loader();
//if you're loading a bigger image or need a preloader
imgLdr.contentLoaderInfo.addEventListener(Event.COMPLETE,onBGLoaded);
imgLdr.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading);
//add loader animation "All Loader"
ldrAnim = new AllLoader();
albumContainer.addChild(ldrAnim);
anomations.push(ldrAnim)
loaders.push(imgLdr.contentLoaderInfo); // fill the arrays
ldrAnim.x = artX;
ldrAnim.y=200;
imgLdr.load(imgURL);
artGrab++;
artX+=481;
}
}
private function onLoading(evt:ProgressEvent):void{
var bytesToLoad:Number=evt.target.bytesTotal;
var numberLoaded:Number=evt.target.bytesLoaded; // note it now refers to target of event
var index:int=loaders.indexOf(evt.target); // should be valid
var ldrAnim:AllLoader=animations[index]; // grab corresponding animation
ldrAnim.progBar.scaleX = numberLoaded/bytesToLoad;
var loadedPercent=Math.round(numberLoaded/bytesToLoad*100);
ldrAnim.progPercent.text = loadedPercent +" %";
trace("Loading..."+loadedPercent +"%");
}
Do the same trick with your onBGLoaded function yourself, as a lesson. Note, you have to retrieve imgLdr value correctly from the event.
What's happening is that you have populated the variable ldrAnim multipe times, creating a new AllLoader each time. When you call removeChild(), this works fine the first time (sort of--it will remove the last one you created, whether it matches the image that loaded or not). When you call removeChild() again, you're calling it for the same one you just removed (which is no longer a child of the object you're calling it on).
One way to fix this is to use a Dictionary and associate each AllLoader with the Loader for that image. When the COMPLETE event fires, you can then look up the Alloader based on the event's properties and remove it.
Another solution is to write a Class that wraps an AllLoader and a Loader and then handles the transition between the two itself when the Loader has finished loading.
That might look something like this:
public class LoadSwitcher extends Sprite{
protected var loader:Loader;
protected var allLoader:AllLoader;
public function loadSwitcher(url) {
super();
loader = new Loader();
var request:URLRequest = new URLRequest(url);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, switchLoaders);
allLoader = new AllLoader(loader);//assume AllLoader now has logic to watch the loader for % complete
loader.load(request);
addChild(allLoader);
}
protected function switchLoaders(e:Event):void {
removeChild(allLoader);
addChild(loader);
}
}
Then just create and position one of these for each one of your albums.
With the code below I created some imgMcA and some imgMcB then I loaded images into imgMcA ones. ImgMcBs have no image at that moment. So if one of imgMcA is clicked the image should be transferred to one of the empty imgMcBs (may be randomly) and if imgmcB is clicked later the image should move back to its imgMcA back. I could not find out how I can accomplish this.
Thanks in advance
function imageList(mcname, img, index){
var imgMcA:MovieClip=new MovieClip();
imgMcA.graphics.beginFill(0x000000);
imgMcA.graphics.drawRect(0,0,imgWidth,imgHeight);
imgMcA.graphics.endFill();
imgMcA.name=lemma;
imgMcA.addEventListener(MouseEvent.CLICK, moveImage);
var imgMcB:MovieClip=new MovieClip();
imgMcB.graphics.beginFill(0x000000);
imgMcB.graphics.drawRect(0,0,imgWidth,imgHeight);
imgMcB.graphics.endFill();
imgMcB.name=index;
addChild(imgMcB);
var imgLoader:Loader = new Loader();
imgLoader.load(new URLRequest(img));
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, changeProperties);
imgLoader.mouseEnabled=false;
imgMcA.addChild(imgLoader);
}
function moveImage(evnt:MouseEvent){
}
You could linked mcA & mcB by adding them to the same parent.
function createBlock():void
{
var imgLoader:Loader = new Loader();
//add the loading code here...
var mcA:Sprite = new Sprite();
var mcB:Sprite = new Sprite();
// add Click event listeners for both Mcs here...
var parent:Sprite = new Sprite();
//add Children
parent.addChild(mcA);
parent.addChild(mcB);
addChild(parent);
}
function mouseClickHandler(event:MouseEvent)
{
var dispatcher:Sprite = event.currentTarget as Sprite;
//if you added a Loader to it
if( dispatcher.numChildren > 0)
{
//retrieve the image
var img:Loader = dispatcher.getChildAt(0);
//identify the parent
var parent:Sprite = dispatcher.parent;
var index:int = parent.getChildIndex(dispatcher);
//identify the receiving MC
//of course this only works with two children!!!
if(index > 0)
var receiver:Sprite = parent.getChildAt(0) as Sprite;
else
receiver = parent.getChildAt(1) as Sprite;
//add the image to the other MC
receiver.addChild(img);
}
}
The rest is not too complicated to achieve. You will need to use a Boolean and add a TextField. If the TextField contains text, set the Boolean to true.
It may be worth looking at Classes or you could use an Object as a container for the MovieClips, the TextField and the Boolean, although a Class will give you more flexibility...
With a Class, you wouldn't have to iterate in order to find what does what. Your Click listener would look something like this:
private function mouseClickHandler(event:MouseEvent)
{
receiver.addChild( image );
if( hasText)
imageReturn();
}