1120: Access of undefined property shuffledArray - actionscript-3

Please can you help me out I am new to as3 and I am trying to create a shuffled deck using the Fisher-Yates Algorithm. When I run the code with ctrl-enter it compiles with no errors but when I try to output it with trace(); it comes back with:
Scene 1, Layer 'actions', Frame 1, Line 6 1120: Access of undefined property shuffledArray.
Like I said I am new to this and it will be me doing something very stupid but all the same i'm stuck.
Here is the code
package src.CardDeck
{
public class CardDeck
{
public var allCards:Array = [];
public var cardNames:Array;
public var cardValues:Array;
public var gameType:String;
public var drawnCards:uint = 0;
public function CardDeck(game:String)
{
gameType = game;
cardNames = ["Ace","Two","Three",
"Four","Five","Six",
"Seven","Eight","Nine",
"Ten","Jack","Queen","King"];
if(gameType == "texasholdem")
{
cardValues = [1,2,3,4,5,6,7,8,9,10,10,10,10];
}
makeSuit("Spade");
makeSuit("Heart");
makeSuit("Diamond");
makeSuit("Club");
}
function makeSuit(suitString:String):void
{
var card:Object;
for(var i:uint = 0; i < cardNames.length; i++)
{
card = {};
card.cardType = suitString;
card.cardName = cardNames[i];
card.cardValue = cardValues[i];
card.isDrawn = false;
allCards.push(card);
}
}
public function shuffleFisherYates():Array
{
var shuffledArray:Array = [];
var randomCardIndex: int;
do
{
randomCardIndex = Math.floor(Math.random()* allCards.length);
shuffledArray.push(allCards[randomCardIndex]); // add to mix
allCards.splice(randomCardIndex,1); // remove from deck
}while(allCards.length); // Meaning while allCards.length != 0
return shuffledArray;
}
}
}
and here is the .fla actions layer
import src.CardDeck.CardDeck;
var deck:CardDeck = new CardDeck("texasholdem");
trace(shuffledArray);
I know its probably something silly but i'm struggling.
Thanks in advance!
Paul

var deck:CardDeck = new CardDeck("texasholdem");
trace(shuffledArray);
This doesn't work because shuffledArray isn't defined there.
Try :
var deck:CardDeck = new CardDeck("texasholdem");
var array:Array = deck.shuffleFisherYates();
for(var i:int=0; i<array.length; i++)
{
trace(array[i].cardName);
trace(array[i].cardType);
trace(array[i].cardValue);
trace(array[i].isDrawn);
}

"shuffledArray" is a property inside of your CardDeck object. To access public methods and properties within it, you need to use the dot syntax:
trace(deck.shuffleFisherYates());
However, depending on what you are doing, you may not need to really be accessing the array directly, if your CardDeck object is meant to control the entire deck.

Related

Actionscript3 how to get the index of object clicked

