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

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.

Related

how to call actionscript functions from flash timeline

I am using AS3, and i want to call function 'startMatchThree' which is in a MatchThree.as (external actionscript file) into the flahs main timeline actions.
here is my code:
package {
import flash.display.;
import flash.events.;
import flash.text.*;
import flash.utils.Timer;
public class MatchThree extends MovieClip {
// constants
static const numPieces:uint = 4;
static const spacing:Number = 45;
static const offsetX:Number = 30;
static const offsetY:Number = 50;
// game grid and mode
private var grid:Array;
private var gameSprite:Sprite;
private var firstPiece:Piece;
private var isDropping,isSwapping:Boolean;
private var gameScore:int;
// set up grid and start game
public function startMatchThree() {
// create grid array
grid = new Array();
for(var gridrows:int=0;gridrows<8;gridrows++) {
grid.push(new Array());
}
setUpGrid();
isDropping = false;
isSwapping = false;
gameScore = 0;
addEventListener(Event.ENTER_FRAME,movePieces);
}
public function setUpGrid() {
// loop until valid starting grid
while (true) {
// create sprite
gameSprite = new Sprite();
// add 64 random pieces
for(var col:int=0;col<8;col++) {
for(var row:int=0;row<8;row++) {
addPiece(col,row);
}
}
// try again if matches are present
if (lookForMatches().length != 0) continue;
// try again if no possible moves
if (lookForPossibles() == false) continue;
// no matches, but possibles exist: good board found
break;
}
// add sprite
addChild(gameSprite);
}
// create a random piece, add to sprite and grid
public function addPiece(col,row:int):Piece {
var newPiece:Piece = new Piece();
newPiece.x = col*spacing+offsetX;
newPiece.y = row*spacing+offsetY;
newPiece.col = col;
newPiece.row = row;
newPiece.type = Math.ceil(Math.random()*4);
newPiece.gotoAndStop(newPiece.type);
newPiece.select.visible = false;
gameSprite.addChild(newPiece);
grid[col][row] = newPiece;
newPiece.addEventListener(MouseEvent.CLICK,clickPiece);
return newPiece;
}
// player clicks on a piece
public function clickPiece(event:MouseEvent) {
var piece:Piece = Piece(event.currentTarget);
// first one selected
if (firstPiece == null) {
piece.select.visible = true;
firstPiece = piece;
// clicked on first piece again
} else if (firstPiece == piece) {
piece.select.visible = false;
firstPiece = null;
// clicked on second piece
} else {
firstPiece.select.visible = false;
// same row, one column over
if ((firstPiece.row == piece.row) && (Math.abs(firstPiece.col-piece.col) == 1)) {
makeSwap(firstPiece,piece);
firstPiece = null;
// same column, one row over
} else if ((firstPiece.col == piece.col) && (Math.abs(firstPiece.row-piece.row) == 1)) {
makeSwap(firstPiece,piece);
firstPiece = null;
// bad move, reassign first piece
} else {
firstPiece = piece;
firstPiece.select.visible = true;
}
}
}
// start animated swap of two pieces
public function makeSwap(piece1,piece2:Piece) {
swapPieces(piece1,piece2);
// check to see if move was fruitful
if (lookForMatches().length == 0) {
swapPieces(piece1,piece2);
} else {
isSwapping = true;
}
}
// swap two pieces
public function swapPieces(piece1,piece2:Piece) {
// swap row and col values
var tempCol:uint = piece1.col;
var tempRow:uint = piece1.row;
piece1.col = piece2.col;
piece1.row = piece2.row;
piece2.col = tempCol;
piece2.row = tempRow;
// swap grid positions
grid[piece1.col][piece1.row] = piece1;
grid[piece2.col][piece2.row] = piece2;
}
// if any pieces are out of place, move them a step closer to being in place
// happens when pieces are swapped, or they are dropping
public function movePieces(event:Event) {
var madeMove:Boolean = false;
for(var row:int=0;row<8;row++) {
for(var col:int=0;col<8;col++) {
if (grid[col][row] != null) {
// needs to move down
if (grid[col][row].y < grid[col][row].row*spacing+offsetY) {
grid[col][row].y += 5;
madeMove = true;
// needs to move up
} else if (grid[col][row].y > grid[col][row].row*spacing+offsetY) {
grid[col][row].y -= 5;
madeMove = true;
// needs to move right
} else if (grid[col][row].x < grid[col][row].col*spacing+offsetX) {
grid[col][row].x += 5;
madeMove = true;
// needs to move left
} else if (grid[col][row].x > grid[col][row].col*spacing+offsetX) {
grid[col][row].x -= 5;
madeMove = true;
}
}
}
}
// if all dropping is done
if (isDropping && !madeMove) {
isDropping = false;
findAndRemoveMatches();
// if all swapping is done
} else if (isSwapping && !madeMove) {
isSwapping = false;
findAndRemoveMatches();
}
}
// gets matches and removes them, applies points
public function findAndRemoveMatches() {
// get list of matches
var matches:Array = lookForMatches();
for(var i:int=0;i<matches.length;i++) {
var numPoints:Number = (matches[i].length-1)*50;
for(var j:int=0;j<matches[i].length;j++) {
if (gameSprite.contains(matches[i][j])) {
var pb = new PointBurst(this,numPoints,matches[i][j].x,matches[i][j].y);
addScore(numPoints);
gameSprite.removeChild(matches[i][j]);
grid[matches[i][j].col][matches[i][j].row] = null;
affectAbove(matches[i][j]);
}
}
}
// add any new piece to top of board
addNewPieces();
// no matches found, maybe the game is over?
if (matches.length == 0) {
if (!lookForPossibles()) {
endGame();
}
}
}
when I put 'startMatchThree' in the actions tab in timeline, it is showing this error message:
1180: Call to a possibly undefined method startMatchThree.
SO how to solve this error!!
Thank you for the help!! :)
startMatchThree() is a method of the MatchThree class, so you need a reference to an instance of MatchThree. Is there a symbol on the timeline somewhere which is linked to the MatchThree class? Then you can do something like this, where "matchThree" is the instance name of the symbol:
matchThree.startMatchThree();
Are you instantiating the MatchThree class in code? Then you just need to use that code reference, something like this,:
var matchThree:MatchThree = new MatchThree();
matchThree.startMatchThree();

I am creating an auto solve function for a sliding puzzle

I am new to actionscript and I am trying to make a "cheat" way of completing a sliding puzzle where when I click the [s] key it calls a solve puzzle function which makes a for loop put all the puzzle pieces in the correct location. This function must call a for loop, those were the instructions I was given. Could anyone help me understand the code that I need to make this happen. I have already made the function and it does properly call when I hit the s key but everything past that doesn't seem to make the code actually move the pieces. Thank you for any help I can get.
package {
import flash.display.*;
import flash.events.*;
import flash.net.URLRequest;
import flash.geom.*;
import flash.utils.Timer;
public class SlidingPuzzle extends MovieClip {
// space between pieces and offset
static const pieceSpace:Number = 2;
static const horizOffset:Number = 50;
static const vertOffset:Number = 50;
// number of pieces
static const numPiecesHoriz:int = 5;
static const numPiecesVert:int = 5;
// random shuffle steps
static const numShuffle:int = 200;
// animation steps and time
static const slideSteps:int = 10;
static const slideTime:int = 250;
// size of pieces
private var pieceWidth:Number;
private var pieceHeight:Number;
// game pieces
private var puzzleObjects:Array;
// tracking moves
private var blankPoint:Point;
private var slidingPiece:Object;
private var slideDirection:Point;
private var slideAnimation:Timer;
public function startSlidingPuzzle() {
// blank spot is the bottom right
blankPoint = new Point(numPiecesHoriz-1,numPiecesVert-1);
// load the bitmap
loadBitmap("oceanshore.jpg");
// event to complete the puzzle for you.
stage.addEventListener(KeyboardEvent.KEY_UP, solvePuzzle);
}
// get the bitmap from an external source
public function loadBitmap(bitmapFile:String) {
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadingDone);
var request:URLRequest = new URLRequest(bitmapFile);
loader.load(request);
}
// bitmap done loading, cut into pieces
public function loadingDone(event:Event):void {
// create new image to hold loaded bitmap
var image:Bitmap = Bitmap(event.target.loader.content);
pieceWidth = image.width/numPiecesHoriz;
pieceHeight = image.height/numPiecesVert;
// cut into puzzle pieces
makePuzzlePieces(image.bitmapData);
// shuffle them
shufflePuzzlePieces();
}
// cut bitmap into pieces
public function makePuzzlePieces(bitmapData:BitmapData) {
puzzleObjects = new Array();
for(var x:uint=0;x<numPiecesHoriz;x++) {
for (var y:uint=0;y<numPiecesVert;y++) {
// skip blank spot
if (blankPoint.equals(new Point(x,y))) continue;
// create new puzzle piece bitmap and sprite
var newPuzzlePieceBitmap:Bitmap = new Bitmap(new BitmapData(pieceWidth,pieceHeight));
newPuzzlePieceBitmap.bitmapData.copyPixels(bitmapData,new Rectangle(x*pieceWidth,y*pieceHeight,pieceWidth,pieceHeight),new Point(0,0));
var newPuzzlePiece:Sprite = new Sprite();
newPuzzlePiece.addChild(newPuzzlePieceBitmap);
addChild(newPuzzlePiece);
// set location
newPuzzlePiece.x = x*(pieceWidth+pieceSpace) + horizOffset;
newPuzzlePiece.y = y*(pieceHeight+pieceSpace) + vertOffset;
// create object to store in array
var newPuzzleObject:Object = new Object();
newPuzzleObject.currentLoc = new Point(x,y);
newPuzzleObject.homeLoc = new Point(newPuzzlePiece.x,newPuzzlePiece.y);
newPuzzleObject.piece = newPuzzlePiece;
newPuzzlePiece.addEventListener(MouseEvent.CLICK,clickPuzzlePiece);
puzzleObjects.push(newPuzzleObject);
}
}
}
//make the puzzle solve itself
public function solvePuzzle(evt:KeyboardEvent)
{
if (evt.keyCode == 83)
{
for(var i:int = 0; i<puzzleObjects.length; i++)
{
}
}
}
// make a number of random moves
public function shufflePuzzlePieces() {
for(var i:int=0;i<numShuffle;i++) {
shuffleRandom();
}
}
// random move
public function shuffleRandom() {
// loop to find valid moves
var validPuzzleObjects:Array = new Array();
for(var i:uint=0;i<puzzleObjects.length;i++) {
if (validMove(puzzleObjects[i]) != "none") {
validPuzzleObjects.push(puzzleObjects[i]);
}
}
// pick a random move
var pick:uint = Math.floor(Math.random()*validPuzzleObjects.length);
movePiece(validPuzzleObjects[pick],false);
}
public function validMove(puzzleObject:Object): String {
// is the blank spot above
if ((puzzleObject.currentLoc.x == blankPoint.x) &&
(puzzleObject.currentLoc.y == blankPoint.y+1)) {
return "up";
}
// is the blank spot below
if ((puzzleObject.currentLoc.x == blankPoint.x) &&
(puzzleObject.currentLoc.y == blankPoint.y-1)) {
return "down";
}
// is the blank to the left
if ((puzzleObject.currentLoc.y == blankPoint.y) &&
(puzzleObject.currentLoc.x == blankPoint.x+1)) {
return "left";
}
// is the blank to the right
if ((puzzleObject.currentLoc.y == blankPoint.y) &&
(puzzleObject.currentLoc.x == blankPoint.x-1)) {
return "right";
}
// no valid moves
return "none";
}
// puzzle piece clicked
public function clickPuzzlePiece(event:MouseEvent) {
// find piece clicked and move it
for(var i:int=0;i<puzzleObjects.length;i++) {
if (puzzleObjects[i].piece == event.currentTarget) {
movePiece(puzzleObjects[i],true);
break;
}
}
}
// move a piece into the blank space
public function movePiece(puzzleObject:Object, slideEffect:Boolean) {
// get direction of blank space
switch (validMove(puzzleObject)) {
case "up":
movePieceInDirection(puzzleObject,0,-1,slideEffect);
break;
case "down":
movePieceInDirection(puzzleObject,0,1,slideEffect);
break;
case "left":
movePieceInDirection(puzzleObject,-1,0,slideEffect);
break;
case "right":
movePieceInDirection(puzzleObject,1,0,slideEffect);
break;
}
}
// move the piece into the blank spot
public function movePieceInDirection(puzzleObject:Object, dx,dy:int, slideEffect:Boolean) {
puzzleObject.currentLoc.x += dx;
puzzleObject.currentLoc.y += dy;
blankPoint.x -= dx;
blankPoint.y -= dy;
// animate or not
if (slideEffect) {
// start animation
startSlide(puzzleObject,dx*(pieceWidth+pieceSpace),dy*(pieceHeight+pieceSpace));
} else {
// no animation, just move
puzzleObject.piece.x = puzzleObject.currentLoc.x*(pieceWidth+pieceSpace) + horizOffset;
puzzleObject.piece.y = puzzleObject.currentLoc.y*(pieceHeight+pieceSpace) + vertOffset;
}
}
// set up a slide
public function startSlide(puzzleObject:Object, dx, dy:Number) {
if (slideAnimation != null) slideDone(null);
slidingPiece = puzzleObject;
slideDirection = new Point(dx,dy);
slideAnimation = new Timer(slideTime/slideSteps,slideSteps);
slideAnimation.addEventListener(TimerEvent.TIMER,slidePiece);
slideAnimation.addEventListener(TimerEvent.TIMER_COMPLETE,slideDone);
slideAnimation.start();
}
// move one step in slide
public function slidePiece(event:Event) {
slidingPiece.piece.x += slideDirection.x/slideSteps;
slidingPiece.piece.y += slideDirection.y/slideSteps;
}
// complete slide
public function slideDone(event:Event) {
slidingPiece.piece.x = slidingPiece.currentLoc.x*(pieceWidth+pieceSpace) + horizOffset;
slidingPiece.piece.y = slidingPiece.currentLoc.y*(pieceHeight+pieceSpace) + vertOffset;
slideAnimation.stop();
slideAnimation = null;
// check to see if puzzle is complete now
if (puzzleComplete()) {
clearPuzzle();
gotoAndStop("gameover");
}
}
// check to see if all pieces are in place
public function puzzleComplete():Boolean {
for(var i:int=0;i<puzzleObjects.length;i++) {
if (!puzzleObjects[i].currentLoc.equals(puzzleObjects[i].homeLoc)) {
return false;
}
}
return true;
}
// remove all puzzle pieces
public function clearPuzzle() {
for (var i in puzzleObjects) {
puzzleObjects[i].piece.removeEventListener(MouseEvent.CLICK,clickPuzzlePiece);
removeChild(puzzleObjects[i].piece);
}
puzzleObjects = null;
}
}
First, program must know where to place the objects, for them to placed correctly. And best way to do it, is to record piece's initial positions.
Before you set piece's new location, create the Object and take it's initial location.
newPuzzleObject.initialLoc = new Point(newPuzzlePiece.x,newPuzzlePiece.y);
Object creation must come before this part, before piece's initial position changed;
// set location
newPuzzlePiece.x = x*(pieceWidth+pieceSpace) + horizOffset;
newPuzzlePiece.y = y*(pieceHeight+pieceSpace) + vertOffset;
And at the solvePuzzle, place them all back to their initial location.
for(i:uint; i < puzzleObjects.length; i++)
{
puzzleObjects[i].x = puzzleObjects[i].initialLoc.x;
puzzleObjects[i].y = puzzleObjects[i].initialLoc.y;
}

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.

How to align object timer and score in actionscript3.0 to center

I'm doing a matching game.using adobeFlash, actionScript3.0. I have no idea how to align the Timer n Score to the center when game is on.. n where to insert those coding..
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.display.StageAlign;
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 = 8;
private static const boardHeight:uint = 8;
private static const cardHorizontalSpacing:Number = 52;
private static const cardVerticalSpacing:Number = 52;
private static const boardOffsetX:Number = 300;
private static const boardOffsetY:Number = 200;
private static const pointsForMatch:int = 100;
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 gameTime:uint;
// text fields
private var gameScoreField:TextField;
private var gameTimeField: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();
//gameScoreField = center;
////gameScoreField = center;
addChild(gameScoreField);
gameScore = 0;
showGameScore();
// set up the clock
gameTimeField = new TextField();
gameTimeField.x = 450;
//gameTimeField = center;
////gameTimeField.stage = StageAlign.TOP;
addChild(gameTimeField);
gameStartTime = getTimer();
gameTime = 0;
addEventListener(Event.ENTER_FRAME,showTime);
}
// 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).gameTime = clockTime(gameTime);
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) {
firstCard.startFlip(1);
secondCard.startFlip(1);
firstCard = null;
secondCard = null;
flipBackTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,returnCards);
}
public function showGameScore() {
gameScoreField.text = "Score: "+String(gameScore);
}
public function showTime(event:Event) {
gameTime = getTimer()-gameStartTime;
gameTimeField.text = "Time: "+clockTime(gameTime);
}
public function clockTime(ms:int) {
var seconds:int = Math.floor(ms/1000);
var minutes:int = Math.floor(seconds/60);
seconds -= minutes*60;
var timeString:String = minutes+":"+String(seconds+100).substr(1,2);
return timeString;
}
public function playSound(soundObject:Object) {
var channel:SoundChannel = soundObject.play();
}
}
}
When you want to (horizontal) align a DisplayObject in its parent DisplayObject, just do something like this:
child.x = (parent.width - child.width) / 2;
In your code example this would be something like
gameTimeField.x = (this.width - gameTimeField.width) / 2;
This should be inserted, when the child DisplayObject is completely painted, so its width is known.