AS2 code to AS3 - Percent calculator - actionscript-3

this.onenterframe = function () {
var _local2 = percent.text * of.text;
var _local1 = _local2 / number(100);
if (of.text === "") {
answer.text = "";
}
else if (of.text > "0") {
answer.text = _local1;
}
};
I used this code years back and now I want to how to get to work again in AS3.

AS3 uses events, so the way you would rewrite this code is:
In my example, I am adding the event lister to stage, but in your code, you may need to add it elsewhere depending on what you're doing.
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
function onEnterFrame($e:Event):void
{
var _local2:Number = Number(percent.text) * Number(of.text);
var _local1:Number = _local2 / 100;
if (of.text === "")
{
answer.text = "";
}
else if (Number(of.text) > 0)
{
answer.text = _local1;
}
}

Related

Implicit coercion of a value of type flash.events:KeyboardEvent to an unrelated type flash.events:MouseEvent

how can I call a function of flash events : MouseEvent in flash events keyboardEvent function
I am a biggner in as3 please help
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(event:KeyboardEvent){
if (event.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
**startFun(event);**
}
else if (keyMode == 1)
{
**checkfun(event);**
}
else if (keyMode == 2)
{
keyMode = 1;
**anotherPro(event);**
}
}
}
There is several ways, dispatch events, etc. I'll give you a simple example:
// or should be KEY_UP?
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedHandler, false, 0, true);
stage.addEventListener(MouseEvent.CLICK, exampleMouseClickHandler, false, 0, true);
function exampleMouseClickHandler(event:MouseEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
mouseClickLogic();
keyPressLogic();
}
function mouseClickLogic():void
{
//do something...
}
function keyPressedHandler(event:KeyboardEvent):void
{
//if necessary to pass any parameter, just need to change these mouseClickLogic() / keyPressLogic() methods
keyPressLogic();
mouseClickLogic();
}
function keyPressLogic():void
{
//to something...
}
You can use like that:
MouseEvent in flash events:
import flash.events.MouseEvent;
stage.addEventListener(MouseEvent.CLICK,clickStage);
stage.addEventListener(MouseEvent.MOUSE_UP,upStage);
stage.addEventListener(Event.MOUSE_LEAVE,leaveStage);
stage.addEventListener(MouseEvent.MOUSE_DOWN,mouseDownStage);
function clickStage(e:MouseEvent):void
{
trace("click Stage");
}
function upStage(e:MouseEvent):void
{
trace("up Stage");
}
function leaveStage(e:Event):void
{
trace("leave Stage");
}
function mouseDownStage(e:MouseEvent):void
{
trace("mouse Down Stage");
}
keyboardEvent function:
function reportKeyDown(event:KeyboardEvent):void
{
trace("Key Pressed: " + String.fromCharCode(event.charCode) + " (character code: " + event.charCode + ")");
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
I thank all those who tried to help me
this is my program without any error the error which I made before is in this code instead of Event
I typed MousEvent
function startFun(evt:Event):void
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.events.Event;
var elapsedTime:Number;
var NumOfProplem:Number;
var PropSolved:Number;
var completeSet:Boolean;
answerbox.restrict = "0-9";
ProplemBox.restrict = "0-9";
mult2.restrict = "?";
mult1.restrict = "?";
var keyMode:Number = 0;
stage.focus = ProplemBox;
bt1.visible = false;
bt2.visible = false;
//////////////////////////////
btnstart.addEventListener(MouseEvent.CLICK, startFun);
function startFun(evt:Event):void {
if (ProplemBox.text == "") {
stage.focus = ProplemBox;
return;
}
bt1.visible = true;
bt2.visible = true;
NumOfProplem = Number(ProplemBox.text);
PropSolved = 0;
completeSet = false;
elapsedTime = getTimer();
keyMode = 1;
anotherPro(evt);
}
///////////////////////////////
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
/////////////////
bt1.addEventListener(MouseEvent.CLICK,checkfun);
function checkfun(evt:Event):void
{
var x:Number = parseInt(mult1.text);
var y:Number = parseInt(mult2.text);
var z:Number = parseInt(answerbox.text);
if ((x*y )== z){
messagebox.text = "Right";
PropSolved++;
if (PropSolved >= NumOfProplem ){
keyMode = 3;
endGameReport();
}
else{
keyMode = 2;
}
}
else
{
messagebox.text = "Wrong";
stage.focus = answerbox;
answerbox.setSelection(0,3);
}
}
function endGameReport():void{
elapsedTime = (getTimer() - elapsedTime);
stage.focus = ProplemBox;
ProplemBox.setSelection(0,2);
bt1.visible = false;
bt2.visible = false;
messagebox.text = "You completed" + NumOfProplem + "Proplems in"
+ Math.floor(elapsedTime/1000) + "Second";
}
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressed);
function keyPressed(evt:KeyboardEvent){
if (evt.keyCode == Keyboard.ENTER)
{
if (keyMode == 0)
{
keyMode = 1;
startFun(evt);
}
else if (keyMode == 1)
{
checkfun(evt);
}
else if (keyMode == 2)
{
keyMode = 1;
anotherPro(evt);
}
}
}