I'm trying to have this hero shoot the bullet. Ex: The bullet has fire and ice type. if the hero placed is fire type then it will shoot fire bullet, if it's ice type then it will shoot ice bullet. And each bullet have each own effects and damages.
So, I've tried to get the index of hero chosen and later on the index will be used to define which bullet used by tracing (heroesArray.indexOf(heroClicked)); but the value of heroclicked is (object Hero1). so I can't use it since the array of heroesArray is [hero1,hero2]. I did splitting and joining too but it kinda messed up...
My question is how to get the String value that only contains the variable of clicked object (hero1 or hero2)? Is there any 'vocabulary' to get the variable name like getqualifiedclassname used for getting class name of an object?
Or is there any other idea to create bullet type the same as hero type without using indexOf ?
Thanks !
Here is the code :
package {
import flash.display.MovieClip
import flash.events.MouseEvent
import flash.events.Event
import flash.display.Sprite
import flash.utils.*
public class Hero {
private var heroesArray:Array;
private var heroContainer:Sprite = new Sprite;
private var hero1:MovieClip = new Hero1();
private var hero2:MovieClip = new Hero2();
private var bulletArray:Array;
private var bullet1:MovieClip = new Bullet1();
private var bullet2:MovieClip = new Bullet2();
private var moveHero:Boolean = false;
private var movingHero:MovieClip;
private var _money:Money = new Money();
private var _main:Main;
private var _enemy:Enemy = new Enemy(_main);
public function Hero(main:Main)
{ _main = main;
heroesArray = [hero1,hero2];
bulletArray = [bullet1,bullet2];
}
private function playerMoving(e:Event):void
{
if (moveHero == true)
{
movingHero.x = _main.mouseX;
movingHero.y = _main.mouseY;
}
}
private function chooseHero(e:MouseEvent):void
{
var heroClicked:MovieClip = e.currentTarget as MovieClip;
var cost:int = _main._money.money ;
if(cost >= 10 && moveHero == false)
{
_main._money.money -= 10;
_main._money.addText(_main);
moveHero = true;
var heroClass:Class = getDefinitionByName(getQualifiedClassName(heroClicked)) as Class;
movingHero = new heroClass();
heroContainer.addChild(movingHero);
movingHero.addEventListener(MouseEvent.CLICK, placeHero);
}
}
private function placeHero(e:MouseEvent):void
{
var heroClicked:MovieClip = e.currentTarget as MovieClip;
var heroRow:int = Math.floor(_main.mouseY/75);
var heroCol:int = Math.floor((_main.mouseX-10)/65);
if(heroRow>0 && heroCol>0 && heroRow<6 && heroCol<10&&
_main.field[heroRow][heroCol]==0)
{
movingHero.fireRate =75;
movingHero.recharge = 0;
movingHero.firing = false;
movingHero.heroRow = heroRow;
movingHero.x = 42+heroCol*65;
movingHero.y = 10+heroRow*75;
_main.field[heroRow][heroCol]=1;
moveHero = false;
movingHero.removeEventListener(MouseEvent.CLICK, placeHero);
}
}
public function displayHero(stage:Object):void
{
stage.addChild(heroContainer);
for (var i:int = 0; i<2;i++)
{
stage.addChild(heroesArray[i]);
heroesArray[i].x = 37;
heroesArray[i].y = 80+i*70;
heroesArray[i].width=60;
heroesArray[i].height=55;
heroesArray[i].buttonMode = true;
heroesArray[i].addEventListener(MouseEvent.CLICK, chooseHero);
heroesArray[i].addEventListener(Event.ENTER_FRAME, playerMoving);
}
}
}
}
You've pretty much got the answer right in front of you. The two heros are of classes Hero1 and Hero2, and you find the class via
var heroClass:Class = getDefinitionByName(getQualifiedClassName(heroClicked)) as Class;
All you need to do is compare heroClass to those two classes like so:
if(heroClass == Hero1)
{
...
}
else
{
...
}
Linking hero to bullet type
If you don't know, or don't want to learn classes (see my comment for an excellent tutorial) then you'll need a lookup table/Dictionary so that you can link bullet type to hero.
//Put this in your constructor after the bullet types and heroes have been declared
var bulletDict = new Dictionary();
bulletDict[hero1] = bulletTypeIce; //Note the lack of quotations around hero1 and 2
bulletDict[hero2] = bulletTypeFire;
So, to get the bullet type out:
var bulletType = bulletDict[heroClicked];

Actionscript 3 Call to a possibly undefined method

