actionscript 3 if array in condition - arrays

i want to ask about this code..
if (objek.dropTarget.parent.name == "book")
{
if ((objek == alif) || (objek == ba)){ //yg perlu diganti
//if (objek == objBenar){ //yg perlu diganti
objek.x = objek.dropTarget.parent.x;
objek.y = objek.dropTarget.parent.y + 50;
objek.removeEventListener(MouseEvent.MOUSE_DOWN, down);
objek.buttonMode = false;
var _loc_2:Number;
objek.scaleY = 0.4;
objek.scaleX = _loc_2;
objek.alpha = 0.6;
score+=5;
scorebox.text = "Score: " + score;
}
else {
objek.x = objek.dropTarget.parent.x;
objek.y = objek.dropTarget.parent.y + 50;
objek.removeEventListener(MouseEvent.MOUSE_DOWN, down);
objek.buttonMode = false;
var _loc_2:Number;
objek.scaleY = 0.4;
objek.scaleX = _loc_2;
objek.alpha = 0.6;
score-=2;
scorebox.text = "Score: " + score;}
}
}
i have movieclip alif, ba, and dal..this three can be dragged to movieclip named "book" and the score will change.
if i drag alif and ba movieclip to book, score will increase..
if i drag dal movieclip to book score will decrease..
how if i want to make the movieclip alif and ba of an array??and how to write the condition??
help pliss :(

I'm not sure if I understand, but do you want to have an array containing alif and ba and then check if the movieclip is in that array? This is how you would do that:
var scoreIncreasers:Array = [alif, ba];
var isScoreIncreaser:Boolean = (scoreIncreasers.indexOf(objeck) !== -1);
if(isScoreIncreaser) {
// Increase score
}
Edit:
Based on your comment, I think this is what you want:
var objBener:Array = [alif, ba];
if(objBener.indexOf(objek) !== -1) {
//yg perlu diganti
}

Related

(Processing) Removing Previously Used Object in Array

Sorry for the horrible wording of the title. I'm creating a game of "War" in Processing for my Programming class. I need to change my code so that each card that is used is removed from the deck/array. I stumbled upon some posts and Google results mentioning "ArrayList", but I'm still sort of clueless.
The following code displays two separate, random cards and displays two new random cards when the mouse is clicked.
(First Tab 'War')
void draw(){
image(card[imageIndex],40,150);
image(card2[imageIndex2],340,150);
}
void mousePressed(){
imageIndex = int(random(card.length));
imageIndex2 = int(random(card2.length));
}
(Second Tab 'Card')
PImage[] card = new PImage[13];
PImage[] card2 = new PImage[13];
int imageIndex = int(random(0,12)),
imageIndex2 = int(random(0,12));
void setup(){
size(500,500);
card[0] = loadImage("2_of_clubs.jpg");
card[1] = loadImage("3_of_clubs.jpg");
card[2] = loadImage("4_of_clubs.jpg");
card[3] = loadImage("5_of_clubs.jpg");
card[4] = loadImage("6_of_clubs.jpg");
card[5] = loadImage("7_of_clubs.jpg");
card[6] = loadImage("8_of_clubs.jpg");
card[7] = loadImage("9_of_clubs.jpg");
card[8] = loadImage("10_of_clubs.jpg");
card[9] = loadImage("jack_of_clubs.jpg");
card[10] = loadImage("queen_of_clubs.jpg");
card[11] = loadImage("king_of_clubs.jpg");
card[12] = loadImage("ace_of_clubs.jpg");
card2[0] = loadImage("2_of_clubs.jpg");
card2[1] = loadImage("3_of_clubs.jpg");
card2[2] = loadImage("4_of_clubs.jpg");
card2[3] = loadImage("5_of_clubs.jpg");
card2[4] = loadImage("6_of_clubs.jpg");
card2[5] = loadImage("7_of_clubs.jpg");
card2[6] = loadImage("8_of_clubs.jpg");
card2[7] = loadImage("9_of_clubs.jpg");
card2[8] = loadImage("10_of_clubs.jpg");
card2[9] = loadImage("jack_of_clubs.jpg");
card2[10] = loadImage("queen_of_clubs.jpg");
card2[11] = loadImage("king_of_clubs.jpg");
card2[12] = loadImage("ace_of_clubs.jpg");
}
Using ArrayList would look more or less like:
// gonna use strings instead of images
// just to show the idea. I don't have all this images...
ArrayList<String> card = new ArrayList<String>();
ArrayList<String> card2;
int imageIndex, imageIndex2;
String display1, display2;
void setup() {
size(500, 500);
card.add("2_of_clubs.jpg");
card.add("3_of_clubs.jpg");
card.add("4_of_clubs.jpg");
card.add("5_of_clubs.jpg");
card.add("6_of_clubs.jpg");
card.add("7_of_clubs.jpg");
card.add("8_of_clubs.jpg");
card.add("9_of_clubs.jpg");
card.add("10_of_clubs.jpg");
card.add("jack_of_clubs.jpg");
card.add("queen_of_clubs.jpg");
card.add("king_of_clubs.jpg");
card.add("ace_of_clubs.jpg");
card2 = new ArrayList<String>(card);
imageIndex = int(random(card.size()));
imageIndex2 = int(random(card2.size()));
display1 = card.get(imageIndex);
display2 = card2.get(imageIndex2);
card.remove(imageIndex);
card2.remove(imageIndex2);
println("\ncard draw from card : "+ display1);
println("card draw from card2: "+ display2 + "\n");
}
void draw() {
}
void mousePressed() {
if (card.size() > 0) {
imageIndex = int(random(card.size()));
imageIndex2 = int(random(card2.size()));
display1 = card.get(imageIndex);
display2 = card2.get(imageIndex2);
card.remove(imageIndex);
card2.remove(imageIndex2);
println("\ncard draw from card : "+ display1);
println("card draw from card2: "+ display2 + "\n");
} else {
println("The deck is empty...");
}
}
if you have to use arrays then you would have to do something similar to the following code:
PImage[] removeCardFromDeck(PImage deck, int index){
PImage[] newdeck = new PImage[deck.length -1];
int count=0;
for(int i =0 ; i<newdeck.length;i++){
if(count==index) count++;
newdeck[i] = deck[count];
count++;
}
return newdeck;
}
but for this task it is better to use ArrayLists.

accessing array elements in another frame as3

I have created an Array in frame 1 and dynamically create a list of movieclips with it , and I want to create the same Array in frame 3 and those movieclips again if something is true or false.is it possible ? because when I'm trying to do this , I will get this error :
1151: A conflict exists with definition i in namespace internal.
here is my code at frame 1 :
stop();
import flash.display.MovieClip;
var p_x:uint = 90;
var p_y:uint = 108;
var my_list:String = "Games,Videos, Medias,Images,Photos,Personal Photos,Social Media,Private,Social,None,Names,Families";
var myListString:Array = my_list.split(",");
var myArray:Array=new Array ();
var listObject = 1;
for (var i:uint=0; i<12; i++)
{
var myItemList:mrb=new mrb();
myItemList.x = p_x;
myItemList.y = p_y + 80;
myItemList.y = (p_y + (listObject * 65));
myArray.push(myItemList);
myItemList.txt.text = i.toString();
myItemList.txt.text = myListString[i].toString();
myItemList.name = "item"+i;
addChild(myItemList) as MovieClip ;
listObject++;
}
and here is code at frame 3 :
var tmpCurFrame:int = currentFrame;
this.addEventListener(Event.ENTER_FRAME, handleUpdate)
function handleUpdate(e:Event):void {
if (tmpCurFrame != currentFrame) {
this.removeEventListener(Event.ENTER_FRAME, handleUpdate);
return;
}
if (so.data.fav1 != undefined)
{
if ( so.data.fav1 == "on")
{
for (var i:int = 0; i < myListString.length;)
{ if (myListString[i].indexOf() > -1)
{
var myRectangle:mrb=new mrb();
trace("found it at index: " + i);
myRectangle.x = p_x;
myRectangle.y = (p_y + (findobject * 50));
trace('p_y+80 =' + (p_y+(findobject*80)) + 'p_x = ' + p_x );
myArray.push(myRectangle);
myRectangle.txt.text = myListString[i].toString();
trace(my_array2[i].toString() );
addChild(myRectangle);
}
}
}
}
else
{
fav_1.fav_on.visible=true;
}
}
This error message simply means that you use twice the same variable i. You just have to give them differents names.

Actionscript 3: Trying to create a randomized array

im trying to create a randomized array that will change the position of my pictures(in the tilelist) each time the application is launched. Hope you understand what im looking for, and i dont really understand how to link code correctly here :/
I think its easier simply copying into flash and view from there
thanks :)
Here's my code:
flash.events.MouseEvent;
btn_back.addEventListener(MouseEvent.CLICK, ftilbake);
function ftilbake(evt:MouseEvent)
{
gotoAndStop(1);
}
var heroArray:Array = new Array();
var randomizeArray:Array = new Array();
createArrays()
function createArrays()
{
heroArray[0] = new Array("Rumble","Garen","Lulu","Corki","Warwick");
heroArray[1] = new Array("Bilder/Champions/Rumble.jpg","Bilder/Champions/Garen.jpg","Bilder/Champions/Lulu.jpg","Bilder/Champions/Corki.jpg","Bilder/Champions/Warwick.jpg");
heroArray[2] = new Array("Bilder/Champions/Rumble1.jpg","Bilder/Champions/Garen1.jpg","Bilder/Champions/Lulu1.jpg","Bilder/Champions/Corki1.jpg","Bilder/Champions/Warwick1.jpg");
heroArray[3] = new Array("the Mechanized Menace","the Might of Demacia","the Fae Sorceress","the Daring Bombardier","the Blood Hunter");
heroArray[4] = new Array(0,0,0,0,0);
heroArray[5] = new Array("Rumble.wav","Garen.wav","Lulu.wav","Corki.wav","Warwick.wav");
randomizeArray[0] = new Array();
randomizeArray[1] = new Array();
randomizeArray[2] = new Array();
randomizeArray[3] = new Array();
randomizeArray[4] = new Array();
//randomizing the positions in the array(?)
var randomPos:int = 0;
for (var i:int = 0; i < heroArray.length; i++)
{
randomPos = int(Math.random() * heroArray[0].length);
while (randomizeArray[randomPos][0] != null)
{
randomPos = int(Math.random() * heroArray.length);
}
}
}
var totalKlikk:int = 0;
for (var teller1:int = 0; teller1 <heroArray[0].length; teller1++)
{
leagueChamps.addItem({label:heroArray[0][teller1], source:heroArray[1][teller1]});
}
leagueChamps.columnWidth = 80;
leagueChamps.rowHeight = 80;
leagueChamps.columnCount = 5;
leagueChamps.rowCount = 1;
leagueChamps.direction = "horizontal";
leagueChamps.addEventListener(MouseEvent.CLICK, bildeKlikk);
function bildeKlikk(evt:MouseEvent)
{
var element:Object = leagueChamps.selectedItem;
var fil:String = element.source;
txtChHero.visible = false;
totalKlikk++;
if (totalKlikk <11)
{
for (teller1 = 0; teller1 <heroArray[0].length; teller1++)
{
if (heroArray[1][teller1] == fil)
{
heroArray[4][teller1]++;
if (heroArray[4][teller1] == 1)
{
txtBox1.visible = true;
txtBox2.visible = true;
leagueShow.source = heroArray[2][teller1];
txtBox1.text = heroArray[0][teller1];
txtBox2.text = heroArray[3][teller1];
}
if (heroArray[4][teller1] == 2)
{
txtBox1.visible = true;
txtBox2.visible = true;
leagueShow.source = heroArray[2][teller1];
txtBox1.text = heroArray[0][teller1];
txtBox2.text = heroArray[3][teller1];
heroArray[5][teller1].play();
}
if (heroArray[4][teller1] == 3)
{
bildeKlikk3();
}
}
}
}
else
{
txtChHero.visible = true;
txtChHero.text = "Du har klikket følgende mange ganger på de forskjellige bildene:";
txtH1.text = heroArray[4][0]
txtH2.text = heroArray[4][1]
txtH3.text = heroArray[4][2]
txtH4.text = heroArray[4][3]
txtH5.text = heroArray[4][4]
txtBox1.visible = false;
txtBox2.visible = false;
leagueShow.visible = false;
}
}
function bildeKlikk3()
{
txtBox1.visible = true;
txtBox2.visible = true;
leagueShow.source = heroArray[2][teller1];
txtBox2.text = "Ikke mer informasjon";
}
txtBox2.visible = false;
txtBox1.visible = false;
Array randomization is something which comes up very frequently in all my projects so I ended up creating a static method in my Array utility class for it.
It uses the Fisher–Yates shuffle which is supposed to be the most unbiased (and efficient?) algorithm for shuffling the content of an array. There could be faster ways of doing it (like using the array.sortOn() method, but I am not sure how unbiased a result they get compared to this one.)
The shuffle method:
/**
* shuffle the given array
* #param array
* #return
*/
public static function shuffle(array:Array):Array
{
var index :int;
var item :*;
var limit :int = array.length as int;
for (var i:int = limit-1; i >= 0 ; --i)
{
index = Math.floor(Math.random() * (i + 1));
item = array[index];
array[index] = array[i];
array[i] = item;
}
return array;
}
Example:
var myArray:Array = new Array("Red","Orange","Yellow","Green","Blue");
myArray = ArrayUtils.shuffle(myArray);
where ArrayUtils is the name of the Array Utility class I use. You can simply use the function directly if you don't want to use a utility class of course.
Try this
while (heroArray.length > 0) {
randomizeArray.push(heroArray.splice(Math.round(Math.random() * (heroArray.length - 1)), 1)[0]);
}
Just instatiate randomizeArray though, and don't fill it with empty Arrays like in ur source!
I recommend creating a single object to hold related data, and using a single Array/Vector of that object type.
To answer your question, randomizing an array is fairly easy to do with array.sort() and a random selection function. This method can also be used to randomize any array. you don't need to splice arrays or iterate either.
function sortOnRandom(a:Object, b:Object):Number{
if(Math.random() > 0.5){
return 1;
}else{
return -1;
}
}
myArray.sort(sortOnRandom);

