How can I call my as. class file from another frame? - actionscript-3

I have a code set up in an external as. class file this class file allows for a couple mouse features such as color transformations using swatches. Now the code works well but it only seems to work in frame 1. I want to move all my artwork from frame 1 into frame 4 while loading the as. class file to accompany my features in frame 4. So basically I am just trying to move everything from frame 1 to frame 4. HOW IS THIS DONE ? I tried going to publish settings and changing the eport classes option to frame 4 but no success. Heres my code which is in an external as. file.
package code
{
/*****************************************
* DrawingSample4 :
* Demonstrates dynamic color transformations.
* -------------------
* See 4_color.fla
****************************************/
import fl.events.SliderEvent;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.SimpleButton;
import flash.display.MovieClip;
import flash.geom.ColorTransform;
public class Drawing5 extends MovieClip
{
//*************************
// Properties:
public var activeSwatch:MovieClip;
// Color offsets
public var c1:Number = 0; // R
public var c2:Number = 51; // G
public var c3:Number = 51; // B
//*************************
// Constructor:
public function Drawing5()
{
// Respond to mouse events
swatch1_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
swatch2_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
swatch3_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
swatch4_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
swatch5_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
swatch6_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
apply_btn.addEventListener(MouseEvent.CLICK,clickHandler,false,0,true);
previewBox_btn.addEventListener(MouseEvent.MOUSE_DOWN,dragPressHandler);
// Respond to drag events
red_slider.addEventListener(SliderEvent.THUMB_DRAG,sliderHandler);
red_slider.addEventListener(Event.CHANGE,sliderHandler);
green_slider.addEventListener(SliderEvent.THUMB_DRAG,sliderHandler);
green_slider.addEventListener(Event.CHANGE,sliderHandler);
blue_slider.addEventListener(SliderEvent.THUMB_DRAG,sliderHandler);
blue_slider.addEventListener(Event.CHANGE,sliderHandler);
// Respond to textfield events
hexc1_txt.addEventListener(Event.CHANGE,changeHexHandler);
hexc2_txt.addEventListener(Event.CHANGE,changeHexHandler);
hexc3_txt.addEventListener(Event.CHANGE,changeHexHandler);
c1_txt.addEventListener(Event.CHANGE,changeRGBHandler);
c2_txt.addEventListener(Event.CHANGE,changeRGBHandler);
c3_txt.addEventListener(Event.CHANGE,changeRGBHandler);
// Draw a frame later
addEventListener(Event.ENTER_FRAME,draw);
}
//*************************
// Initialization:
protected function draw(event:Event):void
{
// Set color transformations
swatch1_btn.chipfill.transform.colorTransform = new ColorTransform(0,0,0,1,127,0,97);
swatch2_btn.chipfill.transform.colorTransform = new ColorTransform(0,0,0,1,130,0,0);
swatch3_btn.chipfill.transform.colorTransform = new ColorTransform(0,0,0,1,10,106,0);
swatch4_btn.chipfill.transform.colorTransform = new ColorTransform(0,0,0,1,0,51,51);
swatch5_btn.chipfill.transform.colorTransform = new ColorTransform(0,0,0,1,0,51,102)
swatch6_btn.chipfill.transform.colorTransform = new ColorTransform(0,0,0,1,127,127,127);
previewBox_btn.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
// Handle listeners...
removeEventListener(Event.ENTER_FRAME,draw);
}
//*************************
// Event Handling:
protected function dragPressHandler( event:MouseEvent ):void
{
activeSwatch = new Swatch();
activeSwatch.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
activeSwatch.addEventListener(MouseEvent.MOUSE_UP,dragReleaseHandler);
activeSwatch.startDrag(true);
addChild(activeSwatch);
}
protected function dragReleaseHandler( event:MouseEvent ):void
{
if( activeSwatch.hitTestObject(car) ){
car.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
}
activeSwatch.stopDrag();
activeSwatch.removeEventListener(MouseEvent.MOUSE_UP,dragReleaseHandler);
removeChild(activeSwatch);
}
protected function clickHandler(event:MouseEvent):void
{
car.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
}
protected function changeRGBHandler(event:Event):void
{
c1 = Number(c1_txt.text);
c2 = Number(c2_txt.text);
c3 = Number(c3_txt.text);
if(!(c1>=0)){
c1 = 0;
}
if(!(c2>=0)){
c2 = 0;
}
if(!(c3>=0)){
c3 = 0;
}
hexc1_txt.text = c1.toString(16);
hexc2_txt.text = c2.toString(16);
hexc3_txt.text = c3.toString(16);
updateSliders();
}
protected function changeHexHandler(event:Event):void
{
c1 = parseInt("0x"+hexc1_txt.text);
c2 = parseInt("0x"+hexc2_txt.text);
c3 = parseInt("0x"+hexc3_txt.text);
if(!(c1>=0)){
c1 = 0;
}
if(!(c2>=0)){
c2 = 0;
}
if(!(c3>=0)){
c3 = 0;
}
c1_txt.text = c1.toString();
c2_txt.text = c2.toString();
c3_txt.text = c3.toString();
updateSliders();
}
protected function sliderHandler( event:SliderEvent ):void
{
switch( event.target )
{
case red_slider:
c1 = red_slider.value;
break;
case green_slider:
c2 = green_slider.value;
break;
case blue_slider:
c3 = blue_slider.value;
break;
}
updateFields();
}
protected function swatchHandler(event:MouseEvent):void
{
switch( event.target.parent )
{
case swatch1_btn:
c1 = 127;
c2 = 0;
c3 = 97;
break;
case swatch2_btn:
c1 = 130;
c2 = 0;
c3 = 0;
break;
case swatch3_btn:
c1 = 10;
c2 = 106;
c3 = 0;
break;
case swatch4_btn:
c1 = 0;
c2 = 51;
c3 = 51;
break;
case swatch5_btn:
c1 = 0;
c2 = 51;
c3 = 102;
break;
case swatch6_btn:
c1 = 127;
c2 = 127;
c3 = 127;
break;
}
updateFields();
updateSliders();
}
//*************************
// Utils:
protected function updateFields():void
{
hexc1_txt.text = c1.toString(16);
hexc2_txt.text = c2.toString(16);
hexc3_txt.text = c3.toString(16);
c1_txt.text = c1.toString();
c2_txt.text = c2.toString();
c3_txt.text = c3.toString();
previewBox_btn.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
}
protected function updateSliders():void
{
red_slider.value = c1;
green_slider.value = c2;
blue_slider.value = c3;
previewBox_btn.transform.colorTransform = new ColorTransform(0,0,0,1,c1,c2,c3);
}
}
}