AS3 Appending text at Caret

Working on a virtual keyboard using flash pro, and im somewhat stuck.
I have a way to control the carat so you can scroll through the text field but I'd like to be able to punch in letters exactly where the carat is using code.
Below is my keyboard controls
// keyboard controls
for (var i=0; i<lettersSmall.length; i++)
{
this["key_" + lettersSmall.charAt(i)].addEventListener(MouseEvent.MOUSE_UP,_keys);
letterButtonSmall["key_" + lettersSmall.charAt(i)] = lettersSmall.charAt(i);
letterButtonCaps["key_" + lettersSmall.charAt(i)] = lettersCaps.charAt(i);
}
function _keys(event:MouseEvent):void
{
curTextPos = textSelect.caretIndex;
strehrows3();
stage.focus = textSelect;
textSelect.setSelection(curTextPos,curTextPos);
if (electoff.currentFrame == 2)
{
ajWidth(event);
}
if (terminalinput.currentFrame == 2)
{
TrWidth(null);
}
if (control == "on" && menu1.visible == false )
{
if (! shift)
{
textSelect.appendText(letterButtonSmall[event.target.name]);
inputMaxWidth = textSelect.width;
}
else
{
textSelect.appendText(letterButtonCaps[event.target.name]);
shift = false;
inputMaxWidth = textSelect.width;
}
savedTxt = textSelect.text;
textSelect.setSelection(textSelect.length,textSelect.length);
if (textSelect.width <= 134.05)
{
//textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2;
}
if (textSelect.width >= 134.05)
{
//textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2-(textSelect.width-134.05);
}
}
textSelect.setSelection(textSelect.length,textSelect.length);
if (electoff.currentFrame == 2)
{
ajWidth(event);
}
if (terminalinput.currentFrame == 2)
{
TrWidth(null);
}
focuser();
strehrows3();
_fontSize();
textSelect.width = inputMaxWidth;
}
You could do it this way:
var inputStr:String = event.target.name; //This looks like it's value of your key pressed?
var caret:int = textSelect.textField.caretIndex;
var afterCaretText:String = textSelect.text.substr(caret);
var beforeCaretText:String = textSelect.text.substr(0,caret);
textSelect.text = beforeCaretText + inputStr + afterCaretText;
You could do this all in one line without creating the four variables, but I think it's easier to understand what's going on like this.

Flash CS5 AS3 Can not get Flashvars