AS3 - Remove spaces from an array for word game

I'm building a word search game using the following AS3 code. My problem is I need to have spaces in my array of words, so that I can have things like states names, but I need the spaces removed before the words go into the puzzle.
The other concern is also that when a person selects a word from the puzzle will it still match the word in the list even though the word in the list still has a space.
I've struggled with this for a few days now and could use some help.
I've pasted all appropriate code below, I believe. Thanks.
Rich
// words and grid
private var wordList:Array;
private var usedWords:Array;
private var grid:Array;
// sprites
private var letterSprites:Sprite;
private var wordsSprite:Sprite;
wordList = ("New York,New Jersey,South Carolina,North Carolina").split(",");
// set up the sprites
gameSprite = new Sprite();
addChild(gameSprite);
letterSprites = new Sprite();
gameSprite.addChild(letterSprites);
wordsSprite = new Sprite();
gameSprite.addChild(wordsSprite);
// array of letters
var letters:Array = placeLetters();
// create word list fields and sprites
for(var i:int=0;i<usedWords.length;i++) {
var newWord:TextField = new TextField();
newWord.defaultTextFormat = letterFormatForList;
if(i < 20){ // first list
newWord.x = listXposition;
newWord.y = i*spacingForList+listYposition;
} else { // second list
newWord.x = listXposition + 130;
newWord.y = i*spacingForList+listYposition - (20 * 19);
}
newWord.width = 135;
newWord.height = spacingForList;
newWord.text = usedWords[i];
newWord.selectable = false;
wordsSprite.addChild(newWord);
}
// set game state
dragMode = "none";
numFound = 0;
}
// place the words in a grid of letters
public function placeLetters():Array {
// create empty grid
var letters:Array = new Array();
for(var x:int=0;x<puzzleSize;x++) {
letters[x] = new Array();
for(var y:int=0;y<puzzleSize;y++) {
letters[x][y] = "*";
}
}
// make copy of word list
var wordListCopy:Array = wordList.concat();
usedWords = new Array();
// make 1000 attempts to add words
var repeatTimes:int = 1000;
repeatLoop:while (wordListCopy.length > wordsLeft) {
if (repeatTimes-- <= 0) break;
// pick a random word, location and direction
var wordNum:int = Math.floor(Math.random()*wordListCopy.length);
var word:String = wordListCopy[wordNum].toUpperCase();
x = Math.floor(Math.random()*puzzleSize);
y = Math.floor(Math.random()*puzzleSize);
var dx:int = Math.floor(Math.random()*3)-1;
var dy:int = Math.floor(Math.random()*3)-1;
if ((dx == 0) && (dy == 0)) continue repeatLoop;
// check each spot in grid to see if word fits
letterLoop:for (var j:int=0;j<word.length;j++) {
if ((x+dx*j < 0) || (y+dy*j < 0) || (x+dx*j >= puzzleSize) || (y+dy*j >= puzzleSize)) continue repeatLoop;
var thisLetter:String = letters[x+dx*j][y+dy*j];
if ((thisLetter != "*") && (thisLetter != word.charAt(j))) continue repeatLoop;
}
// insert word into grid
insertLoop:for (j=0;j<word.length;j++) {
letters[x+dx*j][y+dy*j] = word.charAt(j);
}
// remove word from list
wordListCopy.splice(wordNum,1);
usedWords.push(word);
}
// fill rest of grid with random letters
for(x=0;x<puzzleSize;x++) {
for(y=0;y<puzzleSize;y++) {
if (letters[x][y] == "*") {
letters[x][y] = String.fromCharCode(65+Math.floor(Math.random()*26));
}
}
}
return letters;
}
// player clicks down on a letter to start
public function clickLetter(event:MouseEvent) {
var letter:String = event.currentTarget.getChildAt(0).text;
startPoint = findGridPoint(event.currentTarget);
dragMode = "drag";
}
// player dragging over letters
public function overLetter(event:MouseEvent) {
if (dragMode == "drag") {
endPoint = findGridPoint(event.currentTarget);
// if valid range, show outline
outlineSprite.graphics.clear();
if (isValidRange(startPoint,endPoint)) {
drawOutline(outlineSprite,startPoint,endPoint,0xCCCCCC);
}
}
}
// mouse released
public function mouseRelease(event:MouseEvent) {
if (dragMode == "drag") {
dragMode = "none";
outlineSprite.graphics.clear();
// get word and check it
if (isValidRange(startPoint,endPoint)) {
var word = getSelectedWord();
checkWord(word);
}
}
}
// when a letter is clicked, find and return the x and y location
public function findGridPoint(letterSprite:Object):Point {
// loop through all sprites and find this one
for(var x:int=0;x<puzzleSize;x++) {
for(var y:int=0;y<puzzleSize;y++) {
if (grid[x][y] == letterSprite) {
return new Point(x,y);
}
}
}
return null;
}
// determine if range is in the same row, column, or a 45 degree diagonal
public function isValidRange(p1,p2:Point):Boolean {
if (p1.x == p2.x) return true;
if (p1.y == p2.y) return true;
if (Math.abs(p2.x-p1.x) == Math.abs(p2.y-p1.y)) return true;
return false;
}
// draw a thick line from one location to another
public function drawOutline(s:Sprite,p1,p2:Point,c:Number) {
var off:Point = new Point(offset.x+spacing/2, offset.y+spacing/2);
s.graphics.lineStyle(outlineSize,c);
s.graphics.moveTo(p1.x*spacing+off.x ,p1.y*spacing+off.y-3);
s.graphics.lineTo(p2.x*spacing+off.x ,p2.y*spacing+off.y-3);
}
// find selected letters based on start and end points
public function getSelectedWord():String {
// determine dx and dy of selection, and word length
var dx = endPoint.x-startPoint.x;
var dy = endPoint.y-startPoint.y;
var wordLength:Number = Math.max(Math.abs(dx),Math.abs(dy))+1;
// get each character of selection
var word:String = "";
for(var i:int=0;i<wordLength;i++) {
var x = startPoint.x;
if (dx < 0) x -= i;
if (dx > 0) x += i;
var y = startPoint.y;
if (dy < 0) y -= i;
if (dy > 0) y += i;
word += grid[x][y].getChildAt(0).text;
}
return word;
}
// check word against word list
public function checkWord(word:String) {
// loop through words
for(var i:int=0;i<usedWords.length;i++) {
// compare word
if (word == usedWords[i].toUpperCase()) {
foundWord(word);
}
// compare word reversed
var reverseWord:String = word.split("").reverse().join("");
if (reverseWord == usedWords[i].toUpperCase()) {
foundWord(reverseWord);
}
}
}
// word found, remove from list, make outline permanent
public function foundWord(word:String) {
sndSuccess=new success_sound();
sndSuccessChannel=sndSuccess.play(200);
so.data.totalWordsFound = so.data.totalWordsFound + 1;
so.flush();
// draw outline in permanent sprite
drawOutline(oldOutlineSprite,startPoint,endPoint,0xDDDDDD);
// find text field and set it to gray
for(var i:int=0;i<wordsSprite.numChildren;i++) {
if (TextField(wordsSprite.getChildAt(i)).text.toUpperCase() == word) {
TextField(wordsSprite.getChildAt(i)).textColor = 0x777777;
}
}
// see if all have been found
numFound++;
if (numFound == usedWords.length) {
if (so.data.difficulty == "Easy") {
so.data.easyWon = so.data.easyWon + 1;
}
if (so.data.difficulty == "Medium") {
so.data.mediumWon = so.data.mediumWon + 1;
}
if (so.data.difficulty == "Hard") {
so.data.hardWon = so.data.hardWon + 1;
}
so.flush();
endGame();
}
}
I'm hesitant to post an answer as I'm not really sure what's going on, but hopefully this info will help:
Keep your words in the arrays with spaces, that's a good idea. When you want to check against the words in your game, just convert both words to the same format using a function. eg:
var wordList:Array = ("New York,New Jersey,South Carolina,North Carolina").split(",");
var selectedWord:String = "NEWYORK";
// minWord converts all words to the same format of no spaces and all lower case.
function minWord(word:String):String {
return word.replace(/\s/g, "").toLowerCase();
}
// this loop checks all the words from your array against the selectedWord.
for each(var word:String in wordList) {
trace(minWord(word) + " == " + minWord(selectedWord) + "; ", minWord(word) == minWord(selectedWord));
}
Hope that helps!

