How to increment a score with sharedObject? - actionscript-3

I have been trying to make this small game in Flash using ActionScript 3.0. I'm using the SharedObject class and what I want to do is to see if it is possible to make the data type (so.data.x) null or 0 by default because by default it's not really anything. When I try to increment one of those data types, it gives me NaN or when I try to compare it I get a logic error in the "onClickSubmit" function. I can't assign anything at the beginning of the program because the whole point of it is for it to be saved after you close the game and reopen it. Thanks in advance.
import flash.net.SharedObject;
import flash.events.MouseEvent;
import flash.text.TextField;
var so:SharedObject = SharedObject.getLocal("app");
target.addEventListener(MouseEvent.CLICK, onClickTarget);
submit.addEventListener(MouseEvent.CLICK, onClickSubmit);
function onClickTarget(e:MouseEvent):void
{
so.data.currentHighscore++;
trace("Clicked! " + "(" + so.data.currentHighscore + ")");
}
function onClickSubmit(e:MouseEvent):void
{
if (so.data.currentScore > so.data.highscore)
{
trace("You beat the highscore!");
so.data.currentHighscore = 0;
}
else
trace("You haven't beat the highscore yet... keep trying");
}

You should do like that:
import flash.net.SharedObject;
import flash.events.MouseEvent;
import flash.text.TextField;
var so:SharedObject = SharedObject.getLocal("app");
target.addEventListener(MouseEvent.CLICK, onClickTarget);
submit.addEventListener(MouseEvent.CLICK, onClickSubmit);
var score:int = 0;
if (so.data.highscore == undefined) so.data.highscore = 0;
function onClickTarget(e:MouseEvent):void
{
score++;
trace("Clicked! (" + score + ")");
}
function onClickSubmit(e:MouseEvent):void
{
if (score > so.data.highscore)
{
trace("You beat the highscore!");
so.data.highscore = score;
so.flush();
}
else
trace("You haven't beat the highscore yet... keep trying");
}
Remark
You should use PHP and MySQL, because the .so file can be deleted without user's knowledge. See for more information: Adobe help about SharedOject > Local disk space considerations.

Your description is very contradictory. You want to use something that does not exist. You should create your shared object first and flush it, before you can use it. You can put some logic into your app to check if shared object exists and if not, create it with default values that you want. It is basically what you want - some object with default values. Also, you should not use your properties in SO directly at least because you are loosing strong typing. You should create some backed properties in your app and use them. Then, at some point, you can flush these properties into SO.

Related

1120 Access of undefined property Ibar & Ipc

stop();
import flash.display.*;
this.stop();
this.loaderInfo.addEventListener(ProgressEvent.PROGRESS, PL_LOADING);
function PL_LOADING(event: ProgressEvent): void {
var pcent: Number = event.bytesLoaded / event.bytesTotal * 100;
lbar.scaleX = pcent / 100;
lpc.text = int(pcent) + "%";
if (pcent == 100) {
this.gotoAndStop(2);
}
}
You'll do well to enable "Permit Debugging", however, the issue is on lines 14 & 15. It means you don't have an object in memory by those names. If you're working in the Flash IDE, and these are symbols in your library, add them to the stage, the and issue will be resolved.
Well, this code structure looks a bit disorganized. I'm not sure whether a lot of these changes will matter (since I currently don't have access to flash), but here is how I would typically write this:
stop();
import flash.display.*;
//no need for this.stop() if you've already stopped
this.loaderinfo.addEventListener(ProgressEvent.PROGRESS,PL_LOADING);
function PL_LOADING(e:ProgressEvent):void{
//possibly part of the problem is that the var keyword was on the wrong line
var pcent:Number = e.bytesLoaded/e.bytesTotal*100;
ibar.scaleX=pcent/100;
ipc.text=String(int(pcent)+"%");
//typically you want to make it clear that it's a string when dealing with text fields
if(pcent==100){
gotoAndStop(2);
}
}
Small changes like these as well as thoughtful organization could save your code. If you're still having problems with your code just notify me and I'll try to help you out.

Fast Fourier Transform With Microphone Input Data in AS3