the issue is when you load/call this class it is looking for objects on the stage and if they are not there it will throw errors. So you shouldn't call it until it is on the same frame as the items it is looking for. So if all of your items it is looking for are on frame 4, that is where you should call it.
So go to frame 4 and add this code:
var myDrawings5 = new Drawing5();
Another option is moving the code currently in the constructor function into a new public function called init(). Then you can load the class whenever you want but you don't call the init() until the items are on the stage.
public function Drawing5(){
// now emtpy
}
public function init(){
// move code from Drawing5() here
}
Then load it and call it where needed
var myDrawings5 = new Drawing5();
myDrawings5.init();

I think your problem is that you were using Drawing5 as your document class before. Now you want to run it stand alone in frame 4. To do this, you will need to give the Drawing5 class a reference to your swfs stage so it knows where to find all of those objects now.
var d5:Drawing5 = new Drawing5(this);
then add a property to Drawing5 class called _container (or something)
private var _container:MovieClip;
then in your Drawing 5 constructor, change it to accommodate the new var and set the container
public function Drawing5(container:MovieClip){
_container = container;
}
Then in Drawing5, change ALL calls that reference an object like a list or button to include the container in the path like this:
// Respond to mouse events
_container.swatch1_btn.addEventListener(MouseEvent.CLICK,swatchHandler,false,0,false);
I hope I understood your problem correctly and this helps.

Related

Set up a Countdown and stop the game when it reaches 0

