I'm creating Flash "memory" game, Idea to discover 2 equal cards. But when I choose 1, if second card is wrong It discover only for half second, but this is not enough. I need to make that second card will be shown for 2-3 seconds. How can I add timer?
Here is part of code:
else
{
trace("wrong");
_message = "wrong";
message_txt.text = _message;
_firstCard.gotoAndPlay("flipBack");
event.currentTarget.gotoAndPlay("flipBack");
_firstCard.addEventListener(MouseEvent.CLICK, checkCards);
event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards);
_firstCard = undefined;
}
Thank you for answers.
UPDATED WITH FULL CODE
package
{
import flash.display.MovieClip;
import Card;
import Boarder;
import BlueBoard;
import flash.events.MouseEvent;
import RedBoard;
import Snow;
public class MemoryGame extends MovieClip
{
private var _card:Card;
private var _boarder:Boarder;
private var _blueBoard:BlueBoard;
private var _cardX:Number;
private var _cardY:Number;
private var _firstCard:*;
private var _totalMatches:Number;
private var _currentMatches:Number;
private var _redBoard:RedBoard;
private var _snow:Snow;
private var _cards:Array;
public var _message:String;
public function MemoryGame()
{
_cards = new Array();
_totalMatches = 4;
_currentMatches = 0;
createCards();
}
private function createCards():void
{
_cardX = 45;
_cardY = 10;
for(var i:Number = 0; i < 2; i++)
{
_card = new Card();
addChild(_card);
_boarder = new Boarder();
_card.setType(_boarder);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var j:Number = 0; j < 2; j++)
{
_card = new Card();
addChild(_card);
_blueBoard = new BlueBoard();
_card.setType(_blueBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
_cardX = 45;
_cardY = _card.height + 30;
for(var k:Number = 0; k < 2; k++)
{
_card = new Card();
addChild(_card);
_redBoard = new RedBoard();
_card.setType(_redBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var l:Number = 0; l < 2; l++)
{
_card = new Card();
addChild(_card);
_snow = new Snow();
_card.setType(_snow);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
randomizeCards(_cards);
}
private function checkCards(event:MouseEvent):void
{
event.currentTarget.removeEventListener(MouseEvent.CLICK, checkCards);
if(_firstCard == undefined)
{
_firstCard = event.currentTarget;
}
else if(String(_firstCard._type) == String(event.currentTarget._type))
{
trace("match");
_message = "match";
message_txt.text = _message;
_firstCard = undefined;
_currentMatches ++;
if(_currentMatches >= _totalMatches)
{
trace("YOU WIN !!!");
_message = "YOU WIN !!!";
message_txt.text = _message;
}
}
else
{
trace("wrong");
_message = "wrong";
message_txt.text = _message;
_firstCard.gotoAndPlay("flipBack");
event.currentTarget.gotoAndPlay("flipBack");
_firstCard.addEventListener(MouseEvent.CLICK, checkCards);
event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards);
_firstCard = undefined;
}
}
private function randomizeCards(cards:Array):void
{
var randomCard1:Number;
var randomCard2:Number;
var card1X:Number;
var card1Y:Number;
for(var i:Number = 0; i < 10; i++)
{
randomCard1 = Math.floor(Math.random() * cards.length);
randomCard2 = Math.floor(Math.random() * cards.length);
card1X = cards[randomCard1].x;
card1Y = cards[randomCard1].y;
cards[randomCard1].x = cards[randomCard2].x;
cards[randomCard1].y = cards[randomCard2].y
cards[randomCard2].x = card1X;
cards[randomCard2].y = card1Y;
}
}
}
}
You can use http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html. BTW, do note that Timer constructor's default 2nd parameter is 0 implying that the timer would run indefinitely. Be sure to mark that as 1 for your case.
You need to move code in your 'else' block to another function and setup the timer instead in the else block.
The final code would look something like this:
else
{
trace("wrong");
_message = "wrong";
message_txt.text = _message;
_secondCard = event.currentTarget;//You need to have this variable defined alongwith _firstCard
var timer:Timer = new Timer(2000, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, flipBack);
timer.start();
}
and the function would have:
protected function flipBack(event:TimerEvent):void
{
_firstCard.gotoAndPlay("flipBack");
_sedondCard.gotoAndPlay("flipBack");
_firstCard.addEventListener(MouseEvent.CLICK, checkCards);
_secondCard.addEventListener(MouseEvent.CLICK, checkCards);
_firstCard = _secondCard = undefined;
}
HTH.
If it's only to wait a certain amount of time, you can use setTimeout (flash.utils)
http://livedocs.adobe.com/flash/9.0_fr/ActionScriptLangRefV3/flash/utils/package.html#setTimeout()
Related
I have written a drag and drop game and, for the most part, it works.
It runs and does what I need it to do.
However, I cannot figure out two things.
How to remove the toy objects from the screen and re-add them after game over.
How to remove the event listeners for dragging/collision action after game over has initiated.
At the moment, after score is displayed you can still drop items in the toybox and make the score rise even when game over has been displayed.
Does anyone have any idea what I am doing wrong?
I would love to figure this out but it is driving me crazy.
Any help would be great.
Here is my code ...
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.Font;
import flash.filters.GlowFilter;
public class MainGame extends MovieClip {
const BG_SPEED:int = 5;
const BG_MIN:int = -550;
const BG_MAX:int = 0;
const PBG_SPEED:int = 3;
var bg:BackGround = new BackGround;
var paraBg:ParaBg = new ParaBg;
var toybox:TargetBox = new TargetBox;
var toy:Toy = new Toy;
var tryAgain:TryAgain = new TryAgain;
var cheer:Cheer = new Cheer;
var eightBit:EightBit = new EightBit;
var countDown:Number = 30;
var myTimer:Timer = new Timer(1000, 30);
var myText:TextField = new TextField;
var myText2:TextField = new TextField;
var myTextFormat:TextFormat = new TextFormat;
var myTextFormat2:TextFormat = new TextFormat;
var font1:Font1 = new Font1;
var kids:Kids = new Kids;
var count:int = 0;
var finalScore:int = 0;
var score:Number = 0;
var toy1:Toy1 = new Toy1;
var toy2:Toy2 = new Toy2;
var toy3:Toy3 = new Toy3;
var toy4:Toy4 = new Toy4;
var toy5:Toy5 = new Toy5;
var toy6:Toy6 = new Toy6;
var toy7:Toy7 = new Toy7;
var toy8:Toy8 = new Toy8;
var toy9:Toy9 = new Toy9;
var toy10:Toy10 = new Toy10;
var toy11:Toy11 = new Toy11;
var toy12:Toy12 = new Toy12;
var toy13:Toy13 = new Toy13;
var toy14:Toy14 = new Toy14;
var toy15:Toy15 = new Toy15;
var toy16:Toy16 = new Toy16;
var toy17:Toy17 = new Toy17;
var toy18:Toy18 = new Toy18;
var toy19:Toy19 = new Toy19;
var toy20:Toy20 = new Toy20;
var toyArray:Array = new Array(toy1, toy2, toy3, toy4, toy5, toy6, toy7, toy8, toy9, toy10, toy11, toy12, toy13, toy14, toy15, toy16, toy17, toy18, toy19, toy20);
public function mainGame():void
{
trace("HI");
eightBit.play(0, 9999);
addChildAt(paraBg, 0);
addChildAt(bg, 1);
addChildAt(kids, 2);
kids.x = 310;
kids.y = 200;
addChild(toy);
toy.x = 306;
toy.y = 133;
addChild(toybox);
toybox.x = 295;
toybox.y = 90;
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
for (var i:int = 0; i < toyArray.length; i++)
{
addToys(1140 * Math.random() + 20, 170 * Math.random() + 230);
}
}
public function bgScroll (e:Event)
{
stage.addEventListener(MouseEvent.MOUSE_UP, arrayDrop);
myTimer.addEventListener(TimerEvent.TIMER, countdown);
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.start();
e.target.addEventListener(Event.ENTER_FRAME, collision);
if (stage.mouseX > 600 && bg.x > BG_MIN)
{
bg.x -= BG_SPEED;
paraBg.x -= PBG_SPEED;
for (var m:int=0; m< toyArray.length; m++)
{
(toyArray[m] as MovieClip).x -=BG_SPEED
}
}
else if (stage.mouseX < 50 && bg.x < BG_MAX)
{
bg.x += BG_SPEED;
paraBg.x += PBG_SPEED;
for (var j:int=0; j< toyArray.length; j++)
{
(toyArray[j] as MovieClip).x +=BG_SPEED
}
}
for (var k:int = 0; k < toyArray.length; k++)
{
toyArray[k].addEventListener(MouseEvent.MOUSE_DOWN, arrayGrab);
}
bg.addEventListener(Event.ENTER_FRAME, bgScroll);
} // End of BGScroll
public function collision (e:Event)
{
for (var l:int=0; l< toyArray.length; l++)
{
if (toyArray[l].hitTestObject(toy))
{
removeChild(toyArray[l]);
toyArray[l].x=100000;
toybox.gotoAndPlay(2);
cheer.play(1, 1);
score = score + 10;
trace(score);
}
if (score == 200)
{
timerDone();
myTimer.stop();
}
}
}
public function arrayGrab(e:MouseEvent)
{
e.target.startDrag();
}
public function arrayDrop(e:MouseEvent)
{
stopDrag();
}
public function resetGame(e:Event):void {
trace("CLICK");
countDown = 30;
myText.text = "0" + countDown.toString();
myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone);
myTimer.reset();
removeChild(tryAgain);
myText2.visible = false;
score = 0;
}
public function countdown(e:TimerEvent):void
{
if (countDown > 0)
{
countDown--;
}
if (countDown < 10)
{
myText.text = "0" + countDown.toString();
myText.x = 270;
displayText();
}
else if (countDown < 20 && countDown > 9)
{
myText.text = countDown.toString();
myText.x = 280;
displayText();
}
else
{
myText.text = countDown.toString();
myText.x = 270;
displayText();
}
} // end of countdown function
public function displayText():void
{
myText.filters = [new GlowFilter(0x00FF00, 1.0, 5, 5, 4)];
addChild(myText);
myText.width = 500, myText.height = 50, myText.y = 10;
myTextFormat.size = 50, myTextFormat.font = font1.fontName;
myText.setTextFormat(myTextFormat);
}
public function displayText2():void
{ myText2.filters = [new GlowFilter(0xFF0000, 1.0, 5, 5, 4)];
addChild(myText2);
myText2.width = 500, myText2.height = 35, myText2.x = 204, myText2.y = 200;
myTextFormat2.size = 30, myTextFormat2.font = font1.fontName;
myText2.setTextFormat(myTextFormat2);
}
public function timerDone(e:TimerEvent=null):void
{
if (countDown == 0)
{
count = 0;
finalScore = score;
}
else
{
count = (30) - (myTimer.currentCount);
finalScore = (count * 10) + (score);
}
myText.text = "GAME OVER!";
myText.x = 195;
displayText();
myText2.text = "Your score = " + (finalScore);
displayText2();
addChild(tryAgain);
tryAgain.x = 300;
tryAgain.y = 300;
tryAgain.addEventListener(MouseEvent.CLICK, resetGame);
}
} // End of class
} //End of package
Nevermind ... solved it.
Easiest was was to change
function addToys(xpos:int, ypos:int)
{
addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
To
function addToys(xpos:int, ypos:int)
{
stage.addChild(toyArray[i]);
toyArray[i].x = xpos;
toyArray[i].y = ypos;
}
And then, in the timerDone function I added thisif statement ...
for (var m = 0; m < toyArray.length; m++) {
if (stage.contains(toyArray[m])) {
stage.removeChild(toyArray[m]);
}
Worked a treat!
I have tested out my code and the addchild won't work. No errors are outputted.
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var player:MovieClip;
public var level:Number = 0;
public var scoreLabel:TextField = new TextField
public var levelLabel:TextField = new TextField
public var chancesLabel:TextField = new TextField
public var scoreText:TextField = new TextField
public var levelText:TextField = new TextField
public var chancesText:TextField = new TextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLabel.text = "Score:";
levelLabel.text = "level:";
chancesLabel.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLabel.y = SCOREBOARD_Y;
levelLabel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_Y;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
}
public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = new Array();
level = 1;
levelText.text = level.toString();
addChild(player);
player.startDrag(true,new Rectangle(0,0,550,400))
gameState = STATE_PLAY
}
public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.random()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.random()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
public function moveEnemies():void{
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions():void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}
else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
I have already tried adding this. and stage. in front of addchild and it still doesn't work.
This inside a file called Game.as
When you create your Game instance you need to add it as a child to the stage:
// I would probably rename the variable to 'game'
// 1st character of a variable name is conventionally lower-case
// var game:Game = new Game();
var Script:Game = new Game();
this.addChild(Script);
The code below are inside a file called Script_1.as
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var paly:MovieClip;
public var level:Number = 0;
public var scoreLable:TextField = newTextField
public var levelLable:TextField = newTextField
public var chancesLable:TextField = newTextField
public var scoreText:TextField = newTextField
public var levelText:TextField = newTextField
public var chancesText:TextField = newTextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLable.text = "Score:";
levelLable.text = "level:";
chancesLable.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLable.y = SCOREBOARD_Y;
levelLablel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
//public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = newArray();
level = 1;
levelText.text = leveltoString();
addChild(player);
player.startDrag(true,newRectangle(0,0,550,400))
gameState = STATE_PLAY
}
//public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
//public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.randome()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.randome()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
//public function moveEnemies():void{
/var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions();void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
The Error Reports are:
The Public Attribute Can Only Be Used In A Package
(I put // before these Error Lines to mark them. They are not in the original code.)
Syntax error: expecting identifier before var.
Syntax error: expecting rightbrace before semicolon.
(I put / before these Errors. they are on the same line and the / is not in the original code either.)
Try rename your file to Game.as.
try to add a } after your switch case to close the function gameLoop().
PS:
Is it really your code ? Math.randome() ? newTextField ? newArray() ? public function testCollisions();void ? (;void)
I'm creating Flash "memory" game, Idea to discover 2 equal cards. And I need to make "Try again" button, which remove all cards and spawn new.
Here is main game function:
public function MemoryGame()
{
tryAgain.addEventListener(MouseEvent.CLICK, darKarta);
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
txtTime = new TextField();
addChild(txtTime);
tmpTime = timer.currentCount;
timer.start();
_cards = new Array();
_totalMatches = 18;
_currentMatches = 0;
createCards();
}
Here is createCards function:
private function createCards():void
{
_cardX = 45;
_cardY = 10;
for(var i:Number = 0; i < 2; i++)
{
_card = new Card();
addChild(_card);
_boarder = new Boarder();
_card.setType(_boarder);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 5;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var j:Number = 0; j < 2; j++)
{
_card = new Card();
addChild(_card);
_blueBoard = new BlueBoard();
_card.setType(_blueBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 5;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var r:Number = 0; r < 2; r++)
{
_card = new Card();
addChild(_card);
_penktas = new Penktas();
_card.setType(_penktas);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 5;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
And here is removeCard function:
function removeCards(e:MouseEvent):void
{
//for(var iv:Number = 0; iv < 18; iv++)
{
addEventListener(Event.ENTER_FRAME, remCards);
//}
}
function remCards(evt:Event):void
{
if (contains(_card)) {
removeChild(evt.currentTarget._card);
}
}
But It removes only last card, I don't know how to make to delete them all. Have you any ideas? Thank you.
One way would be to add all the cards inside a container MovieClip and not directly to the stage.
CardContainer.addChild(_card);
and when you want to remove all the cards then either remove the CardContainer MovieClip and re add it to the stage. or you can do this in your removeCards function to remove all cards from it like :
function removeCards(e:MouseEvent):void
{
while(CardContainer.numChildren > 0)
{
CardContainer.removeChildAt(0);
}
}
I'm creating Flash "memory" game, Idea to discover 2 equal cards. I need to add "Timer" in top of window which count in how many seconds all cards will be descovered.
Here is my code:
package
{
import flash.display.MovieClip;
import Card;
import Boarder;
import BlueBoard;
import flash.events.MouseEvent;
import RedBoard;
import Snow;
public class MemoryGame extends MovieClip
{
private var _card:Card;
private var _boarder:Boarder;
private var _blueBoard:BlueBoard;
private var _cardX:Number;
private var _cardY:Number;
private var _firstCard:*;
private var _totalMatches:Number;
private var _currentMatches:Number;
private var _redBoard:RedBoard;
private var _snow:Snow;
private var _cards:Array;
public var _message:String;
public function MemoryGame()
{
_cards = new Array();
_totalMatches = 4;
_currentMatches = 0;
createCards();
}
private function createCards():void
{
_cardX = 45;
_cardY = 10;
for(var i:Number = 0; i < 2; i++)
{
_card = new Card();
addChild(_card);
_boarder = new Boarder();
_card.setType(_boarder);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var j:Number = 0; j < 2; j++)
{
_card = new Card();
addChild(_card);
_blueBoard = new BlueBoard();
_card.setType(_blueBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
_cardX = 45;
_cardY = _card.height + 30;
for(var k:Number = 0; k < 2; k++)
{
_card = new Card();
addChild(_card);
_redBoard = new RedBoard();
_card.setType(_redBoard);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
for(var l:Number = 0; l < 2; l++)
{
_card = new Card();
addChild(_card);
_snow = new Snow();
_card.setType(_snow);
_card.x = _cardX;
_card.y = _cardY;
_cardX += _card.width + 50;
_card.addEventListener(MouseEvent.CLICK, checkCards);
_cards.push(_card);
}
randomizeCards(_cards);
}
private function checkCards(event:MouseEvent):void
{
event.currentTarget.removeEventListener(MouseEvent.CLICK, checkCards);
if(_firstCard == undefined)
{
_firstCard = event.currentTarget;
}
else if(String(_firstCard._type) == String(event.currentTarget._type))
{
trace("match");
_message = "match";
message_txt.text = _message;
_firstCard = undefined;
_currentMatches ++;
if(_currentMatches >= _totalMatches)
{
trace("YOU WIN !!!");
_message = "YOU WIN !!!";
message_txt.text = _message;
}
}
else
{
trace("wrong");
_message = "wrong";
message_txt.text = _message;
_firstCard.gotoAndPlay("flipBack");
event.currentTarget.gotoAndPlay("flipBack");
_firstCard.addEventListener(MouseEvent.CLICK, checkCards);
event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards);
_firstCard = undefined;
}
}
private function randomizeCards(cards:Array):void
{
var randomCard1:Number;
var randomCard2:Number;
var card1X:Number;
var card1Y:Number;
for(var i:Number = 0; i < 10; i++)
{
randomCard1 = Math.floor(Math.random() * cards.length);
randomCard2 = Math.floor(Math.random() * cards.length);
card1X = cards[randomCard1].x;
card1Y = cards[randomCard1].y;
cards[randomCard1].x = cards[randomCard2].x;
cards[randomCard1].y = cards[randomCard2].y
cards[randomCard2].x = card1X;
cards[randomCard2].y = card1Y;
}
}
}
}
EDIT:
And I have one more question. When I will add this game to PHP, how can I add username and his time to database? I need write code in Action Script (swf file) or I can do it in php later? I mean in php can I use any method to get time from swf file and write it to database?
Could you help me? Thank you very much.
Here is an example of how to use the Timer class (flash.utils.Timer) to accomplished what you're asking:
var timer:Timer; //import flash.utils.Timer;
var txtTime:TextField;
var tmpTime:Number; //this will store the time when the game is started
//your constructor:
public function MemoryGame()
{
timer = new Timer(1000); //create a new timer that ticks every second.
timer.addEventListener(TimerEvent.TIMER, tick, false, 0, true); //listen for the timer tick
txtTime = new TextField();
addChild(txtTime);
tmpTime = flash.utils.getTimer();
timer.start(); //start the timer
//....the rest of your code
}
private function tick(e:Event):void {
txtTime.text = showTimePassed(flash.utils.getTimer() - tmpTime);
}
//this function will format your time like a stopwatch
function showTimePassed(startTime:int):String {
var leadingZeroMS:String = ""; //how many leading 0's to put in front of the miliseconds
var leadingZeroS:String = ""; //how many leading 0's to put in front of the seconds
var time = getTimer() - startTime; //this gets the amount of miliseconds elapsed
var miliseconds = (time % 1000); // modulus (%) gives you the remainder after dividing,
if (miliseconds < 10) { //if less than two digits, add a leading 0
leadingZeroMS = "0";
}
var seconds = Math.floor((time / 1000) % 60); //this gets the amount of seconds
if (seconds < 10) { //if seconds are less than two digits, add the leading zero
leadingZeroS = "0";
}
var minutes = Math.floor( (time / (60 * 1000) ) ); //60 seconds times 1000 miliseocnds gets the minutes
return minutes + ":" + leadingZeroS + seconds + "." + leadingZeroMS + miliseconds;
}
//in your you-win block of code:
var score = flash.utils.getTimer() - tmpTime; //this store how many milliseconds it took them to complete the game.
This creates a timer that will tick every second, and update a text field with the current amount of seconds elapsed
As per the second part of your request, here is a way you can do this (the database work needs to be done in PHP, this shows you how to send the data to a php page)
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, scoreSaveResponse,false,0,true);
var request:URLRequest = new URLRequest("http://mysite.com/score.php");
var urlVars:URLVariables = new URLVariables();
urlVars.time = flash.utils.getTimer() - tmpTime;
urlVars.userName = "yourUserName";
//add any other parameters you want to pass to your PHP page
request.method = URLRequestMethod.POST;
urlLoader.data = urlVars;
urlLoader.load(request);
function scoreSaveResponse(e:Event):void {
//whatever you return from the php page is found in urlLoader.data
}