Here is the problem, the object is moved together with the clicked object. I want it to be moveable following the mouse pointer, but let the clicked object stays. so when an object is clicked, there will be 2 objects in the stage(the static and moving one).
I think I've figured it out by adding a new object to be moved. in function onClickHero I've tried movingHero = new heroes but it says "call to a possibly undefined method heroes". My question is there any other way how to make another clone of the clicked object since I made it in array? And why does movingHero = new heroes doesn't work?
I'm still amateur at classes. Sorry if it's messed up. Thanks for helping.
package {
import flash.display.MovieClip
import flash.events.MouseEvent
import flash.events.Event
import flash.display.Sprite
public class Hero {
private var heroesArray:Array;
private var heroContainer:Sprite = new Sprite;
private var hero1:MovieClip = new Hero1();
private var hero2:MovieClip = new Hero2();
private var moveHero:Boolean = false;
private var movingHero:MovieClip;
private var _money:Money = new Money();
private var _main:Main;
public function Hero(main:Main)
{ _main = main;
heroesArray = [hero1,hero2];
heroesArray.forEach(addHero);
}
public function addHero(heroes:MovieClip,index:int,array:Array):void
{
heroes.addEventListener(Event.ENTER_FRAME, playerMoving);
heroes.addEventListener(MouseEvent.CLICK, chooseHero);
}
public function playerMoving(e:Event):void
{
if (moveHero == true)
{
movingHero.x = _main.mouseX;
movingHero.y = _main.mouseY;
}
}
public function chooseHero(e:MouseEvent):void
{
var heroClicked:MovieClip = e.currentTarget as MovieClip;
var cost:int = _main._money.money ;
if(cost >= 10 && moveHero == false)
{
_main._money.money -= 10;
_main._money.addText(_main);
onClickHero(heroClicked);
moveHero = true;
}
}
public function onClickHero(heroes:MovieClip):void
{
movingHero = heroes;
heroContainer.addChild(movingHero);
}
public function displayHero(stage:Object):void
{
stage.addChild(heroContainer);
for (var i:int = 0; i<2;i++)
{
stage.addChild(heroesArray[i]);
heroesArray[i].x = 37;
heroesArray[i].y = 80+i*70;
heroesArray[i].width=60;
heroesArray[i].height=55;
heroesArray[i].buttonMode = true;
}
}
}
}
EDIT: I've tried to make movingHero = new Hero1(); but since I don't know which hero will be clicked so I can't just use Hero1 from library. and If I use movingHero = heroClicked I only get the value of hero1 which is a var from Hero1 movieclip. So, is there any way to call the movie clip from library the same as which hero was clicked in stage?
You seemingly want to clone an object while not knowing its type. If that object also containg game logic, it's not the best idea to say spawn new heroes of either type, this might make a mess of your code. But if not, you can get the exact class of the object given, and make an object of that class via the following code:
public function onClickHero(heroes:MovieClip):void
{
if (!heroes) {
trace('heroes is null!');
return;
}
var heroClass:Class = getDefinitionByName(getQualifiedClassName(heroes)) as Class;
movingHero = new heroClass(); // instantiate that class
heroContainer.addChild(movingHero);
// movingHero.startDrag(); if needed
}
Don't forget to clean up the movingHero once it's no longer needed.

Adding a dynamically created DataGrid as child or element does not work