I have a simple game in AS3, and I'm trying to get a countdown working, so when the countdown gets to 0 the game ends.
I'm not getting any errors when I test this code but I'm also not getting a countdown clock. In the project I've created a text box and made it dynamic with an embedded font.
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.getTimer;
import flash.utils.Timer;
import flash.media.Sound;
import flash.media.SoundChannel;
public class MatchingGameObject10 extends MovieClip {
// game constants
private static const boardWidth:uint = 2;
private static const boardHeight:uint = 2;
private static const cardHorizontalSpacing:Number = 52;
private static const cardVerticalSpacing:Number = 52;
private static const boardOffsetX:Number = 145;
private static const boardOffsetY:Number = 70;
private static const pointsForMatch:int = 50;
private static const pointsForMiss:int = -5;
// variables
private var firstCard:Card10;
private var secondCard:Card10;
private var cardsLeft:uint;
private var gameScore:int;
private var gameStartTime:uint;
private var clockTimer:Timer;
// text fields
private var gameScoreField:TextField;
private var clock:TextField;
// timer to return cards to face-down
private var flipBackTimer:Timer;
// set up sounds
var theFirstCardSound:FirstCardSound = new FirstCardSound();
var theMissSound:MissSound = new MissSound();
var theMatchSound:MatchSound = new MatchSound();
// initialization function
public function MatchingGameObject10():void {
// make a list of card numbers
var cardlist:Array = new Array();
for(var i:uint=0;i<boardWidth*boardHeight/2;i++) {
cardlist.push(i);
cardlist.push(i);
}
// create all the cards, position them, and assign a randomcard face to each
cardsLeft = 0;
for(var x:uint=0;x<boardWidth;x++) { // horizontal
for(var y:uint=0;y<boardHeight;y++) { // vertical
var c:Card10 = new Card10(); // copy the movie clip
c.stop(); // stop on first frame
c.x = x*cardHorizontalSpacing+boardOffsetX; // set position
c.y = y*cardVerticalSpacing+boardOffsetY;
var r:uint = Math.floor(Math.random()*cardlist.length); // get a random face
c.cardface = cardlist[r]; // assign face to card
cardlist.splice(r,1); // remove face from list
c.addEventListener(MouseEvent.CLICK,clickCard); // have it listen for clicks
c.buttonMode = true;
addChild(c); // show the card
cardsLeft++;
}
}
// set up the score
gameScoreField = new TextField();
addChild(gameScoreField);
gameScore = 0;
showGameScore();
}
// set up the clock
public function CountdownClock() {
startClock();
}
public function startClock() {
clockTimer = new Timer(1000,10);
clockTimer.addEventListener(TimerEvent.TIMER, clockTick);
clockTimer.addEventListener(TimerEvent.TIMER_COMPLETE, clockEnd);
clockTimer.start();
showClock();
}
public function clockTick(event:TimerEvent) {
showClock();
}
public function showClock() {
clock.text = String(clockTimer.repeatCount - clockTimer.currentCount);
}
public function clockEnd(event:TimerEvent) {
clock.text = "!";
}
// player clicked on a card
public function clickCard(event:MouseEvent) {
var thisCard:Card10 = (event.target as Card10); // what card?
if (firstCard == null) { // first card in a pair
firstCard = thisCard; // note it
thisCard.startFlip(thisCard.cardface+2);
playSound(theFirstCardSound);
} else if (firstCard == thisCard) { // clicked first card again
firstCard.startFlip(1);
firstCard = null;
playSound(theMissSound);
} else if (secondCard == null) { // second card in a pair
secondCard = thisCard; // note it
thisCard.startFlip(thisCard.cardface+2);
// compare two cards
if (firstCard.cardface == secondCard.cardface) {
// remove a match
removeChild(firstCard);
removeChild(secondCard);
// reset selection
firstCard = null;
secondCard = null;
// add points
gameScore += pointsForMatch;
showGameScore();
playSound(theMatchSound);
// check for game over
cardsLeft -= 2; // 2 less cards
if (cardsLeft == 0) {
MovieClip(root).gameScore = gameScore;
MovieClip(root).clockTimer = clockTimer;
MovieClip(root).gotoAndStop("gameover");
}
} else {
gameScore += pointsForMiss;
showGameScore();
playSound(theMissSound);
flipBackTimer = new Timer(2000,1);
flipBackTimer.addEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
flipBackTimer.start();
}
} else { // starting to pick another pair
returnCards(null);
playSound(theFirstCardSound);
// select first card in next pair
firstCard = thisCard;
firstCard.startFlip(thisCard.cardface+2);
}
}
// return cards to face-down
public function returnCards(event:TimerEvent) {
if (firstCard != null) firstCard.startFlip(1);
if (secondCard != null) secondCard.startFlip(1);
firstCard = null;
secondCard = null;
flipBackTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
}
public function showGameScore() {
gameScoreField.text = "Score: "+String(gameScore);
}
public function playSound(soundObject:Object) {
var channel:SoundChannel = soundObject.play();
}
}
}
In your question you are speaking about a text field that you'v added to your stage, but in this case, your current code should give you an error about the line private var clock:TextField; if your text field is named clock, otherwise ( the name of your text field is not clock ) you can use that name in your showClock() function and do not forget to call CountdownClock() which will start the timer :
public function MatchingGameObject10(): void
{
// ...
CountdownClock();
}
And
public function showClock(): void
{
your_clock_textfield.text = String(clockTimer.repeatCount - clockTimer.currentCount);
}
You can also create your clock text field like you did with your gameScoreField one and in this case you can remove the text field that you'v already inserted in your stage :
public function MatchingGameObject10(): void
{
// ...
clock = new TextField();
addChild(clock);
CountdownClock();
}
Also, don't forget to set the position of your text fields because they will be inserted in the same position (0, 0) by default.
For embedding fonts dynamically ( using ActionScript ), take a look on my answer of this question.
Hope that can help.

