Unable to get actionscript to load xml file then loop - actionscript-3

I have spent many hours searching the internet and have come up empty handed. My problem is that i am trying to create a flash file that loops every 10 seconds and changes 2 dynamic text fields each time it loops.
var xmlData:XML = new XML();
var theURL_ur:URLRequest = new URLRequest("shout.xml");
var loader_ul:URLLoader = new URLLoader(theURL_ur);
function fileLoaded(e:Event):void
{
xmlData = XML(loader_ul.data);
show_txt.text = xmlData.SERVERTITLE;
song_txt.text = xmlData.SONGTITLE;
}
The dynamic fields are set correctly and are all in the same scene but as i said, it does not load the right fields and when it does work it caches which i do not want it to do.

Maybe set a "counter" variable that increments and append your URL with shout.xml?c=[counter]

Related

How can I save variables to a file? Actionscript 3.0

I'm not really very good with Actionscript 3.0 and I was wondering how I can save variables to a file (A .txt), as well as set variables using a button.
What I am trying to do is get a name, date and another name. I have 3 input boxes and I am unsure how to get the text input to be saved into a text file. I need it to create a new file every time it saves so the details of each user is saved (This is my task, it's an induction thingy, nothing bad).
Also, I am unsure how to set variables with the click of a button. Say the button instance name is "next_button" and I want to get it to set a variable that I can call later on. If I click it, the variable will be set to "Contractor", that's what I need.
The start of the "quiz" if you would call it is asking for the name, date and the company they're from. I need those details to be saved to a file.
I also need help with getting a variable to be set with the click of a button. I have 4 buttons on the screen and I want to get the button to change a variable to "Permanent Employee" or "Contractor".
Any help is appreciated.
To save data using the FileReference Class:
var data:String = "JDLKJFSDKJFHS";
var file:FileReference = new FileReference();
file.save(data,"filepath.txt");
To set a variable on mouse click:
var saveVar:String = "";
var buttons:Array = [button1,button2,button3];
var buttonStrings:Array = ["Contractor","Employee","Slave"];
button.addEventListener(MouseEvent.CLICK,onClick);
function onClick(e:MouseEvent):void{
var index:int = buttons.indexOf(e.target);
if (index > 0) saveVar = buttonStrings[index];
}

How to display an image from URLRequest twice (downloading it only once)?

I am just wondering, if it is possible to load an image via URLRequest once, and display that image twice? Or do i have to load the image 2 times?
Edit:
Also want to ask if it is possible to duplicate the bitmaps when they are loaded in a loop(array).
For example:
var duplicate:Array = new Array(loadedArray.push(e.target.content));
When i am trying the code :
loadedArray.push(e.target.content);
var duplicate:Array = new Array(loadedArray.push(e.target.content));
It doesnt give me any errors, but from before it adds the bitmap with no problem, but now, it doesnt add anything.
And when i tried
var duplicate:Array = new Array(loadedArray as Bitmap);
addChild(duplicate[0]);
I have an error Error #2007: Parameter child must be non-null.
Duplicating Bitmap or BitmapData is easy. There are a lot of options, these are few of them:
// in your case, but can be any Bitmap
var original:Bitmap = Bitmap(loader.content);
// we actually need the bitmapData; separate for easy reading
var originalBitmapData:BitmapData = original.bitmapData;
var duplicate:Bitmap = new Bitmap(originalBitmapData);
// this one returns brand new copy of the BitmapData (sometimes needed)
var duplicate:Bitmap = new Bitmap(originalBitmapData.clone());
copyPixels() on BitmapData is also super fast and can be used for duplication, depending if there is already Bitmap(Data) instantiated.

Using an array to load in multiple images in Actionscript

I have a class assignment where I have to create a photo gallery and one of the stipulations is that the images need to be loaded from an external source. The reference code from our assignment was:
var myRequest:URLRequest = new URLRequest("bw1.jpg");
myLoader.load(myRequest);
addChild(myLoader);
My specific needs requires me to have up to 2 copies of the images on the screen at once, one as a thumbnail and a second as a fullsized image. I want it so that when a user clicks a thumbnail a new instance of the picture is created scaled to fullsize with 0 alpha and the current selected picture decreases in alpha as the new pic increases in alpha. Once the old pic is no longer visible it is removed from the stage.
I am having trouble figuring out how to create a copy of the image in actionscript and also my for loop seems to not be executing properly as it only ever goes through one iteration even when I have no error messages.
Here is a link to my code via pastebin: http://pastebin.com/iadgKgsk but to save you from having to switch back and forth between I will also past it here
import flash.display.Bitmap;
//creates a loader for each picture to be loaded, I know I could have an empty array
that I add to but created a full array to test.
var loaders:Array = [new Loader(),new Loader(), new Loader(), new Loader(), new
Loader(), new Loader(), new Loader(), new Loader(), new Loader(), new Loader()];
//stores the url request for each image to be loaded
var Requests:Array =[new URLRequest("pic1.jpg"),new URLRequest("pic2.jpg"),new
URLRequest("pic3.jpg"),
new URLRequest("pic4.jpg"),new URLRequest("pic5.jpg"),new URLRequest("pic6.jpg"), new
URLRequest("pic7.jpg"),
new URLRequest("pic8.jpg"), new URLRequest("pic9.jpg"),new URLRequest("pic10.jpg")];
//creates 2 empty arrays one to store the thumbnail sized pics the other fullsized.
Ideally I want one Array holding the bitmap data and the other holding the thumbnail
instances since I only need 2
// fullsized images at a time I can just create a new one and erase the old one in a
single function.
var pics:Array = new Array();
var pics2:Array = new Array();
//defines an empty bitMap variable as a placeholder for which to copy from redefined in
every iteration of the loop
var test:Bitmap;
//loops through every loader
for (var i in loaders);
{
// loads the loader and url request and creates a picture
loaders[i].load(Requests[i]);
//waits for the pic to load
loaders[i].contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
//after loader is loaded create pic from the data
function loadComplete(evt:Event):void
{
var i = "Test";
trace(i);
test= evt.target.content as Bitmap;
pics2[i] = test;
pics[i] =new Bitmap(test.bitmapData);
pics2[i] =new Bitmap(test.bitmapData);
//creates an image on the stage at runtime to help debug
var pic1 = new Bitmap(test.bitmapData);
addChild(pics[i])
pic1.scaleX = 0.138427734375;
pic1.scaleY = 0.1384114583333333;
pic1.x = 204;
pic1.y = 20.6;
pic1.alpha = .25;
var pic2:Bitmap = new Bitmap(test.bitmapData);
pic2.x =100;
pic2.y =100;
pic2.scaleX =.33;
pic2.scaleY=.33;
addChild(pic2);
loaders[i].contentLoaderInfo.removeEventListener(Event.COMPLETE,
loadComplete)
}
}
Your for loop is setup in a way that it would attempt to iterate for each property of the loaders instance which isn't what you want. You may want to investigate other AS3 bulk loader options too there are already some scripts out there to help take care of this.
Your loop should look like
for(var i=0; i<loaders.length; i++)
{
var curLoader = loaders[i].load(Requests[i]);
You can also see an example I put together that loads a bunch of images flipbook style animation (images generated with blender):
http://www.shaunhusain.com/DrawTextRandomly/
http://www.shaunhusain.com/DrawTextRandomly/srcview/
look in the utils.imageLoader package, I made two classes there that deal with loading the images, since they were output from Blender with sequential file names I just used some loops to load the images based on a numeric counter, in your case you could switch it to use a source array of images to load.
In the BatchImageLoader class I have a variable for how many loaders to allow it to make, I wanted to see the difference in performance in terms of memory vs load time (will depend on runtime environment too but I wanted to get a general idea, ended with leaving it at using 90 loaders at most).

Saving textfield input

I'll explain a little before asking my question ... I've created numerous games which load and unload off a main menu.
The player enters their name on the main menu before playing any games and when the player completes a game I want to save their time (taken to complete the game) and unload this time back into the main menu.
Is there any way of saving the times using AS3 to a word document or something like this? I can't send the times to my website with php because the games will be used within a competition and it all needs to work with the internet.
Any ideas guys?
Edit:
var dataloader:URLLoader = new URLLoader();
var dataarray:Array = new Array(); // do this where you intialise other vars
function preparesave()
{
dataloader.load(new URLRequest("savedata.txt"));
}
dataloader.addEventListener(Event.COMPLETE,savedata);
function savedata (event:Event)
{
dataarray = event.target.data.split(/\n/);
dataarray.push(MyTimer);
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference = new FileReference();
for (var i = 0; i < dataarray.length;i++)
{
bytes.writeMultiByte(dataarray[i] + "\n", "iso-8859-1");
bytes.writeMultiByte('English Game Time: ',"iso-8859-1");
bytes.writeMultiByte(HourText.text.toString(),"iso-8859-1");
bytes.writeMultiByte(':',"iso-8859-1");
bytes.writeMultiByte(MinuteText.text.toString(),"iso-8859-1");
bytes.writeMultiByte(':',"iso-8859-1");
bytes.writeMultiByte(SecondText.text.toString(),"iso-8859-1");
}
fileRef.save(bytes,"savedata.txt")
}
You could use a cookie(sharedObject) for this purpuse. See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html
var data:SharedObject = SharedObject.getLocal("userdata");
data.startTime = new Date().time;
If you need the startTime again you could just retrieve it by the cookie and variable name.
For small amounts of data, you're best-off just going with automaticoo's solution by using SharedObjects.. they take minimal time to set up and are an efficient way of storing small amounts of data.
However, if it's not for you, you could always load/save to a text file. You can do this using ByteArrays and FileReferences.
Since you brought up saving to a word file, I would suggest saving to a text file would be the best way of achieving your goal (although other than your word doc. suggestion, i'm not sure.. your aim is sort of unclear)
Here is a seriously quick demonstration of saving to a text file.. If you need help loading it too, let me know.
function savedata() {
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference = new FileReference();
bytes.writeMultiByte(playername + "\n", "iso-8859-1");
bytes.writeMultiByte(playerscore.toString(),"iso-8859-1");
fileRef.save(bytes,"savedata.txt");
}
This is pretty simply.. By using writeMultiByte, we can write as much data as needed before saving our text file! This is especially useful if you have arrays of data you need to save.
Anyway, the "iso-8859-1" is simply a reference to the character set / file-format being used.. I'm not sure if you can simply write utf-16 etc. instead.. I've always just used it as it is written above.
The result in the text file here will be the following:
Peter
9547 (but up one line)
To load, you can just split data by line, resulting in an array full of strings and ints/numbers (however your scores may work). Again, let me know if you need help doing that.
I'm not sure if this is the most efficient method of achieving what you're after since your goal isn't entirely clear to me, but it has been a very useful way for myself in storing large amounts of data, which I'm guessing you are wanting to do if you are compounding all the scores of players.
edit:
Okay, to the questions you posed below:
To save more than one user's score is simple. Simply have a single array which loads the data from the text file (if the text file exists), then adds the new score to the end of the array, then saves back to the text file.
Here is an example:
var dataloader:URLLoader = new URLLoader();
var dataarray:Array = new Array(); // do this where you intialise other vars
function preparesave() {
dataloader.load(new URLRequest("savedata.txt"));
}
dataloader.addEventListener(Event.COMPLETE,savedata);
function savedata (event:Event) {
dataarray = event.target.data.split(/\n/);
dataarray.push(playername);
dataarray.push(playerscore);
var bytes:ByteArray = new ByteArray();
var fileRef:FileReference = new FileReference();
for (var i = 0; i < dataarray.length;i++) {
bytes.writeMultiByte(dataarray[i] + "\n", "iso-8859-1");
}
fileRef.save(bytes,"savedata.txt")
}
What this does is take any existing save data, pushes it to an array (where one line on your save file is one array data entry), adds your appropriate data, and pushes it back out to the save file.
(2) To load this in whilst in the main menu, simply place this code in the frame of the main menu..
dataloader.load(new URLRequest("savedata.txt"));
dataloader.addEventListener(Event.COMPLETE,loaddata);
function loaddata (event:Event) {
dataarray = event.target.data.split(/\n/);
}
This will load all your existing data into an array. What you do from then on is up to you.

flash as3 and external text config file

My goal was to have an external text file config for a client. I didnt want to go through a crazy xml thing, I just wanted it to be simple to change.
I started with a urlLoader, and was able to dynamically generate an object no problem. This is the function which parses and sets the properties of the object.
function onLoaded(e:Event):void//initializes the config
{
var myString = String(e.target.data);
//trace(e.target.data);
//trace(myString);
var propsArray:Array = myString.split("\n");
for (var i = 0; i < propsArray.length; i++){
var thisLine:Array = propsArray[i].split("=");
var thisPropName:String = thisLine[0];
thisPropName = thisPropName.replace(rex,'');
var thisPropValue:String = thisLine[1];
thisPropValue = thisPropValue.replace(rex,'');
trace("thePropName is: " + thisPropName);
trace("thePropValue is: " + thisPropValue);
config[thisPropName] = thisPropValue;
}
}
The text file would just look something like:
gateway = "http://thePathto/theFile.php
toast = sonofabitch
timer = 5000
xSpeed = 5.0
That way, I could just put a little bit of as3 code in, type what things I wanted configured, then all I would have to do was type config.timer and
var myTimer:Timer = new Timer(Number(config.timer));
I think the problem is load order and scope. The config.timer is not created yet, so the timer is unable to access the value of the config.timer.
I'd look at using XML in future projects of this nature, however to answer your question:
I think the problem is load order and scope. The config.timer is not created yet, so the timer is unable to access the value of the config.timer.
Correct, you will need to initialize your Timer within the onLoaded() method, as the data will be received asynchronously and is not available until this happens.
ok not long ago i had created a download manager that uses this exact concept.
The link below will take you straight to the website where you can download the full swf including my source files. also this website is a good place for resources
http://ffiles.com/flash/web_applications_and_data/dynamic_download_manager_3529.html
Below is my loader:
addEventListener(Event.ENTER_FRAME, update);
var myLoader:URLLoader = new URLLoader();
myLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
myLoader.load(new URLRequest("settings.txt"));
myLoader.addEventListener(Event.COMPLETE, onDataLoad);
function onDataLoad(evt:Event)
{
box1.text = evt.target.data.Id_1;
box2.text = evt.target.data.Id_2;
box3.text = evt.target.data.Id_3;
box4.text = evt.target.data.Id_4;
box5.text = evt.target.data.Id_5;
}
Add some dynamic text boxes to stage and name them "box1, box2 ect..."
Now creat your text file:
Id_1=this is what ever you want
&Id_2=this is what ever you want
&Id_3=this is what ever you want
&Id_4=this is what ever you want
&Id_5=this is what ever you want
Hope this helps.