actionscript 3 sleep? - actionscript-3

I have a simple actionscript function
var string:String = "TEXT REMOVED";
var myArray:Array = string.split("");
addEventListener(Event.ENTER_FRAME, frameLooper);
function frameLooper(event:Event):void {
if(myArray.length > 0) {
text1.appendText(myArray.shift());
}else{
removeEventListener(Event.ENTER_FRAME, frameLooper);
}
}
And I want to have it sleep after calling the framelooper so it is a little bit slower. How could I do this?
btw, I'm fairly new and found this code on a tutorial, it's a text typing effect, if there is a better way of doing this please let me know.

Use a Timer:
var string:String = "TEXT REMOVED";
var myArray:Array = string.split("");
var timer : Timer = new Timer (1000, myArray.length);
timer.addEventListener (TimerEvent.TIMER, frameLooper);
timer.start();
function frameLooper(event:Event):void {
text1.appendText(myArray.shift());
}
This will execute the frameLooper on every second for exactly as many times as the length of the array.

I'm not saying this is better than the timer method, just an option
var string:String = "TEXT REMOVED";
var myArray:Array = string.split("");
addEventListener(Event.ENTER_FRAME, frameLooper);
const WAIT_TIME:int = 10;
var i:int = 0;
function frameLooper(event:Event):void {
if(myArray.length > 0) {
if(i==0){
trace(myArray.shift());
i = WAIT_TIME;
};
} else {
removeEventListener(Event.ENTER_FRAME, frameLooper);
}
i--;
}

Related

flash action-script 3 save and load

Hey Guys I'm working on a game on flash action script 3 and i reached with my code to the point that i have already added a mute button which works perfectly but what i want to do is to keep it muted while in the game even if i closed the game re open it.
one another thing is that i want the game to be saved even if i closed it and re opened it exactly the way i left it.
so please help me guys here is my code below
var foundObjects:Number=0
var triesNumber:Number=0
stop()
import flash.net.SharedObject;
var mySo:SharedObject = SharedObject.getLocal("squaresGame");
if(mySo.data.levelNumber==null)
mySo.data.levelNumber="0.01"
//mySo.data.levelNumber
var level:Number=mySo.data.levelNumber
var sTransform1:SoundTransform = new SoundTransform(1,0);
function setMute1(vol){
sTransform1.volume = vol;
SoundMixer.soundTransform = sTransform1;
}
levelText.text=(level*100).toString()
var turkeyArray:Array = new Array();
turkeyArray[1] = m1;
turkeyArray[2] = m2;
turkeyArray[3] = m3;
turkeyArray[4] = m4;
turkeyArray[5] = m5;
turkeyArray[6] = m6;
turkeyArray[7] = m7;
turkeyArray[8] = m8;
turkeyArray[9] = m9;
m1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m2.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m3.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m4.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m5.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m6.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m7.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m8.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
m9.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
event.currentTarget.play()
testFoundObject(event.currentTarget)
}
function testFoundObject(mc:Object):void
{
if(mc.hitTestObject(apple1) || mc.hitTestObject(apple2)||mc.hitTestObject(apple3))
{
foundObjects++
applesquresound.play()
}
else
emptysquresound.play()
trace(foundObjects)
triesNumber++
if(triesNumber>=3)
if(foundObjects>=3)
{
level+=0.01
mySo.data.levelNumber=level.toFixed(2)
levelText.text=(level*100).toString()
yes.play()
}
else{
no.play()
}
}
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler(event:Event):void
{
if(m1.alpha<1)
for(var counter:Number=1;counter<=9;counter++){
MovieClip(turkeyArray[counter]).alpha+=level
}
}
button_1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_2);
function fl_MouseClickHandler_2(event:MouseEvent):void
{
gotoAndPlay(1)
}
toggleMuteBtn.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler_3);
function fl_MouseClickHandler_3(event:MouseEvent):void
{
if(Mute1 == false) {
Mute1 = true;
setMute1(1);
toggleMuteBtn.gotoAndStop(1)
} else {
Mute1 = false;
setMute1(0);
toggleMuteBtn.gotoAndStop(2)
}
}
var locationMC:MovieClip=MovieClip(turkeyArray[randomRange(1,9)]);
apple1.x=locationMC.x
apple1.y=locationMC.y
locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple2.x=locationMC.x
apple2.y=locationMC.y
while(apple2.hitTestObject(apple1) || apple2.hitTestObject(apple3))
{locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple2.x=locationMC.x
apple2.y=locationMC.y
}
locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple3.x=locationMC.x
apple3.y=locationMC.y
while(apple3.hitTestObject(apple1) || apple3.hitTestObject(apple2))
{locationMC=MovieClip(turkeyArray[randomRange(1,9)]);
apple3.x=locationMC.x
apple3.y=locationMC.y
}
function randomRange(minNum:Number, maxNum:Number):Number
{
return (Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum);
}
You can use SharedObject class to store and load information about sound muting. As I see in your code, you already using this class for storing levelNumber, so I believe its not a challenge for you.

