Actionscript, best practice for opening multiple files - actionscript

I need to open 3 files which may or may not exist. I am using FileStream with an event listener on completion of the load.
The code currently works like this
function 1 - Check/load file 1.
On answer - go to function 2.
function 2 - check/load file 2.
On answer - go to function 3.
function 3 - check/load file 3.
On answer - send completion event.
So I have 3 functions to load 3 files.
Does a better way exist. I wish to avoid a third party library.

A better way would be to use just one function to load all files ? Something like
private var _filesArray:Array = ["file1.ext", "file2.ext", "file3.ext"];
private var _loadIndex:int = 0;
private function loadNextFile():void
{
var _fileToLoad:String = _filesArray[_loadIndex];
// load your file here
}
private function onFileLoaded():void
{
checkIfWeAreDone();
}
private function onFileLoadError():void
{
checkIfWeAreDone();
}
private function checkIfWeAreDone():void
{
_loadIndex++;
if (_loadIndex == _filesArray.length)
{
// we are done, do something
}
else
{
loadNextFile();
}
}

Related

How do functions with multiple parameters of the same name work?

I've been looking through the code for a Flash game (link). However, I'm having trouble understanding how some of these functions work, especially because some of them have function definitions that I would think to fail to get past the compiler.
The following is some code from TodCommon.as that appears to conflict with itself (or at the very least uses bad naming conventions).
private static var gFlashingColor:Color = new Color();
final public static function ClampFloat(ClampInt:Number, ClampInt:Number, ClampInt:Number) : Number
{
if(ClampInt <= ClampInt)
{
return ClampInt;
}
if(ClampInt >= ClampInt)
{
return ClampInt;
}
return ClampInt;
}
final public static function ClampInt(gFlashingColor:int, gFlashingColor:int, gFlashingColor:int) : int
{
if(gFlashingColor <= gFlashingColor)
{
return gFlashingColor;
}
if(gFlashingColor >= gFlashingColor)
{
return gFlashingColor;
}
return gFlashingColor;
}
Also in the code is the weirdest syntax for a for-each loop that I've ever seen (this example also features a package name as a parameter name)
public function CountPlantByType(com.popcap.flash.framework.resources.fonts:int) : int
{
var _loc_3:CPlant = null;
var _loc_2:int = 0;
var _loc_4:int = 0;
var _loc_5:* = this.mPlants;
while(<to complete>)
{
_loc_3 = __nextvalue;
if(_loc_3.mSeedType != com.popcap.flash.framework.resources.fonts)
{
break;
}
_loc_2++;
}
return _loc_2;
}
Those are just a few examples of things that I think look super weird and am having trouble understanding. But these functions all work and are used extensively throughout the code. Can someone explain how the ClampFloat and ClampInt functions work, or why it's legal to use a package name as a parameter? Thanks
Resolved. Turns out the program I used to extract these files from the SWF also corrupted them in the process. Using JPEXS Free Flash Decompiler instead of ActionScriptExtractor fixed the code syntax.

Is this loginRequired(f)() the way to handle login required functions in dart?