I am trying to develop an application in AS3. What I am really trying to achieve is to have only one datagrid and having it show, you say, three different set of datas. (the real count will be changing dynamically, and it does not matter as the problem is not relevant with this) Yes, it has to be only one datagrid because of you know, I need a compact interface.
The class "Sonuc" has three properties which are string versions of inputs from constructor. A typical "Sonuc" object is something like this.
var sonuc1:Sonuc = new Sonuc(1,1,false);
//sonuc1.num = "1"
//sonuc1.type = "1"
//sonuc1.isTrue = "No"
The reason that I have informed you about "Sonuc" class is that I wanted you to know that class was not something too complicated. And x.mxml is the test mxml where I only load the class for testing purposes.
This is what I have coded so far
public class ResultInterface extends UIComponent
{
private const desiredWidth:int = 250;
private const desiredHeight:int = 150;
private const sonuc1:Sonuc = new Sonuc(1,1,false);
public var tablo:DataGrid = new DataGrid();
public var kolonArray:Array = new Array ();
public var sonucArray:Array = new Array ();
public var currentIndex:int = new int ();
public var prevButon:Button = new Button();
public var nextButon:Button = new Button();
public function ResultInterface():void
{
currentIndex = 0;
super();
tablo = new DataGrid();
width=desiredWidth+40;
height=desiredHeight+60;
this.tablo.width = desiredWidth;
this.tablo.height = desiredHeight;
this.tablo.x = 20;
this.tablo.y = 40;
prevButon.x = 10;
prevButon.y = genislik/2 - 10;
prevButon.width =
prevButon.height = 10;
nextButon.x = genislik +20;
nextButon.y = genislik/2 -10;
nextButon.width =
nextButon.height = 10;
var referansColl:ArrayCollection = new ArrayCollection();
sonucArray.push(referansColl);
tablo.dataProvider = sonucArray[currentIndex];
var sampleCol:DataGridColumn = new DataGridColumn();
sampleCol.dataField = "num";
sampleCol.headerText = "Number";
var sampleCol2:DataGridColumn = new DataGridColumn();
sampleCol2.dataField = "type";
sampleCol2.headerText = "Type";
var sampleCol3:DataGridColumn = new DataGridColumn();
sampleCol3.dataField = "isTrue";
sampleCol3.headerText = "Is it true?";
kolonArray.push(sampleCol,sampleCol2,sampleCol3);
tablo.columns = kolonArray;
this.addElement(tablo); //**** this is the problematic line
this.addChild(oncekiButon);
this.addChild(sonrakiButon);
}
public function getNewSonuc(incoming:Sonuc):void
{
sonucArray[currentIndex].addItem(incoming);
}
public function newTablo():void
{
var newTablo:ArrayCollection = new ArrayCollection();
currentIndex = sonucArray.push(newTablo);
}
public function prev(evt:Event):void //I haven't written event listeners yet
{
if(currentIndex > 0)
currentIndex--;
nextButon.enabled = true;
if(currentIndex == 0)
prevButon.enabled = false;
}
public function birSonrakine(evt:Event):void
{
if(currentIndex < sonucArray.length)
currentIndex++;
prevButon.enabled = true;
if(currentIndex == sonucArray.length)
nextButon.enabled = false;
}
in this version, I get a syntax error "call to a possibly undefined method addElement"
I also tried having the base class as "Sprite" and "Canvas"
when I used addChild instead of addElement, then I get runtime error "addChild is not available to this class"
when I just commented the problematic line out, everything was loaded perfectly but the datagrid itself.
Note that error occurs before sending in some data (Sonuc) to datagrid.
and when I tried with canvas and with addelement, I get "Cannot access a property or method of a null object reference" with some weird functions and classes and packages.
1009: Cannot access a property or method of a null object reference.
at mx.styles::StyleProtoChain$/initProtoChainForUIComponentStyleName()[E:\dev\4.y\frameworks\projects\framework\src\mx\styles\StyleProtoChain.as:358]
at mx.styles::StyleProtoChain$/initProtoChain()[E:\dev\4.y\frameworks\projects\framework\src\mx\styles\StyleProtoChain.as:171]
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::initProtoChain()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:10926]
at mx.core::UIComponent/regenerateStyleCache()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:10989]
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::addingChild()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7465]
at mx.core::UIComponent/addChild()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7162]
at mx.controls.listClasses::ListBase/createChildren()[E:\dev\4.y\frameworks\projects\mx\src\mx\controls\listClasses\ListBase.as:3772]
at mx.controls::DataGrid/createChildren()[E:\dev\4.y\frameworks\projects\mx\src\mx\controls\DataGrid.as:1143]
at mx.core::UIComponent/initialize()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7634]
at mx.core::UIComponent/http://www.adobe.com/2006/flex/mx/internal::childAdded()[E:\dev\4.y\frameworks\projects\framework\src\mx\core\UIComponent.as:7495]
at mx.core::Container/http://www.adobe.com/2006/flex/mx/internal::childAdded()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:3974]
at mx.core::Container/addChildAt()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:2618]
at mx.core::Container/addChild()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:2534]
at mx.core::Container/addElement()[E:\dev\4.y\frameworks\projects\mx\src\mx\core\Container.as:2981]
at genel.siniflar::ResultInterfaceArayuz()[C:\Users\Ege\Adobe Flash Builder\brainswift2\src\genel\siniflar\ResultInterface.as:95]
at x()[C:\Users\Ege\Adobe Flash Builder\brainswift2\src\x.mxml:27]
at _x_mx_managers_SystemManager/create()[_x_mx_managers_SystemManager.as:54]
at mx.managers.systemClasses::ChildManager/initializeTopLevelWindow()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\systemClasses\ChildManager.as:311]
at mx.managers::SystemManager/initializeTopLevelWindow()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:3057]
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::kickOff()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:2843]
at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::preloader_completeHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\managers\SystemManager.as:2723]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at mx.preloaders::Preloader/timerHandler()[E:\dev\4.y\frameworks\projects\framework\src\mx\preloaders\Preloader.as:542]
at flash.utils::Timer/_timerDispatch()
at flash.utils::Timer/tick()
I really need your help folks, please answer as soon as possible.
Well, I tried calling "addElement" from outside of the constructor, and it worked. However I don't know what did exactly cause this error and I know that my solution is not a legitimate one. And I would like to learn proper solution to this problem.
changes to resultInterface.as
// this.addElement(tablo); **** this is the problematic line, we have commented it out
this.addChild(oncekiButon);
this.addChild(sonrakiButon);
changes to x.mxml
public function onCreationComplete(evt:Event):void
{
showResult.addElement(showResult.tablo);
addElement(showResult);
}