How can i check by actionscript 3 if every items of an array had hitTestObject the items of the second array

I have this code for a drag and drop game.
How can i check by actionscript 3 if every item of an array had hitTestObject the items of the second array so something else can happens for example show a well done message.
var hitArray:Array = new Array(hitTarget1,hitTarget2,hitTarget3,hitTarget4,hitTarget5);
var dropArray:Array = new Array(drop1,drop2,drop3,drop4,drop5);
var positionsArray:Array = new Array();
for (var i:int = 0; i < dropArray.length; i++) {
dropArray[i].buttonMode = true;
dropArray[i].addEventListener(MouseEvent.MOUSE_DOWN, mdown);
dropArray[i].addEventListener(MouseEvent.MOUSE_UP, mUp);
positionsArray.push({xPos:dropArray[i].x, yPos:dropArray[i].y});
}
function mdown(e:MouseEvent):void {
e.currentTarget.startDrag();
setChildIndex(MovieClip(e.currentTarget), numChildren - 1);
}
function mUp(e:MouseEvent):void {
var dropIndex:int = dropArray.indexOf(e.currentTarget);
var target:MovieClip = e.currentTarget as MovieClip;
target.stopDrag();
if (target.hitTestObject(hitArray[dropIndex])) {
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
playSound(sosto);
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}
}
reset.addEventListener(MouseEvent.CLICK, backObjects);
function backObjects(e:MouseEvent):void{
for(var i:int = 0; i < dropArray.length; i++){
if(dropArray[i].x == hitArray[i].x && dropArray[i].y == hitArray[i].y){
dropArray[i].x = positionsArray[i].xPos;
dropArray[i].y = positionsArray[i].yPos;
}
}
}
function playSound(SoundName:Class):void{
var sound = new SoundName();
var channel:SoundChannel = sound.play();
}
playSound(sosto);
Let's create a function to tell us if every "hitTarget" and its corresponding "drop" are touching each other.
function allCorrect():Boolean {
//for each item in the hitArray, we repeat the action
//we assume that length of hitArray and dropArray are the same
for (var i=0;i<hitArray.length;i++) {
//if the corresponding target and drop do not hit each other, return false
if (!(hitArray[i].hitTestObject(dropArray[i])) {
return false
//if we return false, this function will continue no further
}
}
//We have cycled through all of the items in the arrays, and none of the
//hitTestObjects have been false, so we return true
return true
}
We want to test if everything is correct when we update the positions of our "drops". So, in your mUp function, add this line to the bottom
if (allCorrect()) {
//display "youz a cool cat, bro"
//remove all of your event listeners to improve performance
}
hope this answers your question!
Try adding this line:
stage.addEventListener(Event.ENTER_FRAME, loop);
Where "loop" is a function that contains the rest of your code, which looks something like...
function loop (e:Event):void
{
//Your Code
}
Good luck!

AS3: Issues with multiple save/load slots

I'm trying to take this very simple "game" and give it three save/load slots. Following a separate tutorial I can make it work with a single save slot but once I try adding more, it gives me the following error message.
1046:Type was not found or was not compile-time constant: save2.
1046:Type was not found or was not compile-time constant: save3.
I am new to actionscript 3 so I'm sure I'm being very newbish but I have tried to figure this out for quite some time now but just can't seem to. The whole thing is controlled by buttons already placed on the scene. I appreciate any help I can get.
The code:
import flash.net.SharedObject;
var saveDataObject:SharedObject;
var currentScore:Number = 0
init();
function init():void{
btnAdd.addEventListener(MouseEvent.CLICK, addScore);
btnSave1.addEventListener(MouseEvent.CLICK, save1);
btnSave1.addEventListener(MouseEvent.CLICK, saveData);
btnSave2.addEventListener(MouseEvent.CLICK, save2);
btnSave2.addEventListener(MouseEvent.CLICK, saveData);
btnSave3.addEventListener(MouseEvent.CLICK, save3);
btnSave3.addEventListener(MouseEvent.CLICK, saveData);
btnLoad1.addEventListener(MouseEvent.CLICK, save1);
btnLoad1.addEventListener(MouseEvent.CLICK, loadData);
btnLoad2.addEventListener(MouseEvent.CLICK, save2);
btnLoad2.addEventListener(MouseEvent.CLICK, loadData);
btnLoad3.addEventListener(MouseEvent.CLICK, save3);
btnLoad3.addEventListener(MouseEvent.CLICK, loadData);
}
function save1(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile1");
}
function save2(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile2");
}
function save3(e:MouseEvent):void{
saveDataObject = SharedObject.getLocal("savefile3");
}
function addScore(e:MouseEvent):void{
currentScore += 1;
updateScoreText();
}
function saveData(e:MouseEvent):void{
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function loadData(e:MouseEvent):void{
currentScore = saveDataObject.data.savedScore;
updateScoreText();
trace("Data Loaded!");
}
function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore);
trace("Score text updated");
}
I tried your code and it works like a charm...
Anyways, I've made a simpler version that doesn't use so many functions and Events.
Here is a pure AS3 version of it (just save it as Test.as3 and use as Document Class in Flash), but you can copy the content of the Test() method and paste in a action frame.
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.net.SharedObject;
import flash.text.TextField;
public class Test extends Sprite
{
public function Test()
{
/***** START: Faking buttons and field *****/
var txtScore:TextField = new TextField();
addChild(txtScore);
var btnAdd:Sprite = new Sprite();
var btnSave1:Sprite = new Sprite();
var btnSave2:Sprite = new Sprite();
var btnSave3:Sprite = new Sprite();
var btnLoad1:Sprite = new Sprite();
var btnLoad2:Sprite = new Sprite();
var btnLoad3:Sprite = new Sprite();
var items:Array = [btnAdd, null, btnSave1, btnSave2, btnSave3, null, btnLoad1, btnLoad2, btnLoad3];
for (var i:int = 0; i < items.length; ++i)
{
var item:Sprite = items[i];
if (item)
{
item.graphics.beginFill(Math.random() * 0xFFFFFF);
item.graphics.drawRect(0, 0, 100, 25);
item.graphics.endFill();
item.x = 25;
item.y = i * 30 + 25;
addChild(item);
}
}
/***** END: Faking buttons and field *****/
var saveDataObject:SharedObject;
var currentScore:Number = 0
btnAdd.addEventListener(MouseEvent.CLICK, addScore);
btnSave1.addEventListener(MouseEvent.CLICK, save);
btnSave2.addEventListener(MouseEvent.CLICK, save);
btnSave3.addEventListener(MouseEvent.CLICK, save);
btnLoad1.addEventListener(MouseEvent.CLICK, load);
btnLoad2.addEventListener(MouseEvent.CLICK, load);
btnLoad3.addEventListener(MouseEvent.CLICK, load);
function getLocal(target:Object):String
{
if (target == btnSave1 || target == btnLoad1)
{
return "savefile1";
}
else if (target == btnSave3 || target == btnLoad2)
{
return "savefile2";
}
else if (target == btnSave2 || target == btnLoad3)
{
return "savefile3";
}
}
function save(e:MouseEvent):void
{
var local:String = getLocal(e.target);
saveDataObject = SharedObject.getLocal(local);
saveDataObject.data.savedScore = currentScore;
trace("Data Saved!");
saveDataObject.flush();
trace(saveDataObject.size);
}
function load(e:MouseEvent):void
{
var local:String = getLocal(e.target);
saveDataObject = SharedObject.getLocal(local);
currentScore = saveDataObject.data.savedScore;
updateScoreText();
trace("Data Loaded!");
}
function addScore(e:MouseEvent):void
{
currentScore += 1;
updateScoreText();
}
function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore);
trace("Score text updated");
}
}
}
}