Dynamically populate Text Fields in Flash (AS3)

I am trying to figure out how to dynamically populate textfields in Flash. The text in the fields will either say ON or OFF based on the value of bstatus.
var bstatus will either have a value of 0 or 1
I have the following textfields listed below.
I'm not sure if the syntax is correct, but I was thinking that the text fields would be in an array, and I would create a for loop--that will go through the array in order to have the fields populated.
var textFields:Array = new Array();
textFields[0] = compTxt.text;
textFields[1] = bathLightTxt.text;
textFields[2] = computerLightTxt.text;
textFields[3] = kitchenLight.text;
textFields[4] = livingLightTxt.text;
textFields[5] = descLightTxt.text;
textFields[6] = laundryLightTxt.text;
textFields[3] = ovenTxt.text;
textFields[8] = tvTxt.text;
textFields[9] = washerTxt.text;
I'm thinking that that the textFields Array will go inside a function called populateFields()
// function populateFields ------------------------------------------------------------------
function populateFields(bstatus:int)
{
var displayText:String="";
var textFields:Array = new Array();
textFields[0] = compTxt.text;
textFields[1] = bathLightTxt.text;
textFields[2] = computerLightTxt.text;
textFields[3] = kitchenLight.text;
textFields[4] = livingLightTxt.text;
textFields[5] = descLightTxt.text;
textFields[6] = laundryLightTxt.text;
textFields[3] = ovenTxt.text;
textFields[8] = tvTxt.text;
textFields[9] = washerTxt.text;
if (bstatus == 0) {
// textfield will say OFF
displayText = "OFF";
} else if (bstatus == 1) {
// textfield will say ON
displayText = "ON";
}
/*
for (var i:int=0;i<textFields.length;i++)
{
// do something
}
*/
}
Entire Code:
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.events.EventDispatcher; //event dispatcher
public class House extends MovieClip
{
// List Objects inside Treehouse here....
//private var comp:MovieClip; // comp is a property of TreeHouse
//private var light:MovieClip;
//var comp:HouseObjects = new HouseObjects(); //do this inside another class
var HouseObjects:Array = new Array(); // creates HouseObjects array
var onList:Array = [];
var obj_num:int = 10;
var power:int; // holds value of individual House Objects
var bstate:int; // 0 or 1 (ON or OFF)
var bstatus:int;
var userInput:int; // stores user data (of selected data); holds value of e.currentTarget.power
var currentPower:int; // stores current power
//var objName:String;
var objSelect:Object;
// Constructor--------------------------------------------------------------------
public function House()
{
var currentPower:int = 0;
HouseObjects[0] = new Comp();
HouseObjects[1] = new Light(); // bathroom light
HouseObjects[2] = new LightB(); // computer area light
HouseObjects[3] = new LightC(); // kitchen light
HouseObjects[4] = new LightD(); // living room light
HouseObjects[5] = new LightE(); // description light
HouseObjects[6] = new LightF(); // laundry room light
HouseObjects[7] = new Oven();
HouseObjects[8] = new Tv();
HouseObjects[9] = new Washer();
//HouseObjects[10] = new Car();
//onList.push(objName);
//trace(objName);
//onList.push(HouseObjects[1]);
trace("Tracing onList Array: " + onList);
// list properties of the objects -----------------------------------------------------------------
HouseObjects[0].power = 2; // amount of power
HouseObjects[0].name = "comp";
//comp.bstate = 0; // button state
HouseObjects[1].power = 1; // amount of power
HouseObjects[1].name = "light";
HouseObjects[2].power = 1; // amount of power
HouseObjects[2].name = "lightB";
HouseObjects[3].power = 1; // amount of power
HouseObjects[3].name = "lightC";
HouseObjects[4].power = 1; // amount of power
HouseObjects[4].name = "lightD";
HouseObjects[5].power = 1; // amount of power
HouseObjects[5].name = "lightE";
HouseObjects[6].power = 1; // amount of power
HouseObjects[6].name = "lightF";
HouseObjects[7].power = 3; // amount of power
HouseObjects[7].name = "oven";
HouseObjects[8].power = 4; // amount of power
HouseObjects[8].name = "tv";
HouseObjects[9].power = 5; // amount of power
HouseObjects[9].name = "washer";
//HouseObjects[9].power = 6; // amount of power
//HouseObjects[9].name = "car";
// end of list properties of the house objects -----------------------------------------------------
for (var i:int=0;i<obj_num;i++)
{
HouseObjects[i].buttonMode = true;
//add event listeners -- listens to functions that are called
HouseObjects[i].addEventListener(MouseEvent.MOUSE_OVER, rolloverToggle);
HouseObjects[i].addEventListener(MouseEvent.MOUSE_OUT, rolloutToggle);
HouseObjects[i].addEventListener(MouseEvent.CLICK, toggleClick);
HouseObjects[i].addEventListener(MouseEvent.CLICK, toggleClick);
HouseObjects[i].bstate = 0;
stage.addChild(HouseObjects[i]); // add House Objects to stage ------------------------------
}// end of for loop ------------------------------------------------------------------------
trace("tracing...");
//computer's position
HouseObjects[0].x = 585;
HouseObjects[0].y = 233;
//bathroom light's position
HouseObjects[1].x = 340;
HouseObjects[1].y = 161;
//computer lightB's position
HouseObjects[2].x = 579;
HouseObjects[2].y = 158;
//computer lightC's position
HouseObjects[3].x = 316;
HouseObjects[3].y = 368;
//computer lightD's position
HouseObjects[4].x = 657;
HouseObjects[4].y = 367;
//computer lightE's position
HouseObjects[5].x = 517;
HouseObjects[5].y = 549;
//computer lightF's position
HouseObjects[6].x = 531;
HouseObjects[6].y = 1000;
//oven's position
HouseObjects[7].x = 380;
HouseObjects[7].y = 449;
//tv's position
HouseObjects[8].x = 543;
HouseObjects[8].y = 423;
//washer's position
HouseObjects[9].x = 637;
HouseObjects[9].y = 1155;
} // end of Constructor -----------------------------------------------------------
// function rollOver --------------------------------------------------------------
function rolloverToggle(e:MouseEvent) {
if (e.currentTarget.currentFrame == 1)
e.currentTarget.gotoAndStop(2);
if (e.currentTarget.currentFrame == 3)
e.currentTarget.gotoAndStop(4);
}
// function rollOut -----------------------------------------------------------------
function rolloutToggle(e:MouseEvent) {
if (e.currentTarget.currentFrame == 2)
e.currentTarget.gotoAndStop(1);
if (e.currentTarget.currentFrame == 4)
e.currentTarget.gotoAndStop(3);
}
// function toggleClick-------------------------------------------------------------
function toggleClick(e:MouseEvent) {
// On MouseEvent gotoAndStop(Frame Number)
if (e.currentTarget.currentFrame == 2)
{
e.currentTarget.gotoAndStop(3);
e.currentTarget.bstate = 1;
}
if (e.currentTarget.currentFrame == 4)
{
e.currentTarget.gotoAndStop(1);
e.currentTarget.bstate = 0;
}
// trace statements -------------------------------------------------------
//trace("movieClip Instance Name = " + e.currentTarget); // [object Comp]
//trace(houseArray[e.currentTarget.name]); // comp
trace("using currentTarget: " + e.currentTarget.name); // comp
//trace("powerData: " + powerData); // power of user data
//trace("houseArray: " + houseArray[0]); // the 0 index of house array
// trace(e.currentTarget.power); // currentTarget's power************
//trace ("bstate in click function: " + e.currentTarget.bstate);
//objName = e.currentTarget.name;
trace("target: " + e.currentTarget);
bstatus = e.currentTarget.bstate;
userInput = e.currentTarget.power;
objSelect = e.currentTarget;
trace("objSelect: " + objSelect);
// end of trace statements -------------------------------------------------
calcPower(userInput, bstatus);
//trace("i am bstatus: " + bstatus);
//trace("i am power: " + userInput);
populateFields(bstatus);
sendPhp();
//trackItems(objSelect, bstatus);
} // end of function toggleClick ----------------------------------------------------
// function calcPower ------------------------------------------------------------------
function calcPower(userInput:int, bstatus:int):void
{
//trace("i arrived");
//trace("power: " + userInput + " and " + "bstate: " + bstatus);
if (bstatus == 0) {
trace("i have been clicked OFF");
currentPower -= userInput; // if OFF then minus
trace("currentPower: " + currentPower);
} else if (bstatus == 1) {
trace("i have been clicked ON");
currentPower += userInput; // if OFF then minus
trace("currentPower: " + currentPower);
}
}
// function populateFields ------------------------------------------------------------------
function populateFields(bstatus:int)
{
var displayText:String="";
var textFields:Array = new Array();
textFields[0] = compTxt.text;
textFields[1] = bathLightTxt.text;
textFields[2] = computerLightTxt.text;
textFields[3] = kitchenLight.text;
textFields[4] = livingLightTxt.text;
textFields[5] = descLightTxt.text;
textFields[6] = laundryLightTxt.text;
textFields[3] = ovenTxt.text;
textFields[8] = tvTxt.text;
textFields[9] = WasherTxt.text;
if (bstatus == 0) {
// textfield will say OFF
} else if (bstatus == 1) {
// textfield will say ON
}
/*
for (var i:int=0;i<textFields.length;i++)
{
// do something
}
*/
}
// function pwrPercentage ------------------------------------------------------------------
/*function pwrPercentage()
{
}
*/
// function trackItems ------------------------------------------------------------------
function trackItems(objSelect:Object, bstatus:int):void
{
trace("i arrived in trackItems");
trace("tracing objSelect in function trackItems: " + objSelect);
//trace("tracing Array onList :" + onList);
//trace("power: " + userInput + " and " + "bstate: " + bstatus);
if (bstatus == 0) {
//onList.removeItemAt(onList.getItemIndex(objSelect));
// remove from ON list (array) pop
// call function removeArrayItem
removeArrayItem(objSelect);
} else if (bstatus == 1) {
//trace("adding items to list");
onList.push(objSelect);
//add to ON list (array) push
}
trace("Array:" + onList);
//return array .... only have one array...contain objects that are ONLY ON
}
// function removeArrayItem ------------------------------------------------------------------
function removeArrayItem(objSelect:Object):void
{
var arrayLength:int = onList.length;
// Searches item in array
for (var i:int=0; i<arrayLength; i++)
{
// Finds item and removes it
if (onList[i] == objSelect)
{
onList.splice(i, 1);
///*/**/*/trace("Item Removed: " + onList[i]);
trace("Array Updated: " + onList);
}
}
}
// function frameloop ------------------------------------------------------------------
/* function frameloop(e:Event)
{
}
*/
// function sendPhp ------------------------------------------------------------------
function sendPhp(e:MouseEvent):void
{
// send vars to php
var request:URLRequest = new URLRequest("write_xml.php"); // the php file to send data to
var variables:URLVariables = new URLVariables(); // create an array of POST vars
variables['bathLight'] = compTxt.text;
variables['bathLight'] = bathLightTxt.text;
variables['computer'] = computerLightTxt.text;
variables['kitchenLight'] = kitchenLight.text;
variables['livingLight'] = livingLightTxt.text;
variables['descLight'] = descLightTxt.text;
variables['laundryLight'] = laundryLightTxt.text;
variables['oven'] = ovenTxt.text;
variables['tv'] = tvTxt.text;
variables['washer'] = washerTxt.text;
request.data = variables; // send the vars to the data property of the requested url (our php file)
request.method = URLRequestMethod.POST; // use POST as the send method
try
{
var sender:URLLoader = new URLLoader();
sender.load(request); // load the php file and send it the variable data
navigateToURL(new URLRequest("vars.xml"), '_blank'); //show me the xml
}
catch (e:Error)
{
trace(e); // trace error if there is a problem
}
}
// function called when user clicks on update button-----------------------------------
/*function updateStage():void
{
for (var i:int = 0; i<=onList.length;i++) {
addChild(onList[i]);
}
}*/
} //end of class
} // end of package
You will be better off keeping track of the reference to your textboxes in order to populate them afterwards:
var textFields:Array = new Array();
textFields[0] = compTxt;
textFields[1] = bathLightTxt;
textFields[2] = computerLightTxt;
textFields[3] = kitchenLight;
textFields[4] = livingLightTxt;
textFields[5] = descLightTxt;
textFields[6] = laundryLightTxt;
textFields[3] = ovenTxt;
textFields[8] = tvTxt;
textFields[9] = washerTxt;
I tried it out this way:
import fl.controls.*;
var textFields:Array = new Array(9);
textFields[0] = new TextInput();
textFields[1] = new TextInput();
textFields[2] = new TextInput();
textFields[3] = new TextInput();
textFields[4] = new TextInput();
textFields[5] = new TextInput();
textFields[6] = new TextInput();
textFields[7] = new TextInput();
textFields[8] = new TextInput();
textFields[9] = new TextInput();
var i:uint = 0;
for(i = 0; i < textFields.length; ++i){
textFields[i].text = "Set text at " + i;
trace(textFields[i].text);
}

Resources