actionscript 3.0 how to incorporate algorithm to my code?

I am new to actionscript 3.0 and I am trying to make a deck of cards shuffle, I have succeeded with this but my problem is that my cards are being repeated, so I have duplicates of the same card in a 52 card deck after shuffling. I am trying to create a texas holdem game.
I found this discussion Randomize or shuffle an array but it does not tell me how to incorporate the Fisher–Yates algorithm into my code. I have tried several different methods suggested here and else where over the web and nothing is working (Think the problem is defiantly my lack of experience).
Can someone please give me an example of how to incorporate this into my code or a link to somewhere that will explain how to do this correctly.
Thanks in advance.
Paul
package src.CardDeck
{
public class CardDeck
{
public var allCards:Array = [];
public var cardNames:Array;
public var cardValues:Array;
public var gameType:String;
public var drawnCards:uint = 0;
public function CardDeck(game:String)
{
gameType = game;
cardNames = ["Ace","Two","Three",
"Four","Five","Six",
"Seven","Eight","Nine",
"Ten","Jack","Queen","King"];
if(gameType == "texasholdem")
{
cardValues = [1,2,3,4,5,6,7,8,9,10,10,10,10];
}
makeSuit("Spade");
makeSuit("Heart");
makeSuit("Diamond");
makeSuit("Club");
}
private function makeSuit(suitString:String):void
{
var card:Object;
for(var i:uint = 0; i < cardNames.length; i++)
{
card = {};
card.cardType = suitString;
card.cardName = cardNames[i];
card.cardValue = cardValues[i];
card.isDrawn = false;
allCards.push(card);
}
}
public function shuffle():Array
{
var shuffledArray:Array = [allCards.length];
var randomCard:Object;
do
{
randomCard = getRandomCard();
if(shuffledArray.indexOf(randomCard) == -1)
{
shuffledArray.push(randomCard);
}
}
while(shuffledArray.length < allCards.length)
return shuffledArray;
}
private function getRandomCard():Object
{
var randomIndex:int = Math.floor(Math.random()* allCards.length);
return allCards[randomIndex];
}
}
}
Bug Note:
var shuffledArray:Array = [allCards.length];
Makes an array with a single element which shuffledArray[0] = allCards.length.
In fact you do not need to pre allocate it just say:
var shuffledArray: Array = [];
Here is the classical Fisher–Yates version:
public function shuffleFisherYates():Array {
var shuffledArray:Array = [];
var randomCardIndex: int;
do {
randomCardIndex = Math.floor(Math.random()* allCards.length);
shuffledArray.push(allCards[randomCardIndex]); // add to mix
allCards.splice(randomCardIndex,1); // remove from deck
}while(allCards.length); // Meaning while allCards.length != 0
return shuffledArray;
}
Here is Durstenfeld's (in place) version:
public function shuffleDurstenfeld():Array {
var swap:Object;
var countdown:int = allCards.length-1;
var randomCardIndex: int;
for(i = countdown; i > 0; i--){
randomCardIndex = Math.floor(Math.random()* countdown);
swap = allCards[countdown];
allCards[countdown] = allCards[randomCardIndex];
allCards[randomCardIndex]= swap;
}
return allCards; // shuffled in place
}
Assuming your shuffling code is okay, I think a reason why you are seeing repeated cards is that within your getRandomCard() method, you are not accounting for cards that have been drawn. You randomly generate an index and return the card there in the array....but that card is still in the array and it's possible that same index can be randomly generated again, resulting in the same card being returned.

AS3 Creating an array of objects