how to detect all tween complete in starling-framework

I'm develop a game with starling-framework.my problem is how to detect all tween is complete when I add a set of elements into juggler.
current my plan is
while(some_condition){ //allocate a set of tween
var tween=createTween(tweenCount++);
tween.onComplete=function(){
tweenCount--;
}
}
function checkComplete(){
if(tweenCount==0)
doStuff();
else
setTimeout(checkComplete,1000);
}
and there is any better solution ? thanks for your time!
update
write a simple class to solve this ,seems like better
public class TweenMonitor
{
public function TweenMonitor()
{
throw new Error('static class');
}
private static var refDict:Dictionary = new Dictionary();
public static function monit(tweens:Vector.<Tween>,onAllFinish:Function,id:String='$default$'):void
{
for (var i:int = 0; i < tweens.length; i++)
{
var tween:Tween = tweens[i];
if (tween == null)
continue;
if (refDict[id] == null) {
refDict[id] = 1;
}else
refDict[id]++;
tween.addEventListener(Event.REMOVE_FROM_JUGGLER,function (e:Event):void
{
refDict[id]--;
if (refDict[id] == 0)
onAllFinish && onAllFinish();
});
}
}
}
You simply need the onComplete property of Tween Class (Starling Framework)
Here is an Example :
function addTween() {
var tween:Tween = new Tween(object, 2.0, Transitions.EASE_IN_OUT);
tween.animate("x", object.x + 50);
tween.animate("rotation", deg2rad(45));
tween.fadeTo(0);
tween.onComplete = tween_complete;
Starling.juggler.add(tween);
}
function tween_complete() {
// Handle Tween Complete Action Here
}
EDIT
In case of multiple tweens, you probably could do better by attaching a timer class instead of settimeout:
while(some_condition){ //allocate a set of tween
var tween=createTween(tweenCount++);
tween.onComplete = function() { tweenCount--; }
}
var timer : Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER,update);
timer.start();
function update(e) {
if(tweenCount > 0) return;
timer.stop();
timer = null;
doStuff();
}
I would have done like this:
OnComplete = tweenDone;
...
function tweenDone() {
TweenCount--;
If(TweenCount == 0) doStuff();
}
Wrote this on a cell phone so I had to take a lot of shortcuts, if you need more info, leave a comment!