I am new to Dart programming. I am trying to figure out what is the proper way (what everyone will do) to handle/guard those functions which are login required. The following is my first trial:
$ vim login_sample.dart:
var isLoggedIn;
class LoginRequiredException implements Exception {
String cause;
LoginRequiredException(this.cause);
}
Function loginRequired(Function f) {
if (!isLoggedIn) {
throw new LoginRequiredException("Login is reuiqred.");
}
return f;
}
void secretPrint() {
print("This is a secret");
}
void main(List<String> args) {
if (args.length != 1) return null;
isLoggedIn = (args[0] == '1') ? true : false;
try {
loginRequired(secretPrint)();
} on LoginRequiredException {
print("Login is required!");
}
}
then, run it with $ dart login_sample.dart 1 and $ dart login_sample.dart 2.
I am wondering if this is the recommended way to guard login required functions or not.
Thank you very much for your help.
Edited:
My question is more about general programming skills in Dart than how to use a plugin. In python, I just need to add #login_required decorator in the front of the function to protect it. I am wondering if this decorator function way is recommended in dart or not.
PS: All firebase/google/twitter/facebook etc... are blocked in my country.
I like the functional approach. I'd only avoid using globals, you can wrap it in a Context so you can mock then for tests and use Futures as Monads: https://dartpad.dartlang.org/ac24a5659b893e8614f3c29a8006a6cc
Passing the function is not buying much value. In a typical larger Dart project using a framework there will be some way to guard at a higher level than a function - such as an entire page or component/widget.
If you do want to guard at a per-function level you first need to decide with it should be the function or the call site that decides what needs to be guarded. In your example it is the call site making the decision. After that decision you can implement a throwIfNotAuthenticated and add a call at either the definition or call site.
void throwIfNotAuthenticated() {
if (!userIsAuthenticated) {
throw new LoginRequiredException();
}
}
// Function decides authentication is required:
void secretPrint() {
throwIfNotAuthenticated();
print('This is a secret');
}
// Call site decides authentication is required:
void main() {
// do stuff...
throwIfNotAuthenticated();
anotherSecreteMethod();
}

gather total score of quiz questions with new .as class (2 errors currently)