Is it possible to get the source of adobes flash.media.SoundMixer class ?
If it is, where can i find / get it ?
I waht to "clone" the .computeSpectrum() function to transform a raw sound wave ( byteArray ) from Microphone input into a frequency spectrum.
I've found a couple of examples like this one -> http://pierrickpluchon.fr/blog/as3-how-to-plug-your-microphone-with-a-soundspectrum-in-flash-player-10-1/
All other methos i've found are pretty much the same.
The problem is that there is always a Sound() playing, what i DON'T want. ( I don't want any loopback )
But if i'm not playing a sound, i can't use the SoundMixer.computeSpectrum() function to transform my ByteArray that comes from the Microphone to a frequency spectrum by turning the FFTMode to true ( computeSpectrum(myByteArray,true) )
Also if you know any other method to get the Frequency Spectrum from the Raw Sound Wave, please let me know.
UPDATE
my code:
var bytes:ByteArray = new ByteArray();
var mic:Microphone = Microphone.getMicrophone();
mic.rate = 44;
// mic.gain = 100; // gain
mic.addEventListener(SampleDataEvent.SAMPLE_DATA, onSampleData);
function onSampleData( event:SampleDataEvent ):void {
graphics.clear();
graphics.lineStyle(1, 0xFF0000);
for( var i:uint = 0; i < 256; i++ ) {
var num:Number = event.data.readFloat() * 100 + 100; // -Math.abs( )
if( i == 0 ) {
graphics.moveTo( i, num );
} else {
graphics.lineTo( i, num );
}
}
}
"..Also if you know any other method to get the Frequency Spectrum from the Raw Sound Wave, please let me know."
Well Joe Beuckman beat me to it and gave you the link to Gerry Beauregard's FFT code. That's the best AS3 one I've seen so far since I found it two years ago. From the comments I see you were wondering how to implement... Well to see implementation code you need to see another page on his blog:
http://gerrybeauregard.wordpress.com/2010/08/06/real-time-spectrum-analysis/
To test that code yourself you first have to save the classes shown in the link here: http://gerrybeauregard.wordpress.com/2010/08/03/an-even-faster-as3-fft/
Save each package's code respectively as FFT2.as and FFTElement.as
Now in your document class put the code from: http://gerrybeauregard.wordpress.com/2010/08/06/real-time-spectrum-analysis/
However in that code you must also add some lines importing the other saved .as classes
import __AS3__.vec.Vector;
import flash.display.Sprite;
import flash.events.*;
import flash.media.Microphone;
import flash.text.*;
import flash.utils.*;
import FFT2;
import FFTElement;
Now it should run without errors and show the same thing as screenshot on his blog. The online demo used to work for me but not today so I say screenshot just so you know what to expect when it works fine.
Hope it helps. VC:One
FFT means the Fast Fourier Transform. That is exactly the algorithm that transforms the raw sound wave values into the frequency space. You should be able to find (or port) an implementation of the FFT in AS3, and that does what you ask.

Flash/AS3: Type was not found or was not a compile-time constant

it's been several years since I've touched AS3, but have a project requiring a bit of scripting.
I'm trying to have a Table of Contents menu slide down, then slide up, depending on a generic Open/Close button. The concept is the same as using .slideToggle() in jQuery.
I've created a MovieClip, given it an Instance Name and have Exported it for ActionScript in my Library, but for some reason, when I try and run a method to just shift it down 325px, I keep getting this error:
1046: Type was not found or was not a compile-time constanc: toc.
I realize that the library is missing a reference for something, but since the MC has an Instance Name and has been exported for AS, I'm a little puzzled as to what it could be. All of my scripts are in Frame 1, and I'm not using any external classes. Any help/pointers would be greatly appreciated!! I'm also having the same issue when I try to create the Email link, towards the bottom of my code.
Again, any help would be greatly appreciated!! Thanks!!
import flash.events.MouseEvent;
import flash.display.MovieClip;
import flash.display.SimpleButton;
// Initial load elements
gotoAndStop("Frame1");
UpdateFrame();
// Mouse events
btnNextSlide.addEventListener(MouseEvent.CLICK, NextSlide);
btnPrevSlide.addEventListener(MouseEvent.CLICK, PrevSlide);
btnTOC.addEventListener(MouseEvent.CLICK, ShowToC);
//btnDifferenceLink.addEventListener(MouseEvent.CLICK, Email);
// Various Methods
function NextSlide(event:MouseEvent):void
{
// find current slide, go to next slide
var currentFrame = this.currentFrame;
var nextFrame = currentFrame + 1;
if (int(nextFrame) == this.totalFrames)
{
// stop
gotoAndStop("Frame" + this.framesLoaded);
}
else
{
// go to next slide
gotoAndStop("Frame" + nextFrame);
}
// go to and stop at the next frame
UpdateFrame();
}
function PrevSlide(event:MouseEvent):void
{
// find current slide
var currentFrame = this.currentFrame;
var prevFrame = currentFrame - 1;
if (int(prevFrame) == 1)
{
// stop
gotoAndStop("Frame1");
}
else
{
// go to next slide
gotoAndStop("Frame" + prevFrame);
}
// go to and stop at the next frame
UpdateFrame();
}
function UpdateFrame():void
{
txtCurrentSlide.text = this.currentFrame.toString();
}
function Email():void
{
var email:URLRequest = new URLRequest("mailto:emailaddress");
navigateToURL(email, "_blank");
}
function ShowToC():void
{
// slide Table of Contents down
toc.y = 325;
}
function HideToC():void
{
// slide Table of Contents up
toc.y = -325;
}
I have just found the solution!
curtismorley.com/2007/06/20/flash-cs3-flex-2-as3-error-1046
In his first paragraph, he mentions objects on your stage and in your library cannot have the same name. In my case, I had an asset called "toc" in the library, and was referencing "toc" via Instance Name. By changing this, the problem has been solved. I've been searching for a day and a half on this stupid error..