I am new to fairly new to AS3 and I have found myself needing to extend a fla. that was written by a 3rd party.
The goal is to access flashvars but for the life of me can not get it to work...been at it for days learning..
the fla I am working with is code on timeline with 2 frames. the movieclip runs to frame 2 ans stops.
On frame 2 is where I require the use of the flashvar.
I have built a simple example that will populate a textbox on frame two that works fine.
frame 1
var my_var:String = new String();
my_var = root.loaderInfo.parameters.uploadId;
frame 2
my_txt.text = my_var;
stop();
However when I use the same approach on my 3rd party fla I get NULL output. I am not using any TLF text either (I think).
I don't understand why it works in one case but not the other. I am thinking it might have to do with conflict with the surrounding code but I don't know enough about AS to track it down. Any help on this would be greatly appreciated.
frame 1
import net.bizmodules.uvg.loading;
stop();
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.showDefaultContextMenu = false;
stage.quality = StageQuality.BEST;
function RandomValue()
{
var d = new Date();
return String(d.getDate()) + String(d.getHours()) + String(d.getMinutes()) + String(d.getSeconds());
}
var my_var:String;
my_var = root.loaderInfo.parameters.uploadId;
var userId;
var albums:Object;
var resource:Object;
var strUploadPage:String;
if (root.loaderInfo.parameters.uploadPage != undefined)
strUploadPage = root.loaderInfo.parameters.uploadPage;
else
strUploadPage = "http://localhost/dnn450/desktopmodules/ultramediagallery/flashuploadpage.aspx?PortalId=0&ModuleId=455";
if (strUploadPage.indexOf("?") > 0)
strUploadPage += "&";
else
strUploadPage += "?";
strUploadPage += "action=loadAlbums&seed=" + RandomValue();
trace(strUploadPage);
var myLoading:MovieClip = new loading();
myLoading.x = (stage.stageWidth - myLoading.width) / 2;
myLoading.y = (stage.stageHeight - myLoading.height) / 2;
addChild(myLoading);
var myRequest:URLRequest = new URLRequest(strUploadPage);
var myLoader:URLLoader = new URLLoader(myRequest);
myLoader.addEventListener(Event.COMPLETE, xmlLoaded);
function xmlLoaded(evtObj:Event)
{
myLoader.removeEventListener(Event.COMPLETE, xmlLoaded);
try
{
var xDoc:XMLDocument = new XMLDocument();
xDoc.ignoreWhite = true;
var xml:XML = XML(myLoader.data);
xDoc.parseXML(xml.toXMLString());
userId=xDoc.firstChild.attributes.userId;
if (userId < 0)
{
removeChild(myLoading);
txtError.text = "Please ensure you are logged in";
return;
}
if(xDoc.firstChild.childNodes.length > 0)
{
albums = xDoc.firstChild.childNodes[0].childNodes;
resource = xDoc.firstChild.childNodes[1].attributes;
}
else
{
removeChild(myLoading);
txtError.text = xDoc.firstChild.attributes.error;
return;
}
play();
}
catch(e:Error)
{
removeChild(myLoading);
txtError.text = e + "\n\nPlease check your Event Viewer to find out detailed error message and contact service#bizmodules.net";
}
}
frame 2
import net.bizmodules.upg.Alert;
stop();
removeChild(myLoading);
initialize();
function initialize()
{
Alert.init(stage);
upload.addVar("userId",userId);
lstAlbums.dropdown.rowHeight = 24;
loadAlbums(0, albums);
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
var lastAlbum = my_so.data.lastAlbum * 1;
var foundLastAlbum = false;
if (lastAlbum > 0)
{
for (var i:int = 0; i< lstAlbums.length; i++)
{
if (lstAlbums.getItemAt(i).data == lastAlbum)
{
trace("find previous album");
foundLastAlbum = true;
lstAlbums.selectedIndex = i;
break;
}
}
}
if (!foundLastAlbum)
{
lstAlbums.selectedIndex = lstAlbums.length - 1;
}
albums_change(null);
lstAlbums.addEventListener("change", albums_change);
lstAlbums.setStyle("backgroundColor", 0x504C4B);
lstAlbums.dropdown.setStyle("backgroundColor", 0x504C4B);
lstAlbums.setStyle("themeColor", 0x1F90AE);
lstAlbums.setStyle("color", 0xC4C0BF);
lstAlbums.setStyle("textSelectedColor", 0xC4C0BF);
lstAlbums.setStyle("textRollOverColor", 0xC4C0BF);
lstAlbums.setStyle("alternatingRowColors", [0x504C4B, 0x504C4B]);
lstAlbums.setStyle("borderStyle", 'none');
}
my_txt.text = "hello" + " " + my_var;
function loadAlbums(level:int, xml:Object)
{
var prefix = " ".substring(0, level * 4);;
for (var i:int = 0;i<xml.length;i++)
{
var itemValue = xml[i].attributes.itemid;
if (xml[i].childNodes.length > 0)
itemValue *= -1;
lstAlbums.addItem({data: itemValue, label: prefix + xml[i].attributes.name});
if (xml[i].childNodes.length > 0)
{
loadAlbums(level + 1, xml[i].childNodes);
}
}
}
function albums_change(e)
{
var albumId = lstAlbums.getItemAt(lstAlbums.selectedIndex).data;
upload.set_albumId(albumId);
if (albumId > 0)
{
var my_so:SharedObject = SharedObject.getLocal("UPGUpload");
my_so.data.lastAlbum = albumId;
}
else
{
Alert.show("The album you choosed is invalid", null, 0xEAEAEA, 0x000000);
}
}
private var flashVarObj:Object = new Object;
flashVarObj=LoaderInfo(this.loaderInfo).parameters;
var my_var:String = new String();
my_var = flashVarObj.uploadIdd;