I currently created a new actionScript class, called Quiz.as
// package
// {
// public class Quiz
// {
public var knowledgePoints:int = 10;
public var allQuestions:Array = new Array;
public var questionCorrect:Boolean = false;
public function getTotalScore():int
{
// var totalScore:int = 0;
var totalScore = 0;
for (var i = 0; i < allQuestions.length; i++)
{
totalScore += allQuestions[i].getCalculatedScore();
if (currentModule.allQuestions[i].parent.questionCorrect)
{
knowledgePoints++;
}
else
{
knowledgePoints--;
}
}
debugLog("Total score: " + totalScore);
debugLog(knowledgePoints);
return totalScore;
}
// }
//}
This solution derived from my original question at: keeping track of a series of simple multiple choice web form answers
But now with the above code I am getting errors in flash console. My latest attempt to fix these errors are with the commented out regions above.
Error 1. Attribute used outside of class.
So I comment out first couple lines, but error continues to point to whatever line is exposed first.
Error 2. 'Int' could not be loaded.
Thanks for any advice,
Your issue is likely the result of using the above code on the timeline in AnimateCC/FlashPro.
Class files (and their corresponding attributes like public/private) need to be in their own actionscript (.as) file.
To create a class file in AnimateCC, go to file -> new and choose ActionScript 3.0 Class. Give it the class name of Quiz (so it matches what you've declared in your code)
Replace the default code with the class file code from your question (you'll need to restore those commented out lines too)
Save the file in the same directory as your .fla
To use your new class file in the timeline, you'd do something like this:
var quiz:Quiz = new Quiz(); //make an instance of your custom class
quiz.allQuestions.push(whateverAQuestionIs); //add a question to your array
trace(quiz.getTotalScore()); //trace out the total score
If you want to use that code in the timeline and forgo using a class file, you'll just need to remove the 4 public keywords (in addition to the lines you've already commented out)

Whats the best way to completely disable every play at runtime?

I want to disable everyplay, built in unity, when running iphone4/3G/3GS
but I'm not sure of the easiest place to just globally disable it. Any suggestions?
if (iPhone.generation == iPhoneGeneration.iPhone4 || iPhone.generation == iPhoneGeneration.iPhone3G || iPhone.generation == iPhoneGeneration.iPhone3GS )
You can easily disable single core devices (3GS/4/iPad1) by calling Everyplay.SharedInstance.SetDisableSingleCoreDevices(true) in the first scene of your game. After that you don't have to worry if you are calling StartRecording on a single core device since the calls are ignored by Everyplay. 3G (and Unity editor) does not support the recording in the first place.
In case you need to support recording on iPad 1 one approach is to create an Everyplay singleton wrapper which simply does not call recording functions on devices which you have have defined to be not supported.
Simple wrapper example (untested but gives you the idea):
using UnityEngine;
public static class MyEveryplayWrapper {
private static iPhoneGeneration[] unsupportedDevices = {
iPhoneGeneration.iPad1Gen,
iPhoneGeneration.iPhone,
iPhoneGeneration.iPhone3G,
iPhoneGeneration.iPhone3GS,
iPhoneGeneration.iPodTouch1Gen,
iPhoneGeneration.iPodTouch2Gen,
iPhoneGeneration.iPodTouch3Gen
};
private static bool CheckIfRecordingSupported() {
bool recordingSupported = !Application.isEditor;
foreach(iPhoneGeneration device in unsupportedDevices) {
if(device == iPhone.generation) {
recordingSupported = false;
break;
}
}
Debug.Log ("Everyplay recording support: " + recordingSupported);
return recordingSupported;
}
public static bool IsRecordingSupported = CheckIfRecordingSupported();
public static void StartRecording() {
if(IsRecordingSupported) {
Everyplay.SharedInstance.StartRecording();
}
}
public static void StopRecording() {
if(IsRecordingSupported) {
Everyplay.SharedInstance.StopRecording();
}
}
}
To use it you just call MyEveryplayWrapper.MethodName instead of Everyplay.SharedInstance.MethodName. When rendering your UI you can take the IsRecordingSupported into account to show/hide Everplay related buttons etc.

Return values when using Delegate with sendAndLoad in a AS2 class file

I have a Flash animation with AS2 code that calls sendAndLoad in a separate class file, and following guides online I've used a Delegate to handle the onLoad part, like this:
ActionScript Code in class:
function myFunction():String{
...
var send_lv:LoadVars = new LoadVars();
var saveresult_lv:LoadVars = new LoadVars();
send_lv.dataString = rc4_hash; send_lv.sendAndLoad("<my url>",saveresult_lv,"POST");
saveresult_lv.onLoad = Delegate.create(this, onLoad);
}
function onLoad (success:Boolean) {
if (success) {
}else{
}
}
I've got two issues:
Because I call myFunction() from my .fla file, how do I send the result of onLoad() back as the return value of myFunction()?
How do I refer to variables that were created inside myFunction from within onLoad?
In my fla file, I have code like this:
myVar:String=myFunction();
If onLoad takes any time then I think that myFunction() is returning nothing, and myVar ends up undefined. How do I get the fla to wait for the onLoad in the class file to finish and then populate myVar with the result?
Many thanks in advance for any tips
Your class could be restructured to answer your questions.
Separate the constructor, load function and result operation. When load is ready, the class can dispatch an event. Your FLA can listen to this event.
// Class code should something like this: (my AS2 is a little rusty)
class Sender {
private var classSavedData:String;
// these three vars are needed to use EventDispatcher.
public var addEventListener:Function;
public var removeEventListener:Function;
public var dispatchEvent:Function;
// Make your class ready to send events
public function Sender() {
EventDispatcher.initialize(this);
}
public function loadData(){
classSavedData = "Something the FLA can pick up after loading";
var send_lv:LoadVars = new LoadVars();
var saveresult_lv:LoadVars = new LoadVars();
send_lv.dataString = rc4_hash;
end_lv.sendAndLoad("<my url>",saveresult_lv,"POST");
saveresult_lv.onLoad = Delegate.create(this, onLoad);
}
private function onLoad():Void {
dispatchEvent({target:this, type:"eventFired", loadAnswer: saveresult_lv , extraData:classSavedData});
}
}
... and code in FLA can look like this:
var myClassInstance:Sender = new Sender()
myClassInstance.addEventListener ("eventFired", Delegate.create (this, onDataLoaded))
myClassInstance.loadData()
function onDataLoaded(evt:Object){
trace ("loaded loadvars "+evt.loadAnswer)
}

Resources