as3 calling a function in another class [duplicate]

UPDATE: OK I am about ready to give up on Pacakages and classes. No answers coming. Not sure what to do. I tried to make the question easier and made a new post but I was down voted for it. as3 calling a function in another class
I am TOTALLY NEW to using PACKAGES and CLASSES. I am finally converting over from the timeline after having so many issues. Please be patient with my lack of knowledge. I need to know how to call a function in the child swf file I loaded from code in the maintime in the parent swf.
There are 2 swf files. Main.swf and pConent.swf
1. Main.swf has code in the timeline of the first frame.
2. pConent.swf is loading a PACKAGE CLASS as file.
QUESTIONS
I am trying to call a function in it from its parent Main.swf. How do I do this?
Here is sections of the code from both. Thanks
Main.swf CODE /// is an AIR for Andrid swf
function LoadContent()
{
TheContent.load(new URLRequest( "pContent.swf"));
TheContent.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadContentTWO);
function LoadContentTWO(e:Event)
{
Content = TheContent.content as MovieClip;
pContent = Content as Object;
addChild(TheContent);
var OSS:String = "device";
trace(pContent); //// comes out as: [object pContent]
pContent.GetOnlineStatus(OSS); ///// HOW DO I GET THIS TO CALL FUNCTION
}
}
A SECTION OF THE "CLASS" in pContent.swf I am trying to call
public function GetOnlineStatus(OS:String)
{
if(OS=="online")
trace("inside ONLINE" );
}
if(OS=="device")
{
trace("inside DEVICE" );
}
}
THE ERROR I AM GETTING
TypeError: Error #1006: GetOnlineStatus is not a function.
UPDATE: I decided to post the FULL PACKAGE ( my first) to see if I am doing it right.
package
{
import flash.display.MovieClip;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.display.*;
import flash.media.Sound;
import flash.system.*;
import flash.media.SoundChannel;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class pContent extends MovieClip
{
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
var ScreenY = flash.system.Capabilities.screenResolutionY;
var ScreenX = flash.system.Capabilities.screenResolutionX;
var swf:String;
var daSounds:String;
var images:String;
var videos:String;
var OnlineStatus:Boolean;
//++++++++++++++++++++++++
//++++++++++++++++++++++++
public function pContent()
{
BG.addEventListener(MouseEvent.CLICK, mouseHandlerdown);
}
//++++++++++++++++++++++++
//++++++++++++++++++++++++
//-------- * FUNCTIONS * --------
//-------------------------------
public function mouseHandlerdown(event:MouseEvent):void
{
alpha = .3; // testing
}
public function GetOnlineStatus(OS:String)
{
if(OS=="online")
{
OnlineStatus = true;
Security.allowDomain("*");
trace("inside THE PATH " + ThePath.text);
daSounds = "http://mycontactcorner.com/upload/files/";
swf = "http://mycontactcorner.com/upload/files/";
trace("inside THE DEVICE ONLINE" );
OnlineStatus = false;
swf = "";
daSounds = "content/sounds/";
//LoadMenu();
LoadStage();
LoadBeau();
}
if(OS=="device")
{
trace("inside THE DEVICE ONLINE" );
}
}
//------ * END FUNCTIONS * -----
//------------------------------
}// END FUNCTION pContent
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
}//// END PACKAGE
Don't be disappointed, but I won't have a "real" answer to your question, and I am really not going to work through all of your code to solve it, either. It is your own task to learn how to do this, and unless people here are very, very hungry for reputation, no one will do it for you - we will only help you to find the right way.
Your problem is not "packages and classes", so please do not give up on them. They will help you a great deal, once you've started to understand them. Your problem is, that you are not facing a single problem, but actually at least two (and quite substantial ones, I might add):
You need to go back to learn about the basics of object oriented programming in ActionScript. You won't have much luck getting answers to questions like this, otherwise. And believe me, I don't mean that in a patronizing way - it is simply a complicated matter, and it is hard to communicate complicated issues, both when you don't know the terms to express them, or when your counterpart doesn't understand them. Think of it like a high school math problem: You won't ever find a solution to your trigonometry question (or get a decent answer), unless you learn some basic algebra first.
You also have a problem related to loading, application domains, and the Flash Player security model - which are all far more complicated than what you should aim at when trying out OOP stuff. This can be a major obstacle, and unless you want to frustrate yourself, you should try to avoid it, until your program actually runs.
So this here is my advice: Always try to solve one problem at a time. Do not work yourself into such complex scenarios as the one you are in right now, but take step by step, until you've reached a level where you are confident with what you are doing.
Your first issue should be to understand what's going on with classes and objects. Everything else will come later. You should try to isolate your problem in the pContent.swf and get that to work first - or better yet, put everything you need for your program into a single file. Convert to using classes. Then, once you know how to work with those, start learning about more advanced OO, decoupling your code using interfaces, type casting and loading binaries at runtime.
//makes contact with classs but comes out as: [object pContent]
its because you said
pContent = Content as Object;
I am not sure why you are doing this extra step
Change it to this
Content = TheContent.content as MovieClip;
// pContent = Content as Object; //NO NEED OF THIS
addChild(Content); // just in case this gives error change it as addChild(Content as Object);
var OSS:String = "device";
trace(Content); //now see the difference
Content.GetOnlineStatus(OSS); // it calls now
Also, give the link where you posted that scary question :P if it has rest of the code
Sorry if this does not sound like an answer, but I'm going to write a couple of doubts that I have reading your code that can possibly lead to the solution:
Why are you casting it to MovieClip? If you cast it as MovieClip, the compiler it is going to tell you that the method "GetOnlineStatus" doesn't exist, because MovieClip class doesn't have it! I think you have to cast it as pContent
Why are you trying to casting TheContent.content? What is "content"? I had a look to your previous post and I cannot see anything called "content"?
If I ignore my second doubt (TheContent.content issue), I would change the code like this:
Content = TheContent.content as pContent; // your class it's called pContent
addChild(Content);
Content.GetOnlineStatus(OSS); // it calls now
Also, keep in mind that generally it's a good pratice to capitalize name of classes and not variables.
Let me know!
private function GetOnlineStatus
Try making this a public function instead. When it's private it can't be accessed outside the scope of the class that owns it.
I believe that in order to make this work, content property of the Loader. You have to create a reference to the loaded SWF as the class you are trying to call. This class has to be included in the main SWF's project. Then you can call the functions of that particular class in the child.
function LoadContent()
{
TheContent.load(new URLRequest( "pContent.swf"));
TheContent.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadContentTWO);
}
function LoadContentTWO(e:Event)
{
var pContent:GetOnlineStatus = GetOnlineStatus(e.target.content);
addChild(e.target.content); //Assuming that "TheContent was
// declared as var TheContent:Loader , you'd be adding the loader to the stage when I think you actually wanted // to add the content.
var OSS:String = "device";
trace(pContent); //// comes out as: [object pContent]
pContent.GetOnlineStatus(OSS); ///// HOW DO I GET THIS TO CALL FUNCTION
// This should work now. If not, try to loading a function that is not the class' main function. Because I think you might get an "unable to call static function error". I'm a begginner too though, so sorry if I'm wrong. Example: pContent.GetOnlineStatusFunction(OSS);
}
This answer assumes that the pContent.swf contains a class file that looks like this:
package {
public class GetOnlineStatus {
public function GetOnlineStatus (OSS:String) {
//Do your GetOnlineStatus Logic. This is the main function.
}
/*public function GetOnlineStatusFunction (OSS:String) {
//Example non-main function
} */
}
}
Source: http://www.scottgmorgan.com/accessing-document-class-of-externally-loaded-swf-with-as3/

