I am creating a puzzle in which the player have to click on the buttons on the right order or sequence to go to the next level (Scene 2 for example). I don't know how to do it. If any one have any idea to how to achieve this in Action Script.
Thank you
Scene 1:
enter image description here
each number is a button. Now the player has to click in the right order or sequence (1 2 3 4 5 6 7 8) to open the next level (Scene 2)
var checkString:String = "";
//Create event listeners and their functions.
btn1.addEventListener(Mouse.CLICK, oneClick);
btn2.addEventListener(Mouse.CLICK, twoClick);
btn3.addEventListener(Mouse.CLICK, threeClick);
btn4.addEventListener(Mouse.CLICK, fourClick);
btn5.addEventListener(Mouse.CLICK, fiveClick);
btn6.addEventListener(Mouse.CLICK, sixClick);
btn7.addEventListener(Mouse.CLICK, sevenClick);
btn8.addEventListener(Mouse.CLICK, eightClick);
function oneClick(evt:Event):void
{
//In each event listener function, add a letter or
//string to the checkString variable.
checkString += "on";
//Then, see if the string matches or not.
check();
}
function twoClick(evt:Event):void
{
checkString += "tw";
check();
}
function threeClick(evt:Event):void
{
checkString += "th";
check();
}
function fourClick(evt:Event):void
{
checkString += "fo";
check();
}
function fiveClick(evt:Event):void
{
checkString += "fi";
check();
}
function sixClick(evt:Event):void
{
checkString += "si";
check();
}
function sevenClick(evt:Event):void
{
checkString += "se";
check();
}
function eightClick(evt:Event):void
{
checkString += "ei";
check();
}
//If the proper sequence is one, two, three, four, five, six, seven, eight the string would read "ontwthfofisiseei".
function check():void
{
if(checkString == "ontwthfofisiseei")
{
//Clear the checkString for convenience before going on.
clearString();
//CODE TO GO TO NEW FRAME
gotoAndPlay(1, "Scene 3");
}
}
function clearString():void
{
//You will want to have a function for clearing the string.
//This is especially useful if you have a button for "start over."
checkString = "";
}
this the code i used before but it show error in the listener and it doesn't. work
To answer your updated question:
Your error is likely that Mouse.CLICK should be MouseEvent.CLICK.
Your other error is telling you that there is no scene called "Scene 3"
Let's assume you have 8 MovieClips (or buttons) that are on a timeline in Flash/Animate.
One (of many) ways to accomplish this would be the following:
Give each of those buttons an instance name. To make for less code, lets give them the name btn + their respective correct order number - so btn1, btn2, btn3 etc.
You'll need to add a click listener to each button, so they can have something happen when they are clicked.
You could do this 8 times (one for each button): btn1.addEventListener(MouseEvent.CLICK, buttonClick); but to make things simpler, you can just iterate through all the objects on the timeline and add the listener to each object whose name starts with "btn":
var totalBtns:int = 0; //create a var to store how many buttons there are
//loop through each child of the current timeline
var i:int = numChildren;
while(i--){
//if the child's name starts with 'btn'
if(getChildAt(i).name.indexOf("btn") == 0){
//add the click listener
getChildAt(i).addEventListener(MouseEvent.CLICK, buttonClick,false,0,true);
totalBtns++; //increase the total buttons variable by 1
}
}
This also means less work later if you add/remove buttons
You need a way to track when a button was clicked. To accomplish this, we'll use an array.
var clickArray:Array = []; //this creates a new array
//When a button is clicked, you add it to this array
lets create the function that is called when a button is clicked:
function buttonClick(e:Event):void {
//add the item that was just clicked (represented by the event's currentTarget property) to the array
//so if btn1 was just clicked, btn1 would be e.currentTarget
clickArray.push(e.currentTarget);
//now disable the button so it can't be clicked anymore
SimpleButton(e.currentTarget).enabled = false;
//check if all button have been clicked
if(clickArray.length == totalBtns){
//lets go through every item in the array, and see if it's in the right order
var ctr:int = 0; //a counter to keep track of the expected next number var i:int = 0; //iterator for the for loops
for(i=0;i<clickArray.length;i++){
//lets convert everything after the 3rd character of the name to a number - so for btn1, that would be 1
if(parseInt(clickArray[i].name.substring(3)) == ctr + 1){
ctr++; //increment the counter to the next expected number
}else{
break; //leave the for loop early since a click was out of place
}
}
//if the correct order was achieved
if(ctr == totalBtns){
nextScene(); //or however you continue
}else{
//the correct order was NOT acheived
//make all the buttons clickable again
for(i=0;i<clickArray.length;i++){
SimpleButton(clickArray[i]).enabled = true;
}
//reset the array
clickArray = [];
//probably want to tell the user to try again
}
}
}
Related
I am pretty new to as3 and tried searching around for an answer to my question but it seems nothing works. I have an xml loaded file where when the user clicks the correct option (of 4) they get a point scored. I'm trying to disable the button after it has been clicked once but this is not happening. Any help would be greatly appreciated.
Here is the section I have.
function setupButtons():void {
for (var obj:Object in buttons)
{
buttons[obj].addEventListener(MouseEvent.CLICK, checkAnswer);
}
buttons[obj].addEventListener(MouseEvent.MOUSE_UP,disableBtns);
}
function disableBtns(evt:MouseEvent):void {
for (var obj:Object in buttons)
evt.currentTarget.removeEventListener(MouseEvent.MOUSE_UP,disableBtns);
buttons[obj].enabled = false;
}
Here are some comments next to your original code to help explain what is likely happening:
function setupButtons():void {
//you're adding a click listener for every object in `buttons`
for (var obj:Object in buttons)
{
buttons[obj].addEventListener(MouseEvent.CLICK, checkAnswer);
}
//this next line seems out of place,
//it is NOT a part of your for loop above so it will only run once,
//The value of obj will be the LAST item in the for loop above
buttons[obj].addEventListener(MouseEvent.MOUSE_UP,disableBtns);
}
function disableBtns(evt:MouseEvent):void {
//you don't have curly braces on this next for loop line
//this means it's only going to run the line immediately following the loop as part of the loop.
for (var obj:Object in buttons)
//your attempting to remove the same listener over and over again (since this line is in a loop)
evt.currentTarget.removeEventListener(MouseEvent.MOUSE_UP,disableBtns);
//this next line is not part of the loop above.
//I imagine you only want to disable the button that was clicked (evt.currentTarget)
//This will only disable whatever the last value of obj was in the loop above
buttons[obj].enabled = false;
}
Now, here is a simple code refactoring that may help:
//first, just have one click listener for each button, forget the mouse up listener
function setupButtons():void {
for (var obj:Object in buttons){
buttons[obj].addEventListener(MouseEvent.CLICK, btnClick);
}
}
function btnClick(evt:MouseEvent):void {
//If buttons are of the SimpleButton class, you can just disable them
evt.currentTarget.enabled = false;
//OR, if the buttons are not of the SimpleButton class
evt.currentTarget.mouseChildren = false;
evt.currentTarget.mouseEnabled = false;
//OR, just remove the click listener
evt.currentTarget.removeEventListener(MouseEvent.CLICK, btnClick);
//run the checkAnswer function
checkAnswer(evt);
}
To disable all buttons when any 1 is clicked, you could do this:
function btnClick(evt:MouseEvent):void {
for (var obj:Object in buttons){
buttons[obj].removeEventListener(MouseEvent.CLICK, btnClick);
}
//run the checkAnswer function
checkAnswer(evt);
}
I've added the basic targets and applying drag and drop for my puzzle pieces, now Im having trouble making the shuffling aspect. As in, after the player completes or opens up the fla, each time will start the puzzle pieces in random places of the stage. I understand using arrays for shuffling somehow but Im not sure exactly how to achieve this. I've stored the instance of my 19 puzzle pieces inside the array but now I have no idea what to do with this array. Other tutorials were abit out of my league and leaves my head scratching.
Just started doing coding for flash professional so yeah, any help with the shuffling movie clips ie the puzzles pieces would be greatly appreciated.
Heres's my code, Im not posting the whole thing since from P1 to P19 is basically copy pasting:
import flash.events.Event;
stage.addEventListener(Event.ENTER_FRAME, EntFrame)
function EntFrame(e: Event) : void
{
P1.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
function fl_ClickToDrag(event:MouseEvent):void
{
P1.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
function fl_ReleaseToDrop(event:MouseEvent):void
{
P1.stopDrag();
}
if (T1.hitTestObject(P1.Tar1))
{
P1.x = 313.15;
P1.y = 242.75;
}
P19.addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag_19);
function fl_ClickToDrag_19(event:MouseEvent):void
{
P19.startDrag();
}
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop_19);
function fl_ReleaseToDrop_19(event:MouseEvent):void
{
P19.stopDrag();
}
if (T19.hitTestObject(P19.Tar19))
{
P19.x = 624.35;
P19.y = 455.60;
}
}
Here is what I hope is more holistic answer.
First, ditch those inline functions. Right now you make an ENTER_FRAME listener and inside that function you have inline function defined. This means every frame tick (which is tied to your frame rate, not the main timeline), those functions are going to get created again, and since you are adding them as handlers for listeners, they will stay in memory forever.
Here is a way you code this, showing ways to reduce redundancy and get rid of those memory leaks. This assumes the following:
You have 19 objects on the stage called T1 - T19, that represent the possible locations the pieces can go.
You have 19 pieces on the stage called P1 - P19, that, and the numbers correlate to the T locations as per the correct location of the piece.
//let's create a function to randomize the piece location
function seedPieces() {
//create an array consisting of the integers 1 - 19
var unusedSpaces:Vector.<int> = new Vector.<int>;
var i:int;
for (i = 1; i <= 19; i++) {
//populate that array
unusedSpaces.push(i);
}
var curLocation:DisplayObject; //helper var for the loop below
var curPiece:Sprite; //helper var for the loop below
//loop 19 times (from 1 - 19) - one iteration for each piece
for (i = 1; i <= 19; i++) {
curPiece = this["P" + i] as Sprite; //you can get the piece this way, or use an array if you've made one, like `pieces[i];`
trace(curPiece.name);
//splice removes and returns the item at the specified index (in this case a random number between 0 and arrays length less 1) - the second parameter is amount of items to remove (just 1 for this case)
curLocation = this["T" + unusedSpaces.splice(int(Math.random() * unusedSpaces.length), 1)] as DisplayObject;
trace(" ",curLocation.name);
//move the piece to the random location:
curPiece.x = curLocation.x;
curPiece.y = curLocation.y;
}
}
//NOW, as an aside, you should use a loop to add all your listeners for the sake of sanity - if you have them in an array, loop through that, or use the sloppy way like this:
for (var i:int = 1; i <= 19; i++) {
Sprite(this["P" + i]).addEventListener(MouseEvent.MOUSE_DOWN, fl_ClickToDrag);
}
//create a var to hold any piece that is currently being dragged, so you know which piece to stop drag on later
var currentDraggingItem:Sprite;
seedPieces();
function fl_ClickToDrag(event:MouseEvent):void
{
//assign this clicked item to the currentDraggingItem var
currentDraggingItem = event.currentTarget as Sprite;
//bring this one to the front
currentDraggingItem.parent.addChild(currentDraggingItem);
//you can use this one click handler for all pieces
//the piece that was actually clicked, is referenced by event.currentTarget
currentDraggingItem.startDrag();
//add the mouse up listener now that the mouse is currently DOWN
stage.addEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
//listen every frame while dragging
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
}
function fl_ReleaseToDrop(event:MouseEvent):void
{
//if currentDraggingItem has a value, stop drag it
if (currentDraggingItem) {
currentDraggingItem.stopDrag();
//send to the back
currentDraggingItem.parent.addChildAt(currentDraggingItem,0);
}
//remove the mouse up and enter frame listener now that the mouse is UP
stage.removeEventListener(MouseEvent.MOUSE_UP, fl_ReleaseToDrop);
stage.removeEventListener(Event.ENTER_FRAME, EntFrame);
if(checkComplete()){
//game over, do something
}
}
function EntFrame(e: Event) : void
{
//this will snap the peice to the correct spot when the mouse is touching the correct spot
if(currentDraggingItem){
if (this[currentDraggingItem.name.replace("P","T")].hitTestPoint(mouseX,mouseY))
{
currentDraggingItem.x = this[currentDraggingItem.name.replace("P","T")].x;
currentDraggingItem.y = this[currentDraggingItem.name.replace("P","T")].y;
}
}
}
function checkComplete():Boolean {
//use a loop to go through all your pieces and check if they are in the right spot. Again, you could have them in an array, or do it the lazy way
for (var i:int = 1; i <= 19; i++) {
if (!this["T"+i].hitTestObject(this["P"+i]))
{
return false;
}
}
return true;
}
Well, in general you can shuffle with the following code:
var shuffledVector:Vector.<someClass> = new Vector.<someClass>;
while (originalVector.length > 0) {
shuffledVector.push(originalVector.splice(Math.random() * originalVector.length, 1)[0]);
}
Longer, explained version:
var shuffledVector:Vector.<someClass> = new Vector.<someClass>; //We will store our shuffled vector in here
var randomIndex:int; //Random index from the originalVector
var resultVector:Vector.<someClass>; //result from the originalVector.splice(...) function
var randomElement:someClass; //Random element from the originalVector
while (originalVector.length > 0) { //We will reduce the size of the originalVector until the originalVector is empty.
randomIndex = Math.random() * originalVector.length; //Calculate a random index within the range of the originalVector from 0 to originalVector.lenght-1 (note that the range decreases by one on every loop)
randomVector = originalVector.splice(randomIndex, 1); //Use splice to remove one element at the randomly choosen index, we will receive a vector with the removed element...
randomElement = randomVector[0]; //...so we need to access the element
shuffledVector.push(randomElement); //Add the randomly choosen element to our shuffled vector
}
I've written the code for a vector as i suggest to use a vector instead of an array, but the principle behind it is the same for an array.
In your case the originalVector is a vector filled with your P1-P19 Movieclips and someClass would be MovieClip. The originalVector is empty at the end and could be replaced with the shuffled one and of course it would make a lot more sense if you put the code in a seperate function like this:
function Shuffle(originalVector:Vector.<someClass>) : void {
var shuffledVector:Vector.<someClass> = new Vector.<someClass>;
while (originalVector.length > 0) {
shuffledVector.push(originalVector.splice(Math.random() * originalVector.length, 1)[0]);
}
originalVector = shuffledVector;
}
Offtopic, but important for further coding: Someone else already mentioned, that it is not good to add EventListeners on every frame, because it is absolutely unnecessary. You only need to add the Listeners once. Your code is very repetitive, you should use a function which accepts a MovieClip, x and y then call that function 19 times.
e.g.:
function setUpMovieClip(MC:MovieClip, x:int, y:int) : {
MC.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag);
//more code...
}
within the clickToDrag function you can access the MovieClip which was clicked via the event.target property:
function clickToDrag(e:MouseEvent) : {
e.target.startDrag();
//more code...
}
I hope you get the idea.
How can I make a clickable movieclip 'hide' behind another object. Eg.. I have a rabbit movieclip - he is clickable - as he walks behind a tree(MC) he needs to hide behind that tree.
At the moment, if I click on the tree - the mouse click seems to ignore the tree completely and I can still click the unseen rabbit.
var HitCount:Number = 10;
var RabbitG1X:Number = 0;
var RabbitG1Y:Number = 0;
var RabbitG2X:Number = 0;
var RabbitG2Y:Number = 0;
Mouse.hide();
stage.addEventListener(MouseEvent.MOUSE_MOVE, follow);
function follow(evt:MouseEvent)
{
Cursor_mc.x =mouseX;
Cursor_mc.y=mouseY;
}
stage.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:MouseEvent):void
{
if (Cursor_mc.hitTestObject(RabbitG1_mc))
{
trace ("you fed rabbit1 ");
RabbitG1_mc.x = RabbitG1X + 5000;
RabbitG1H_mc.x = RabbitG1X + 1271.85;
RabbitG1H_mc.y = RabbitG1Y + 184.05;
HitCount = HitCount -1;
Dec_txt.text = "" + HitCount + "";
}
if (Cursor_mc.hitTestObject(RabbitG2_mc))
{
trace ("you fed rabbit2 ");
RabbitG2_mc.x = RabbitG2X + 5000;
RabbitG2H_mc.x = RabbitG2X + 1271.85;
RabbitG2H_mc.y = RabbitG2Y + 184.05;
HitCount = HitCount -1;
Dec_txt.text = "" + HitCount + "";
}
if (HitCount ==0)
{
trace("You fed all the rabbits");
}
}
I tried adding this to the tree mc to see if I could kill the mouse when it moved over tree.
Tree2MC.addEventListener(MouseEvent.CLICK, solid);
function solid(e:MouseEvent):void{
Tree2MC.mouseEnabled = false;
}
However, it isn't ideal. I really need a clickable object to hide if it goes behind another object on the stage. So if he is half hidden and I click on the part of the MC still revealed, it will click.. And it didn't work.
First, there is no need to use the hitTest code to figure out what was clicked. You can use the mouse event's .target property to figure that out - that will also solve your issue of knowing if the tree was clicked or the rabbit.
For example:
function clickHandler(event:MouseEvent):void {
if (event.target == RabbitG1_mc){
//.....do you stuff
if (event.target == RabbitG2_mc){
Now, one thing to point out, is the .target of an event could also be a child object of a rabbit (if your rabbit MC had other objects inside it). So to make sure it's consistent, you can do something like this when you initialize your rabbits:
RabbitG1_mc.mouseChildren = false;
RabbitG2_mc.mouseChildren = false;
Alternatively, you could just add mouse event listeners to the rabbits directly instead of one listener on the stage that will catch everything. This way, if an object (tree) is in front of them (and is mouse enabled), the click event will dispatch on the tree instead of the rabbit and the clickHandler won't run.
RabbitG1_mc.addEventListener(MouseEvent.CLICK, clickHandler);
RabbitG2_mc.addEventListener(MouseEvent.CLICK, clickHandler);
function clickHandler(event:MouseEvent):void {
//event.currentTarget is a reference to what you attached the listener to
switch(event.currrentTarget){
case RabbitG1_mc:
//..do your code
break;
case RabbitG2_mc:
//..do your code
break;
}
}
Hey Everyone so I am currently working on a game and the objective is for the user to click on objects on the stage. But the user has to click on the largest objects first before the user clicks on the smaller objects. I wanted to make it that if the user clicks on a smaller object first and not the larger one then the game will be over. I thought I could go about setting this up with booleans for each object on the stage but my if statements arent cutting it here is how I have it set up:
Here are my objects and booleans I use:
//Add box references
public var box_1:MovieClip;
public var box_2:MovieClip;
public var box_3:MovieClip;
public var box_4:MovieClip;
//Booleans
private var b1:Boolean;
private var b2:Boolean;
private var b3:Boolean;
private var b4:Boolean;
now I set all the Booleans to false and if the user clicks on one of the objects I set the Boolean to true.
Here are my if statements tied to my main ENTER_FRAME Listener:
private function level_1():void
{
if (b1)
{
mainScreen.box_1.gotoAndPlay("B1GONE");
b1 = false;
}else
if (b2)
{
mainScreen.box_2.gotoAndPlay("B2GONE");
b2 = false;
}else
if (b3)
{
mainScreen.box_3.gotoAndPlay("B3GONE");
b3 = false;
}else
if (b2 && !b1)
{
endGameCondition();
}
}
On this statement:
if (b2 && !b1)
{
endGameCondition();
}
I was trying to state that if box_2 is true meaning that its clicked on and box_1 hasnt been clicked on yet which is the larger object then the game is now over due to the user not clicking on the largest object first. I have it setup to where box_1 is the largest object and the others are the next size down.
Can anyone see why this isnt working correctly or if there is a better method in doing this?
**** UPDATE HOW MY MAIN CLASS IS SETUP NOW **************
Where I add all my Movie clips and variables:
public class boxTapEngine extends MovieClip
{
//Screens
private var mainScreen:mcMainScreen;
//Add box references
public var box_1:MovieClip;
public var box_2:MovieClip;
public var box_3:MovieClip;
public var box_4:MovieClip;
private var aBoxesArray:Array;
in my constructor function:
aBoxesArray = [box_1, box_2, box_3, box_4];
//AddMainScreen
mainScreen = new mcMainScreen();
mainScreen.x = (stage.stageWidth / 2);
mainScreen.y = (stage.stageHeight / 2);
stage.addChild(mainScreen);
//Initiate numbers
nLevel = 1;
for each(var box:MovieClip in aBoxesArray)
{
box.addEventListener(MouseEvent.CLICK, boxClick);
}
finally on the boxClick function:
private function boxClick(e:MouseEvent):void
{
var box:MovieClip = e.currentTarget as MovieClip; //get a reference to one that was just clicked
box.mouseEnabled = false; //we'll use this as a flag to know if it's been clicked yet
box.gotoAndPlay("BGONE");
//check to see if previous boxes have been clicked.
//this will iterate through all the boxes in order
for (var i:int = 0; i < aBoxesArray.length; i++)
{
if(aBoxesArray[i] == box) return; //if we've reached the currently clicked box, all is good, no need to keep checking so let's exit this loop and function
if (!aBoxesArray[i].mouseEnabled)
{ //one of the previous boxes hasn't been clicked yet
endGameCondition();
}
}
}
Probably isn't working because your final else if statement won't ever be reached (because you're handling b2 == true earlier on which will then bypass all other else statements). Plus your setting b2 to false when you handle it earlier, so it will always be false by the time it gets your final statement.
You need to move that final else if before you check for the other things. See code comments:
//Do this first, and not as a else if
if (b2 && !b1){
endGameCondition();
return; //no need to check checking things if it's game over
}
//now you can do the rest
if (b1)
{
mainScreen.box_1.gotoAndPlay("B1GONE");
b1 = false;
}else
if (b2)
{
mainScreen.box_2.gotoAndPlay("B2GONE");
b2 = false;
}else
if (b3)
{
mainScreen.box_3.gotoAndPlay("B3GONE");
b3 = false;
}
As an aside, you don't need the enter frame handler, you can just check everything on click. Something like this would work:
var boxes:Array = [box_1,box_2,box_3,box_4]; //make sure this is in order of what needs to be clicked first
//if you wanted to actually sort them dynamically based off total size (regardless of what order you've stuffed them in the array), you could add in something like this, which will order them from biggest to smallest:
boxes.sort(function(a,b){
//compare which item has a greater total area (width * height)
if(a.width * a.height > b.width * b.height) return -1; //A is bigger, so put a before b in the array
if(a.width * a.height < b.width * b.height) return 1; //put b before a in the array
return 0; //return 0 if they are the same
});
for each(var box:MovieClip in boxes){
box.addEventListener(MouseEvent.CLICK, boxClick,false,0,true);
}
function boxClick(e:Event):void {
var box:MovieClip = e.currentTarget as MovieClip; //get a reference to one that was just clicked
box.mouseEnabled = false; //we'll use this as a flag to know if it's been clicked yet
box.gotoAndPlay("BGONE");
//or you could just do this to get rid of the box:
if(box.parent) box.parent.removeChild(box);
//check to see if previous boxes have been clicked.
//this will iterate through all the boxes in order
for(var i:int=0;i<boxes.length;i++){
if(boxes[i] == box) return; //if we've reached the currently clicked box, all is good, no need to keep checking so let's exit this loop and function
if(!boxes[i].mouseEnabled){ //one of the previous boxes hasn't been clicked yet
endGameCondition();
}
}
}
//Store your clips in an array
var myClips:Array = [mc1,mc2,mc3,mc4];
//get the clip sizes and store it to an array.
var sizes:Array = new Array();
for (var i:uint = 0; i < myClips.length; i++) {
sizes.push(myClips[i].width);
}
//apply Numeric array sort.
sizes.sort(Array.NUMERIC);
function onClickAction(e:MouseEvent):void {
//Check wheather the array is empty or not.
if (sizes.length != 0) {
//Check wheather the clicked object bigger or not.
if (e.target.width == sizes[sizes.length - 1]) {
trace("Bigger");
e.target.alpha = .5;
sizes.splice(sizes.length-1,1);
} else {
trace("Smaller");
}
}
}
I am struggling making 3 buttons be able to go to a frame when the buttons are clicked in a certain order. For example the buttons are labeled
button 1
button 2
button 3
and the order that they are needed to be clicked in is button 3, button 1, button 2 for them to go to the next frame, How can I achieve this?
This is what I have so far.
var clicked = MouseEvent.CLICK
var buttons = new Array(YellowButton, BlueButton, RedButton);
for (var a=0; a<buttons.lenght; a++)
{
buttons[a].buttonMode=true
buttons[a].addEventListener(clicked,RedYellowBlue);
}
function RedYellowBlue(event:MouseEvent):void { gotoAndStop(20); }
Thanks for your help in advance
What I recommend is to create a string object that will be assembled by clicking the buttons, and then compared to a particular sequence that you set. The beauty of this is that you can make it work for sequences of any length.
The biggest thing here is, you don't want the same event listener on all three buttons. You want their actions to be unique, otherwise, clicking one is the same as clicking all the others (which is your current code's problem.)
var checkString:String = "";
//Create event listeners and their functions.
YellowButton.addEventListener(Mouse.CLICK, yellowClick);
RedButton.addEventListener(Mouse.CLICK, redClick);
BlueButton.addEventListener(Mouse.CLICK, blueClick);
function yellowClick(evt:Event):void
{
//In each event listener function, add a letter or
//string to the checkString variable.
checkString += "y";
//Then, see if the string matches or not.
check();
}
function redClick(evt:Event):void
{
checkString += "r";
check();
}
function blueClick(evt:Event):void
{
checkString += "b";
check();
}
//If the proper sequence is red, yellow, blue, the string would read "ryb".
function check():void
{
if(checkString == "ryb")
{
//Clear the checkString for convenience before going on.
clearString();
//CODE TO GO TO NEW FRAME
gotoAndStop(20);
}
else
{
//Make sure the string is at least 3 characters long.
if(checkString.length >= 3)
{
clearString();
gotoAndStop(foo);
}
}
}
function clearString():void
{
//You will want to have a function for clearing the string.
//This is especially useful if you have a button for "start over."
checkString = "";
}
That should be sufficient to get you started. If you need additional help, feel free to comment on my answer.
To consolidate #JasonMc92's answer, you could use the name of the target as the checkString letter so you only need to call one function for all buttons.
yellowButton.addEventListener(MouseEvent.CLICK, redYellowBlue);
redButton.addEventListener(MouseEvent.CLICK, redYellowBlue);
blueButton.addEventListener(MouseEvent.CLICK, redYellowBlue);
function redYellowBlue(e:MouseEvent){
checkString += e.currentTarget.name.substr(0,1);
check();
}
//... continue on with Jason's functions
Or, since you've set them up in an array, you could also just use the buttons' indices as your check sequence. Something like:
function redYellowBlue(e:MouseEvent){
checkString += String(buttons.indexOf(e.currentTarget));
check();
}
function check(){
if (checkString == '201') {
// ... handle correct sequence
}
}
Also, just a best practice tip:
only use a leading capital for names of classes. Instance names and function names should start with a lowercase. (leading cap won't break anything, but it's standard practice)
//Here is code
var buttons:Array = new Array(YellowButton, BlueButton, RedButton);
for(var i:int=0;i< buttons.length;i++)
{
buttons[a].buttonMode=true
buttons[a].addEventListener(MouseEvent.CLICK,buttonsClickHandler);
}
function buttonsClickHandler(event:MouseEvent):void {
var button:MovieClip = MovieClip(event.target);
switch(button.name)
{
case "YellowButton":
case "BlueButton":
gotoAndStop(2);
break;
case "RedButton":
gotoAndStop(3);
break;
}
}