AS3: Why is a line created with .graphics appearing in two different places and when removed with parent.visible = false, only one goes?

Nobody seems to have this question already so I asked it because I've spent a few hours trying to debug this and can't find a solution;
Essentially, I have a function called draw, which is declared in my document class:
public function draw(Target: MovieClip,mX: int,mY: int,lX: int,lY: int):void {
Target.graphics.clear();
Target.graphics.lineStyle(1,0x000000,1);
Target.graphics.moveTo(mX,mY);
Target.graphics.lineTo(lX,lY);
}
I call it later to draw two lines, on two different MovieClips:
draw(Line,Line.mX,Line.mY,Mirror.x + (Mirror.width / 2),Line.lY);
draw(nextLine,(Mirror.x + (Mirror.width / 2)),200,(Mirror.x + (Mirror.width / 2)),0);
where
var Line: MovieClip = new MovieClip();
var Mirror: MovieClip = new mirror();
and Mirror is draggable, so Mirror.x changes whenever it is dragged.
Line is a line made using .graphics and Line.mX is equal to the Line.graphics.moveTo X value last time it was modified. Line.mY is the same, but for the Y coordinate. I set these values by doing this:
Line.mX = 0;
Line.mY = 200;
Line.lX = 550;
Line.lY = 200;
But with whatever values I want to draw the line, with lX and lY being equal to the X and Y coordinates of Line.graphics.lineTo. Then I draw Line using my draw function like this:
draw(Line,Line.mX,Line.mY,Line.lX,Line.lY);
Then it gets more complex because, actually, Line is just one line in an array of lines, created like this:
public var lines = [line0,line1,line2,line3,line4,line5,line6,line7,line8];
and each of those lines is created like this (with 0 being replaced by the line's number, respectively):
public var line0: MovieClip = new MovieClip();
then I give each line a number and a name, add them to the stage and hide them like this:
for each(var setupLine:MovieClip in lines) {
setupLine.num = (lines.indexOf(setupLine));
setupLine.name = ('line' + setupLine.num);
addChild(setupLine);
setupLine.visible = false;
}
Then, after making line0 visible, because I need to see it at the start, I loop through each line in a function that runs on ENTER_FRAME, and set the value of nextLine to a different value each time I run the loop like this:
for each(var Line:MovieClip in lines) {
nextLine = this['line' + (Line.num + 1)];
}
Within that loop, I then loop through a few other arrays, then check for a collision with the selected Line and another selected MovieClip from another array, which I wont go into or this question will be longer than the code for node.js.
So essentially, if the collision with the two MovieClips is present, I draw the line that I mentioned at the top of my question. But for some reason, although Line draws correctly, nextLine draws correctly, but a duplicate of it is drawn across the Y axis at 0, and stops where nextLine is on the Y axis (nextLine is vertical, so it has the same Y value at the start as at the end).
Even stranger, when I try to hide nextLine if the collision with the two MovieClips is no longer present, using this code:
nextLine.visible = false;
it only hides the version of nextLine that runs along the top of the stage, which I didn't even intend to create in the start.
EDIT
here is a link to the current source code
Here is a link to the entire project files with the original source code
copy/paste the new source code from the pastebin link to get the new version
Thanks in advance,
-Raph
I figured out how to do this, code is
package {
import flash.events.*;
import flash.utils.*;
import flash.display.*;
[SWF(backgroundColor="0xbdc3c7")]
public class LightStage extends MovieClip {
//import classes
public var globeClass:Globe = new Globe();
public var mirrorClass:Mirror = new Mirror();
public var lineClass:Line = new Line();
//create all stage objects
public var curLine:Line
public var nextLine:Line;
public var curMirror:Mirror;
//create containers
public var mirrors:Vector.<Mirror> = new Vector.<Mirror>(); //a vector is an array, but every member has to be (or subclass) the specified class
public var globes:Vector.<Globe> = new Vector.<Globe>();
public var lines:Vector.<Line> = new Vector.<Line>();
trace('lightstage: working');
//create level object
public var curLevel:int = -1;
//create dependent variables
public var kill: Boolean = true;
//init function
public function LightStage() {
//setup MovieClips
var i:int = 0;
for (i = 0; i < 4; i++) {
mirrors.push(new Mirror());
}
for (i = 0; i < 4;i++ ) {
globes.push(new Globe());
}
var tmpLine:Line;
for (i = 0; i < 10; i++) {
tmpLine = new Line();
lines.push(tmpLine);
addChild(tmpLine);
tmpLine.visible = false;
}
//create ENTER_FRAME listener
stage.addEventListener(Event.ENTER_FRAME,enterFrame);
//start the game
levelUp();
}
//levelUp function
public function levelUp() {
curLevel++;
curLine = lines[curLevel]; //set line to the current level
curLine.curX = 0;
curLine.curY = 200;
curLine.draw(550, 200);
curLine.visible = true;
//show and position mirrors and globes
curMirror = mirrors[curLevel];
addChild(curMirror);
curMirror.x = 250;
curMirror.y = 350;
var curGlobe:Globe = globes[curLevel];
addChild(curGlobe);
curGlobe.x = 100;
curGlobe.y = 50;
//set mirror types
curMirror.gotoAndStop(2);
trace("you are now on level " + (curLevel + 1) + "!");
}
//ENTER_FRAME function
public function enterFrame(event:Event) {
//line1.visible = true;
for (var i:int = 0; i < lines.length;i++){
if (i < lines.length - 1) nextLine = lines[i + 1]; //check for out of bounds before assignment next line
if (lines[i].visible == true) {
kill = true;
for each(var mirror:Mirror in mirrors) {
if (lines[i].visible && mirror.stage && mirror.hitTestObject(lines[i])) { //for efficiency, do the hit test last in the if statement
for each(var globe:Globe in globes) {
//Looped through Mirrors and Lines and checked for collision - if collision is present, we loop through globes here
if (nextLine && nextLine.stage) {
addChild(nextLine);
}
//check for active globes
if (lines[i].visible && lines[i].hitTestObject(globe)) {
//check if the selected line touches the selected globe - if it does then we will start the timer for that globe
if (!globe.running){
globe.start();
//trace('timing');
kill = false;
}
}
else {
globe.reset();
}
switch(mirror.currentFrame) {
case 1:
break;
case 2:
//trace('live a life you will remember' + Math.random());
if(nextLine) nextLine.visible = true;
lines[i].draw(mirror.x + (mirror.width / 2),lines[i].curY);
if (nextLine) {
nextLine.curX = mirror.x + (mirror.width / 2);
nextLine.curY = 200;
nextLine.draw(mirror.x + (mirror.width / 2), 0);
}
kill = false;
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
trace(mirror.currentFrame);
kill = false;
break;
}
}
}
else if (lines[i].visible && mirror.stage && lines[i].stage){
if (kill && nextLine){
nextLine.graphics.clear();
nextLine.visible = false;
}
}
}
}
}
}
}
}
//MIRROR CLASS DECLARATION
import flash.events.MouseEvent;
class Mirror extends MovieClip {
trace('mirror: working');
public function Mirror() {
this.addEventListener(MouseEvent.MOUSE_DOWN,onDown,false,0,true);
}
private function onDown(e:MouseEvent):void {
//add the mouse up listener on the stage, that way it's consistent even if the user drags so fast that the mouse leaves the bounds of the mirror
stage.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
this.startDrag();
}
private function onUp(e:MouseEvent):void {
//we need to remove the listener from the stage now
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp, false);
this.stopDrag();
}
}
//LINE CLASS DECLARATION
import flash.display.Graphics;
class Line extends MovieClip {
trace('line: working');
public var curX:int;
public var curY:int;
public function Line():void {
}
public function draw(toX:int,toY:int):void {
graphics.clear();
graphics.lineStyle(1,0x000000,1);
graphics.moveTo(curX,curY);
graphics.lineTo(toX, toY);
curX = toX;
curY = toY;
}
}
//GLOBE CLASS DECLARATION
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
class Globe extends MovieClip {
trace('globe: working');
private var timer:Timer = new Timer(3 * 100, 5);
public function Globe():void {
timer = new Timer(300, 5);
timer.addEventListener(TimerEvent.TIMER, repeatShine, false, 0, true);
}
public function reset():void {
timer.reset();
}
public function start():void {
timer.start();
}
public function get running():Boolean { return timer.running; };
private function repeatShine(e:TimerEvent):void {
}
}