How to load an external image on a drag & drop object using AS3?

NEW MESSAGE - THE SOLUTION I ENDED UP APPLYING
This is what I used to load an external image into a movie clip and drag and drop.
The feedback part is pretty much the same from the old code.
var holdermc_Arr:Array = new Array(4);
for(var i:uint = 0; i < holdermc_Arr.length; i++)
{
holdermc_Arr[i] = this["panel" + (i+1) + "_mc"];
var myLoader:Loader = new Loader();
var fileRequest:URLRequest = new URLRequest("images/" + (i+1) + ".jpg");
myLoader.load(fileRequest);
holdermc_Arr[i].addChild(myLoader);
holdermc_Arr[i].addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
holdermc_Arr[i].addEventListener(MouseEvent.MOUSE_UP, dropIt);
holdermc_Arr[i].buttonMode = true;
}
var startX:Number;
var startY:Number;
var counter:Number = 0;
function pickUp(event:MouseEvent):void {
startX = event.currentTarget.x;
startY = event.currentTarget.y;
setChildIndex(MovieClip(event.currentTarget),numChildren-1);
event.currentTarget.startDrag();
reply_txt.text = "";
}
OLD MESSAGE BELLOW
This is my latest attempt with the current error I am getting.
I actually would like to work with the code of my previous attempt because to me is easier that way to add multiple draggable movie clips.
But whichever the code, what seems to be the fundamental problem is that I am not setting up the property correctly for the "Loader".
Let me know if a link to the example is needed.
The error is the following:
ReferenceError: Error #1069: Property dropTarget not found on
flash.display.Loader and there is no default value. at
cs5test_fla::MainTimeline/ReleaseToDrop()
The code is the following
var myLoader:Loader = new Loader();
panel1_mc.addChild(myLoader);
var url:URLRequest = new URLRequest("uploadedImages/photo_1.jpeg");
myLoader.load(url);
var startX:Number;
var startY:Number;
var counter:Number = 0;
panel1_mc.addEventListener(MouseEvent.MOUSE_DOWN, ClickToDrag);
function ClickToDrag(event:MouseEvent):void
{
panel1_mc.startDrag();
startX = event.target.x;
startY = event.target.y;
reply_txt.text = "";
event.target.parent.addChild(event.target);
}
stage.addEventListener(MouseEvent.MOUSE_UP, ReleaseToDrop);
function ReleaseToDrop(event:MouseEvent):void
{
panel1_mc.stopDrag();
var myTargetName:String = "target" + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
reply_txt.text = "Good Job!";
event.target.x = myTarget.x;
event.target.y = myTarget.y;
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, ClickToDrag);
event.target.removeEventListener(MouseEvent.MOUSE_UP, ReleaseToDrop);
event.target.buttonMode = false;
counter++;
} else {
reply_txt.text = "Try Again!";
event.target.x = startX;
event.target.y = startY;
}
if(counter == 1){
reply_txt.text = "Congrats, you're finished!";
}
}
OLDER MESSAGE BELLOW
I am still struggling.
I am new to all this so I am really tying the best I can to grasp it.
The ActionScript I am trying to work with is all the way at the bottom.
I'd really appreciate if someone tries to look at this code and tell me how can I load external images to each draggable movie clip with out getting the following error.
ReferenceError: Error #1069: Property startDrag not found on
flash.display.Loader and there is no default value. at
dragdropDilema_fla::MainTimeline/pickUp() ReferenceError: Error #1069:
Property stopDrag not found on flash.display.Loader and there is no
default value. at dragdropDilema_fla::MainTimeline/dropIt()
I tried to use a simple var loader but for what I can see on the error, I have to set up the startDrag property to work with the Loaded image and not with the draggable movie clips that are currently in place??
I thought I would have just been simple if I had use the following for each:
var myLoader:Loader = new Loader();
imageHolder.addChild(myLoader);
var url:URLRequest = new URLRequest("uploadedImages/photo_1.jpeg");
myLoader.load(url);
and then do something like:
square_mc.imageHolder.addChild(myLoader);
but when I do that I get the error anyway when I click on the image.
Here is the entire code: It is supposed to count when the object meet their target and gives a message all through out and at the end.
panel1_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
panel1_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
panel1_mc.buttonMode = true;
var startX:Number;
var startY:Number;
var counter:Number = 0;
function pickUp(event:MouseEvent):void {
startX = event.target.x;
startY = event.target.y;
event.target.startDrag(true);
reply_txt.text = "";
event.target.parent.addChild(event.target);
}
function dropIt(event:MouseEvent):void {
event.target.stopDrag();
var myTargetName:String = "target" + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
reply_txt.text = "Good Job!";
event.target.x = myTarget.x;
event.target.y = myTarget.y;
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickUp);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropIt);
event.target.buttonMode = false;
counter++;
} else {
reply_txt.text = "Try Again!";
event.target.x = startX;
event.target.y = startY;
}
if(counter == 1){
reply_txt.text = "Congrats, you're finished!";
}
}
Thanks.
import flash.display.DisplayObjectContainer;
import flash.display.Loader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.URLRequest;
var _dragMc:MovieClip = new MovieClip();
addChild(_dragMc);
loadImage("image.jpg")
function loadImage(path:String):void
{
var _loader:Loader = new Loader();
var _loaderToLoad:URLRequest = new URLRequest(path);
_loader.load(_loaderToLoad);
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded, false, 0, true);
}
function imageLoaded(evt:Event):void
{
addLoader(evt.currentTarget.loader, _dragMc);
}
function addLoader(loader:Loader, container:DisplayObjectContainer):void
{
container.addChild(loader);
addListeners();
}
function addListeners():void
{
_dragMc.addEventListener(MouseEvent.MOUSE_DOWN, setDrag, false, 0, true);
}
function setDrag(evt:MouseEvent):void
{
_dragMc.addEventListener(MouseEvent.MOUSE_MOVE, doDrag, false, 0, true);
_dragMc.removeEventListener(MouseEvent.MOUSE_DOWN, setDrag);
}
function doDrag(evt:MouseEvent):void
{
_dragMc.startDrag(false, null);
stage.addEventListener(MouseEvent.MOUSE_UP, endDrag, false, 0, true);
_dragMc.removeEventListener(MouseEvent.MOUSE_MOVE, doDrag);
}
function endDrag(evt:MouseEvent):void
{
_dragMc.stopDrag();
_dragMc.addEventListener(MouseEvent.MOUSE_DOWN, setDrag, false, 0, true);
stage.removeEventListener(MouseEvent.MOUSE_UP, endDrag);
}
This loads an image onto a MovieClip called _dragMc. The rest from there is up to you. I also added some quick code that will enable you to drag _dragMc around.