AS3 Showing image after load is finish

So i'm loading picture from xml, and adding them into a movieclip called cv which has a holder called cHolder. Right now the problem is that while the preloader shows it is loading, the cv(s) appeared already. Is there anyway to show all the cv only after the images have finish loading?
Thanks.
for each (var projectName:XML in projectAttributes)
{
//trace(projectName);
var projectDP:XMLList = projectInput.project.(#name == projectName).displayP;
//trace(projectDP);
var cv:MovieClip = new cView();
catNo += 1;
cv.name = "cv" + catNo;
cv.buttonMode = true;
if(catNo % 5 == 0)
{
catY += 137;
catX = -170;
cv.x = catX;
cv.y = catY;
}
else
{
cv.x = catX;
cv.y = catY;
catX += 112;
}
var imageLoader = new Loader();
imageLoader.load(new URLRequest(projectDP));
TweenLite.to(cv.cHolder, 1, {colorTransform:{tint:0x000000, tintAmount:0.8}});
cv.cHolder.addChild(imageLoader);
cv.ct.text = projectName;
projName.push(projectName);
this.addChild(cv);
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageProg);
function imageProg(e:ProgressEvent):void
{
loader.visible = true;
var imageLoaded:Number = e.bytesLoaded/e.bytesTotal*100;
loader.scaleX = imageLoaded/100;
}
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoad);
function imageLoad(e:Event):void
{
loader.visible = false;
}
First, don't put a function inside another function, this won't help for anything and is a bad habit :)
Declare two private variables:
var nImages:uint;
var loadedImages:uint;
Before the loop:
nImages = projectAttributes.length();
loadedImages = 0;
cv.visible = false;
and in the Event.COMPLETE listener:
function imageLoad(e:Event):void
{
loader.visible = false;
loadedImages++;
if (loadedImages == nImages)
{
cv.visible = true;
}
}
var count:int = 0;
var totalClips:int = 0;
cv.visible = false;
for each (var projectName:XML in projectAttributes)
{
++totalClips;
//trace(projectName);
var projectDP:XMLList = projectInput.project.(#name == projectName).displayP;
//trace(projectDP);
var cv:MovieClip = new cView();
catNo += 1;
cv.name = "cv" + catNo;
cv.buttonMode = true;
if(catNo % 5 == 0)
{
catY += 137;
catX = -170;
cv.x = catX;
cv.y = catY;
}
else
{
cv.x = catX;
cv.y = catY;
catX += 112;
}
var imageLoader = new Loader();
imageLoader.load(new URLRequest(projectDP));
TweenLite.to(cv.cHolder, 1, {colorTransform:{tint:0x000000, tintAmount:0.8}});
cv.cHolder.addChild(imageLoader);
cv.ct.text = projectName;
projName.push(projectName);
this.addChild(cv);
imageLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, imageProg);
function imageProg(e:ProgressEvent):void
{
loader.visible = true;
var imageLoaded:Number = e.bytesLoaded/e.bytesTotal*100;
loader.scaleX = imageLoaded/100;
}
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoad);
function imageLoad(e:Event):void
{
++count;
if(count == totalClips){
cv.visible = true;
}
loader.visible = false;
}
}
So you might want to adapt things a little, in case I'm counting in the wrong spots etc for your implementation but as you can see the solution is simple, you count the total number of clips being processed for loading from the XML, then as the images are loaded and call the OnComplete callback, you increment another count until you've seen that you've loaded all processed images, and set the container to visible.