As3 Error: Error #1009: Cannot access a property or method of a null object reference

I seem to be having an error with my inventory system.
This is my class:
package
{
import flash.display.*;
public class InventoryDemo extends MovieClip
{
var inventory:Inventory;
public function InventoryDemo()
{
inventory = new Inventory(this);
inventory.makeInventoryItems([d1,d2]);
}
}
}
I have already placed d1 and d2 objects in a second keyframe.
And this is the child class:
package
{
import flash.display.*;
import flash.events.*;
public class Inventory
{
var itemsInInventory:Array;
var inventorySprite:Sprite;
public function Inventory(parentMC:MovieClip)
{
itemsInInventory = new Array ;
inventorySprite = new Sprite ;
inventorySprite.x = 50;
inventorySprite.y = 360;
parentMC.addChild(inventorySprite);
}
function makeInventoryItems(arrayOfItems:Array)
{
for (var i:int = 0; i < arrayOfItems.length; i++)
{
arrayOfItems[i].addEventListener(MouseEvent.CLICK,getItem);
arrayOfItems[i].buttonMode = true;
}
}
function getItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
itemsInInventory.push(item);
inventorySprite.addChild(item);
item.x = itemsInInventory.length - 1 * 40;
item.y = 0;
item.removeEventListener(MouseEvent.CLICK,getItem);
item.addEventListener(MouseEvent.CLICK,useItem);
}
function useItem(e:Event)
{
var item:MovieClip = MovieClip(e.currentTarget);
trace(("Use Item:" + item.name));
}
}
}
The code works when I try it in a black project with only d1 and d2 in the stage. Can any one help me solve this?
Your error suggests that d1 and d2 are not created at the time that you call
inventory.makeInventoryItems([d1,d2]);
You suggest that you have created d1 and d2 in the second keyframe, but if InventoryDemo is your DocumentClass, then it will run before you reach the second keyframe.
So, if you want to use d1 and d2 you either need to move them to the first frame, or you need to not try and use them until the second frame of the Movie has occurred.
If you want to keep d1 and d2 on the second frame, then you need to take the call out of the constructor and into a new function that you call on the second frame:
public function InventoryDemo()
{
//Do nothing here
//inventory = new Inventory(this);
//inventory.makeInventoryItems([d1,d2]);
}
public function initialiseInventory():void
{
//Initialise you inventory here.
inventory = new Inventory(this);
inventory.makeInventoryItems([d1,d2]);
}
Then on the 2nd frame of your timeline call the function:
initialiseInventory();
stop();

