How can I save variables to a file? Actionscript 3.0 - actionscript-3

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];
}

Related

AS3, variables outside event handler function?

I have searched arond, but cant seem to find a proper answer to this. Lets say we have a super basic program which adds two numbers from 2 input text fields togehter and prints them out. Why cant i accses variables outside the event handler function? And what do i have to do in order to achieve this? The code is on a frame.
Why does this example not work? :
btn.addEventListener(MouseEvent.CLICK, cal);
var fnum:Number = Number(txt1.text);
var snum:Number = Number(txt2.text);
function cal(evt:MouseEvent){
txtOutput.text = String(fnum + snum);
}
And this example work?:
btn.addEventListener(MouseEvent.CLICK, cal);
function cal(evt:MouseEvent){
var fnum:Number = Number(txt1.text);
var snum:Number = Number(txt2.text);
txtOutput.text = String(fnum + snum);
}
I hate to be this guy, but I can't get it to replicate whats happening for you..
The only assumption that I can make is that the txt1.text & txt2.text aren't set yet when the button is clicked in example 1. Feel free to zip your project and dropbox it to me if you want me to investigate further :)

How add UNDO to my text field in AS3?

I have a simple text editor with cut, paste and undo buttons. I have this for cut and paste but i don't how to create undo button?
var clipboardFmt:TextFormat = new TextFormat();
var initialPoint:Number = new Number();
var finalpoint:Number = new Number();
var clipBoard:String = new String();
cut_button.addEventListener(MouseEvent.CLICK,cutText);
paste_button.addEventListener(MouseEvent.CLICK, pastefromClipboard);
function cutText(event:MouseEvent):void
{
clipBoard = txt.text.substring(txt.selectionBeginIndex,txt.selectionEndIndex);
System.setClipboard(clipBoard);
txt.replaceText(txt.selectionBeginIndex,txt.selectionEndIndex,"");
}
function pastefromClipboard(e:Event):void
{
txt.replaceText(txt.selectionBeginIndex,txt.selectionEndIndex,clipBoard);
finalpoint = initialPoint + clipBoard.length;
txt.setSelection(initialPoint,finalpoint);
txt.setTextFormat(clipboardFmt, initialPoint,finalpoint);
}
txt.addEventListener(Event.CHANGE,count);
function count(e:Event):void
{
wn.text = countWords(txt.text);
function countWords(input:String):int
{
return input.match(/[^\s]+/g).length;
}
}
You need to store a copy of text-field text in a variable. Each time text-field's value is being changed but before the change is applied (the event is called TextEvent.TEXT_INPUT) save a copy of text-field value into this variable. When undo button is pressed set text-field value to a value stored in this variable.
This is the simplest solution which will allow you to undo only one step back. You can use an array instead of single variable in order to store several states of text-field which will allow you to undo several steps back.
create an array based undo system. Don't use the clipboard it will not work.

Unable to get actionscript to load xml file then loop

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]

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.