I would like to add a bunch of cars to the stage, and store them in an array as objects. The problem is I hate using external AS files and would like to keep it as simple as possible.
I tried doing :
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
var test:Array = new Array()
for (var i:Number=0; i<10; i++) {
test.push(car)
}
The problem is if I try to set a value of one object in the like
test[1].carscale = 5
Every object in the array gets their attribute carscale set to 5.
Is there any way I can do this without using external class files?
While you should use external AS files (its a good practice), here's the reason why you are having the issue, and I'm going to explain line-by-line
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
//This creates an object called car. Suppose it saves it in memory at "location" 0x12345
var test:Array = new Array();
//This creates an empty array
for (var i:Number=0; i<10; i++) {
test.push(car);
//This adds the object "car" to the array
//Since Object is a reference type, its memory location is actually added to the array
//This means you added 0x12345 to the array (10 times over the loop)
}
//The array now contains
[0x12345, 0x12345, 0x12345, .......];
//So now
test[1]; //returns the object at 0x12345
test[1].carscale=5; //sets the carscale property of the object at 0x12345
Since all objects in the array point to the same location, getting any of them will actually return the same object. This means that all of them will show carscale as 5
A solution to this would be:
var test:Array = new Array();
for (var i:Number=0; i<10; i++) {
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
test.push(car);
}
A better, REAL Object oriented solution would be to create a class called Car and then instead of doing
var car:Object = {carcolor:String,carscale:Number,carpower:Number};
you use
var car:Car = new Car();
The Car.as class would be like this:
public class Car {
public function Car() {
//this is the constructor, initialize the object here
//Suppose the default values of the car are as follows:
carcolor="red";
carscale=5;
carpower=1000;
}
public var carcolor:String;
public var carscale:Number, carpower:Number;
}
In fact, you could even use another constructor that automatically sets the properties based on arguments:
public function Car(_color:String, _scale:Number, _power:Number) {
carcolor=_color;
carscale=_scale;
carpower=_power;
}
and call it as
var car:Car=new Car("red", 5, 1000);
In fact, the car before carcolor, carscale and carpower is not even necessary because it is obvious when you put them in a class called Car.
Like TheDarkIn1978 said you're pushing a reference of your car instance into your array. When you change the value of one instance's property the same happens for each reference.
The simple answer is to create a new object upon each interation of your for loop like in the following:
var test:Array = [];
for (var i:Number = 0; i < 10; i++)
{
var car:Object = {carcolor:String, carscale:Number, carpower:Number};
test.push(car);
}// end for
[UPDATE]
I know you said that you didn't want to use "external classes" but there are advantages to using a custom class object to store values as opposed to a Object object. Here is an example:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var cars:Vector.<Car> = new Vector.<Car>();
cars.push(new Car("red", 1, 1));
cars.push(new Car("blue", 2, 2));
cars.push(new Car("green", 3, 3));
trace(cars[2].color); // output: green
}// end function
}// class
}// end package
internal class Car
{
private var _color:String;
private var _scale:Number;
private var _power:Number;
public function get color():String { return color; }
public function get scale():String { return scale; }
public function get power():String { return power; }
public function Car(color:String, scale:Number, power:Number)
{
_color = color;
_scale = scale;
_power = power;
}// end function
}// end class
This is a good example of creating an object for the sole purpose of storing values that never change by only allowing the object's properties to be set upon initiation and using getter methods to make the values read only.
I feel dumb, I found the answer here :
http://board.flashkit.com/board/showthread.php?t=792345
You're pushing the Object reference to the array, not a unique Object each time. You have to do something like:
for(var temp=0;temp<100;temp++){
var roomData:Object=new Object;
roomData.first_time=true;
rooms.push(roomData);
}
you're adding the same object to the array multiple times. you need to create new instances of your car object.
EDIT:
although it would be a best practice to create your own "Car" class and create new instances of it, even if it's only a small object with 3 properties, here's a quick example that should get you started.
package
{
//Imports
import flash.display.Sprite;
//Class
public class Main extends Sprite
{
//Constants
private static const DEFAULT_CAR_COLOR:Number = 0x000000;
private static const DEFAULT_CAR_SCALE:Number = 1.0;
private static const DEFAULT_CAR_POWER:int = 50;
//Properties
private var carsArray:Array;
//Constructor
public function Main():void
{
init();
outputCarColors();
}
//Initialize
private function init():void
{
carsArray = new Array();
for (var i:int = 0; i < 10; i++)
{
carsArray.push(CreateCar(Math.random() * 0xFFFFFF));
}
}
//Output Car Colors
private function outputCarColors():void
{
for (var i:int = 0; i < carsArray.length; i++)
{
trace("Color of car " + i + " : " + carsArray[i].carColor);
}
}
//Create Car Object
private function CreateCar(carColor:Number = DEFAULT_CAR_COLOR, carScale:Number = DEFAULT_CAR_SCALE, carPower:int = DEFAULT_CAR_POWER):Object
{
var result:Object = new Object();
result.carColor = carColor;
result.carScale = carScale;
result.carPower = carPower;
return result;
}
}
}