Issue with sharedObject usage / loading data

The main goal of my code is to create a 3x3 grid and when you click a cell from that grid you cant click it again even if you close the fla and load it again.
Something like a shop where the 1st row is level1 of the upgrade and the columns are the other levels.
There are also 2-3 other things that it does -> every cell of the grid has 4 mouseStates.
Also at the 1st load of the FLA you create the 3x3 grid and you can click only on the elements in the 1st row.(you cant get Speed 2 if you didnt have Speed1 before that.)
So you can click the 2nd element of a column only if the 1st element of the same column has been clicked before.
The same goes for the 3rd element of the column -> it can be clicked only if the 2nd was clicked before.
But im having trouble with the logic after loading the fla for the 2nd time.
To be more specific :
It is changing the mouseOver/out states on the elements that were clicked before(which is good (cause i want to see that)), but it is leting me click only the 1st row.And since Im loading the clickedBefore buttons and removing the mouseEvent.CLICK from them, I cant click some of them if i haven`t clicked them at the 1st load of the fla.
I have 2 classes: Main
import flash.events.Event;
import flash.events.MouseEvent;
import flash.utils.getDefinitionByName;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.Graphics;
import flash.display.Bitmap;
import flash.display.SimpleButton;
import flash.net.SharedObject;
public class Main extends Sprite
{
private var elementRow:int = 0;
private var elementCol:int = 0;
private var myClassImage_Arr:Array = new Array();//this contains the different mouseState Images in Class data.
private var myBitmapNames_Arr:Array = ["speed1_", "speed2_", "speed3_",
"time1_", "time2_", "time3_",
"turbo1_", "turbo2_", "turbo3_",];
//------------------------------------------
private var index:int = 0;
private var col:int = 3;
private var row:int = 3;
//------------------------------------------
private var savedData:SharedObject = SharedObject.getLocal("ZZZ_newWAY_nextButton+imageChange_7");
private var buttonThatHaveBeenClicked_Arr:Array = [];
private var myButtons_Arr:Array = [];
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
for (var i:int = 0; i < col; i++)
{
var lastRowElement:BitmapButton = null;
for (var j:int = 0; j < row; j++)
{
for (var k:int = 0; k < 4; k++)//4states of mouse
{
var cls:Class = Class(getDefinitionByName(myBitmapNames_Arr[index] + k));
myClassImage_Arr.push(cls);
}
var myImage_mc = new BitmapButton(myClassImage_Arr[0 + (index * 4)],
myClassImage_Arr[1 + (index * 4)],
myClassImage_Arr[2 + (index * 4)],
myClassImage_Arr[3 + (index * 4)], i, j);
myImage_mc.x = 100 + i * (myImage_mc.width + 10);
myImage_mc.y = 100 + j * (myImage_mc.height + 10);
myImage_mc.name = "myImage_mc" + index;
this.addChild(myImage_mc);
myButtons_Arr.push(myImage_mc)
myImage_mc.mouseEnabled = false;
myImage_mc.mouseChildren = false;
myImage_mc.buttonMode = false;
myImage_mc.addEventListener("send_SOS", onCustomClick);
if ( lastRowElement == null )
{
myImage_mc.mouseEnabled = true;
myImage_mc.mouseChildren = true;
myImage_mc.buttonMode = true;
}
else
{
lastRowElement.next_1 = myImage_mc;
}
lastRowElement = myImage_mc;
index++;
}
}
if(savedData.data.myArray == undefined) trace(" 1st time loading this game\n")
else if(savedData.data.myArray != undefined)
{
trace(" Game was played before\n")
buttonThatHaveBeenClicked_Arr = savedData.data.myArray;
var savedData_length:int = savedData.data.myArray.length;
trace("Buttons that have been clicked before: " + buttonThatHaveBeenClicked_Arr + "\n");
for (var m:int = 0; m < myButtons_Arr.length; m++)
{
var myButtons_ArrName:String = myButtons_Arr[m].name
for (var p:int = 0; p < savedData_length; p++)
{
if(myButtons_ArrName == savedData.data.myArray[p])
{
myButtons_Arr[m].alpha = 0.9
myButtons_Arr[m].buttonMode = false;
myButtons_Arr[m].removeEventListener("send_SOS", onCustomClick);
myButtons_Arr[m].myInsideBtn.upState = myButtons_Arr[m].image3
myButtons_Arr[m].myInsideBtn.overState = myButtons_Arr[m].image4
}
}
}
}
}
private function onCustomClick(ev:Event):void
{
trace(ev.target.name);
if (ev.target is BitmapButton)
{
var btn:BitmapButton = ev.currentTarget as BitmapButton;
if (btn.next_1 != null)
{
btn.next_1.mouseEnabled = true;
btn.next_1.mouseChildren = true;
btn.next_1.buttonMode = true;
}
btn.mouseChildren = false;
btn.buttonMode = false;
btn.removeEventListener("send_SOS", onCustomClick);
buttonThatHaveBeenClicked_Arr.push( btn.name );
savedData.data.myArray = buttonThatHaveBeenClicked_Arr;
savedData.flush();
savedData.close();
}
}
}
}
and BitmapButton
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.events.Event;
public class BitmapButton extends Sprite
{
public var next_1:BitmapButton = null;
//-----------------------------------
public var myInsideBtn:SimpleButton = new SimpleButton();
private var image1:Bitmap;
private var image2:Bitmap;
public var image3:Bitmap;
public var image4:Bitmap;
public var imageIsInRow:int;
public var imageIsInCol:int;
public function BitmapButton(active_OutState:Class, active_OverState:Class, notActive_OutState:Class, notActive_OverState:Class,col:int,row:int)
{
image1 = new Bitmap (new active_OutState() );
image2 = new Bitmap (new active_OverState() );
image3 = new Bitmap (new notActive_OutState() );
image4 = new Bitmap (new notActive_OverState() );
imageIsInRow = row;
imageIsInCol = col;
myInsideBtn.upState = image1;
myInsideBtn.overState = image2;
myInsideBtn.downState = myInsideBtn.upState;
myInsideBtn.hitTestState = myInsideBtn.overState;
addChild( myInsideBtn );
myInsideBtn.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(ev:MouseEvent):void
{
myInsideBtn.upState = image3;
myInsideBtn.overState = image4;
var myNewEvent:Event = new Event("send_SOS");
this.dispatchEvent(myNewEvent);
trace("CLICK from inside the button");
}
}
}
ill also upload it to this link Grid_with_sharedObject with a zip.
and upload also Grod_before_Using_sharedObject if someone decides that he would help but the code is to messed up
If I'm reading your code correctly, I'd honestly say your problem is sequential. For whatever reason, the setting of the active and inactive rows is occurring BEFORE the data is actually being interpreted into the button states. As a result, the computer sees all buttons as off when it decides whether to make other rows clickable, and THEN updates the state of the buttons.
The easiest way to fix this, I think, would be to split the Main() function into a few sub functions, such as updateButtons() for the function that changes whether a row/button is clickable, and loadData() for the function the loads from the SharedObject. In Main(), put the calls to those functions. This will make Main() easier to work with, and you can call a function multiple times if necessary.
To solve your particular issue, you'd need to get the data for the buttons using the SharedObject FIRST (which obviously is working), and THEN update whether the other buttons are clickable.
A "soft-skills" tip for programming: when you run into a problem, grab a piece of paper, a pencil, and read through your code the way your computer would. Be the computer. Write down variables and their values when they change. Mark when functions are called. You'll spot a lot of errors this way.

Use MouseEvent for getting Object`s public variables