Flash AS3: position loaded images from loop based on image height

I'm trying to dynamically stack images that are being pulled in via an xml file. Below is what I'm doing, and it almost works. The problem is that it only seems to fire off the event complete function on the very last one, instead of going for all of them. Is there a way to make it run the even.complete function for each image?
function aboutfileLoaded(event:Event):void {
aboutXML = new XML(aboutTextLoader.data);
for(var l:int = 0; l < aboutXML.aboutimages.image.length(); l++)
{
imageLoader = new Loader();
imageSource = aboutXML.aboutimages.image[l];
if (imageSource != "") {
this.imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, aboutimageLoaded);
this.imageLoader.load(new URLRequest(imageSource));
//aboutBox.aboutContent.addChild(imageLoader);
//imageLoader.y = imageYpos;
//imageYpos = imageYpos + 50;
}
}
}
function aboutimageLoaded(event:Event):void {
aboutBox.aboutContent.addChild(imageLoader);
this.imageLoader.y = imageYpos;
imageYpos = imageYpos + this.imageLoader.height;
}
I use a simple Image class I wrote for loading all images.
public function loadImages(xml:XML):void {
for each(var img:XML in xml.images) {
var i:Image = new Image(img.src, img.width, img.height);
i.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, positionImage);
}
}
/**/
private function positionImage(e:Event):void {
var i:Image = e.target;
gallery.addChild(i);
// Do the positioning.
}
In your code above, you could always just change your aboutimageLoaded function:
// In aboutfileLoaded() change all "this.imageLoader" to just "imageLoader"
function aboutimageLoader(event:Event):void {
aboutBox.aboutContent.addChild(event.target);
event.target.y = imageYpos;
}
each Loader can only deal with one job at a time, so either you want to stack the jobs to load one after another:
//Global vars
loadIndex:int = 0;
imageLoader = new Loader();
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, aboutimageLoaded);
loadImage();
private function loadimage(){
if(aboutXML.aboutimages.image[loadIndex] != null){
imageSource = aboutXML.aboutimages.image[loadIndex];
if (imageSource != "") {
imageLoader.load(new URLRequest(imageSource));
}
}
}
function aboutimageLoaded(event:Event):void {
var holder = (ev.content as Bitmap).clone();
aboutBox.aboutContent.addChild(holder);
holder .y = imageYpos;
imageYpos = imageYpos + holder.height;
loadIndex ++;
loadimage();
}
or make multiple instances of Loaders, one for each:
for(var l:int = 0; l < aboutXML.aboutimages.image.length(); l++)
{
var imageLoaderTemp = new Loader();
imageSource = aboutXML.aboutimages.image[l];
if (imageSource != "") {
imageLoaderTemp.contentLoaderInfo.addEventListener(Event.COMPLETE, aboutimageLoaded);
imageLoaderTemp.load(new URLRequest(imageSource));
}
}
}
function aboutimageLoaded(event:Event):void {
aboutBox.aboutContent.addChild(event.target);
event.target.y = imageYpos;
imageYpos = imageYpos + event.target.height;
}