Creating Classes and Properties in AS3

I'm new to AS3. Learning how to create classes. Is comp = new HouseObjects creating a new class? Is comp creating an instance of the HouseObjects? I realize that this is inside public class TreeHouse. I'm thinking that HouseObjects, how I set it up is not a class...not sure what the correct way to set up classes and properties.
Also I noticed, that when I tried to link another movieclip using the same linkage name HouseObjects--it asked to enter a unique class. I'm trying to create multiple instances from the same class called HouseObjects.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class TreeHouse extends MovieClip
{
private var comp:MovieClip;
var powerData:int; // stores user data (of selected data)
//var currentPower:int; // stores current power
public function TreeHouse()
{
comp = new HouseObjects; // linkage in library
comp.power = 2; // amount of power
comp.name = "comp";
comp.buttonMode = true;
comp.bstate = 0; // button state
//add event listeners -- listens to functions that are called
comp.addEventListener(MouseEvent.MOUSE_OVER, rolloverToggle);
comp.addEventListener(MouseEvent.MOUSE_OUT, rolloutToggle);
comp.addEventListener(MouseEvent.CLICK, toggleClick);
comp.addEventListener(MouseEvent.CLICK, toggleClick);
stage.addChild(comp); // add computer to stage -----------------------------------
trace("tracing...");
comp.x = 100;
comp.y = 100;
}
// function rollOver --------------------------------------------------------------
function rolloverToggle(e:MouseEvent) {
if (e.currentTarget.currentFrame == 1)
e.currentTarget.gotoAndStop(2);
if (e.currentTarget.currentFrame == 3)
e.currentTarget.gotoAndStop(4);
}
// function rollOut-- --------------------------------------------------------------
function rolloutToggle(e:MouseEvent) {
if (e.currentTarget.currentFrame == 2)
e.currentTarget.gotoAndStop(1);
if (e.currentTarget.currentFrame == 4)
e.currentTarget.gotoAndStop(3);
}
// function toggleClick-------------------------------------------------------------
function toggleClick(e:MouseEvent) {
// On MouseEvent gotoAndStop(Frame Number)
if (e.currentTarget.currentFrame == 2)
{
e.currentTarget.gotoAndStop(3);
e.currentTarget.bstate = 1;
}
if (e.currentTarget.currentFrame == 4)
{
e.currentTarget.gotoAndStop(1);
e.currentTarget.bstate = 0;
}
//var powerData:int = HouseObjects[e.currentTarget.power]; // set power value
// Find out which object selected-------------------------------------------------
//trace("movieClip Instance Name = " + e.currentTarget); // [object Comp]
//trace(houseArray[e.currentTarget.name]); // comp
trace("using currentTarget: " + e.currentTarget.name); // comp
//trace("powerData: " + powerData); // power of user data
//trace("houseArray: " + houseArray[0]); // the 0 index of house array
trace(e.currentTarget.power); // currentTarget's power************
}
} //end of class
} // end of package
I am not quite sure if I understood your question correctly. comp = new HouseObjects creates a new instance (object) of the type HouseObjects. (A little research on OOP basics would probably make life easier for you.)
Regarding the »Please enter a unique class name« error: You cannot assign the same class to two library symbols because the symbol is hooked up to the class internally so that if you create a new instance (var x = new HouseObjects; addChild(x);), the content from the linked symbol is also added to the display list. If there were multiple library symbols linked to the same class, how would the Flash compiler know which one to choose?
Your question is pretty broad and , as klickverbot suggests, it would be better if you took a little time to understand basic OOP concepts.
There are a lot of resources available to get you started with AS3, check this for instance
http://tv.adobe.com/watch/colin-moocks-lost-actionscript-weekend/course-1-introduction
Colin Moock's tutorial is very easy to follow and will give you most of the tools you need to get started.
If you are new to AS3, and OOP in particular, you should check out Moock's Essential Actionscript 3 which is beyond fantastic for a step by step education in OOP in AS3.
HouseObjects appears to be a class and you are creating a new instance of it for the variable comp
You've got a duplicate definition. It appears that you are trying to use Flash Pro to extend HouseObjects for the lightbulb. It doesn't work like this in Flash Pro. You are creating a MovieClip symbol and giving it a class definition. It has to extend MovieClip and you cannot change this in this case. You could likely extend HouseObjects in an AS3 file and make use of it in your application.
Personally think that if you want to really get your head around OOP with AS3 you should get the book and get out of Flash Pro. Use an IDE like Flash Builder, FDT, Flash Develop, or IntelliJ IDEA. It is a lot easier to understand when you get away from the dialogs and other complications of the Flash Pro IDE :>