I have a simple problem which is not easy at the moment. this is a text field class which add a text field to a movieclip (passed from root class) and also save(buffer) some data (like xml file name) in it`s public variables:
package src {
import flash.display.Shape;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
public class menuitem00 extends Shape {
public var activateFlag:Boolean = false;
public var name00:String = "";
public var xml00:String = "";
public var txt00:TextField = new TextField();
private var OM:MovieClip;
private var id00:Number = 0;
public function menuitem00(n:int ,OE:MovieClip ,xmlf:String):void {
trace (" Text Field Object with buffer ");
OM = OE; id00 = n; xml00 = xmlf;
}
public function init():void{
// textfield
txt00.selectable = false;
txt00.autoSize = TextFieldAutoSize.LEFT;
txt00.defaultTextFormat = new TextFormat("Impact", 36,0x66AAFF);
txt00.text = name00;
txt00.border = true;
txt00.borderColor = 0x00FF00;
txt00.sharpness = 100;
txt00.x = 0;
txt00.y = (id00 * txt00.height) + 1;
txt00.z = 0;
OM.addChild(txt00);
}
}
}
.. now I use a for loop to add instance of that class to a movie clip on stage:
for (var i:int = 0; i<Bunker[0]["trans0size"]; i++) {
menuData[i] = new menuitem00(i, menu_mc, Bunker[0]["transfile0" + i]);// pass i , a movieclip named menu_mc and an xml file name
menuData[i].name00 = Bunker[0]["transtitle0" + i]; // pass text
menuData[i].activateFlag = true; // set actveFlag to true
menuData[i].init(); // run init() inside the instance. it adds textfield to the menu_mc and also set name00 as Text for the textField
}
also I add mouse event for clicking on the stage,
stage.addEventListener(MouseEvent.CLICK, clk, false, 0, true);
public function clk(evt:MouseEvent):void{ //// mouse
trace (" Name: " + evt.target.text);
//trace (evt.target.xml00);
}
HERE IS MY PROBLEM --> I want to get "xml00" var from that instance on the stage by mouse click but, trace (evt.target.xml00); is not working .. also trace (evt.target.name00); is not working. I can get everything like .alpha or .text from txt00 but not other variables in my object. Any idea ?
don't add the click-listener to the STAGE but to you object.
menuData[i].addEventListener(MouseEvent.CLICK, clk, ...);
and add the following line to your menuitem00 class:
this.mouseChildren = false;
so you can be sure that the evt.target is an object of this class and not a child (like the textfield or something else).
edit
if you want to keep the stage-listener, try this:
stage.addEventListener(MouseEvent.CLICK, clk, ...);
private function clk (evt:MouseEvent):void
{
if (evt.currentTarget is menuitem00)
{
var item:menuitem00 = evt.currentTarget as menuitem00;
trace(item.xml00); // or any other public variable
}
}
but still add the mouseChildren = false; to your class.
edit2
make the menuitem00 class a sprite (and rename it pls):
public class MenuItem extends Sprite {
private var _activateFlag:Boolean;
private var _xml:String;
private var _txt:TextField;
private var _id:Number;
public function MenuItem (n:int, xmlf:String) {
trace (" Text Field Object with buffer ");
_id = n;
_xml = xmlf;
_activeFlag = true;
this.mouseChildren = false;
// create txt
_txt = new TextField();
// do the formating here ...
this.addChild(_txt);
}
public function getXml():String {
return _xml;
}
}
in the for loop you would do sth like this:
for (var i:int = 0; i<Bunker[0]["trans0size"]; i++) {
var item:MenuItem = new MenuItem(i, Bunker[0]["transfile0" + i]);
item.addEventListener(MouseEvent.CLICK, clk, false, 0, true);
menu_mc.addChild(item);
menuData[i] = item;
}
private function clk (evt:MouseEvent):void {
var item:MenuItem = evt.target as MenuItem;
if (item != null) {
trace(item.getXml()); // use a getter and don't access the variable directly
}
}
and pls re-read your actionscript (or programming) books, you're doing some really bad things i your code that you shouldn't.