Unable to input numbers in TextField - actionscript-3

I'm trying to create a calculator to calculate the power energy and its cost.
The following is my code and although it does not have error, i can't input numbers. I cant input alphabets because i restricted it but i cant input numbers too.
import flash.events.MouseEvent;
ok_btn.addEventListener(MouseEvent.CLICK, multiplyClick);
back_btn.addEventListener(MouseEvent.CLICK, backClick);
var multiSym:Boolean = false;
var backSym:Boolean = false;
usage.restrict = "0-9";
power.restrict = "0-9";
power.border = true;
usage.border = true;
var input1:String;
var input2:String;
var multiResult:Number;
function multiplyClick(event:MouseEvent):void
{
multiSym = true;
backSym = false;
input1 = usage.text;
input2 = power.text;
if(multiSym == true){
multiResult = parseInt(input1)* parseInt(input2);
multiResult.toString();
total_power.text = String(multiResult);
} else {
total_power.text = "Please Choose an option";
}
}
function backClick(event:MouseEvent):void
{
multiSym = false;
backSym = true;
}
stop();
can someone help me?
Thank you

Related

Actionscript 3 drag and drop multiple objects to target with well done

The drag and drop works, however, I have no idea how to create an if statement that goes to the next scene when all movieclips have been placed on the target.
I've tried placing the instance names in an if statement with the hittestobject however, no luck.
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.display.MovieClip;
/* Touch and Drag Event
Allows the object to be moved by holding and dragging the object.
*/
var objectoriginalX:Number;
var objectoriginalY:Number;
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
var lemons:Array = [lemon1_mc, lemon2_mc, lemon3_mc, lemon4_mc, lemon5_mc];
for each(var lemonMC:MovieClip in lemons)
{
lemonMC.buttonMode = true;
lemonMC.addEventListener(TouchEvent.TOUCH_BEGIN, pickobject);
lemonMC.addEventListener(TouchEvent.TOUCH_END, dropobject);
lemonMC.startX = lemonMC.x;
lemonMC.startY = lemonMC.y;
}
var fl_DragBounds:Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
function pickobject(event:TouchEvent):void
{
event.target.startTouchDrag(event.touchPointID, false, fl_DragBounds);
event.target.parent.addChild(event.target);
objectoriginalX = event.target.x;
objectoriginalY = event.target.y;
}
function dropobject(event:TouchEvent):void
{
if(event.target.hitTestObject(target_mc)){
event.target.buttonMode = false;
event.target.x = target_mc.x;
event.target.y = target_mc.y;
event.target.visible = false;
} else {
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
var melons:Array = [melon1_mc, melon2_mc, melon3_mc, melon4_mc, melon5_mc, melon6_mc, melon7_mc];
for each(var melonMC:MovieClip in melons)
{
melonMC.buttonMode = true;
melonMC.addEventListener(TouchEvent.TOUCH_BEGIN, pickobject2);
melonMC.addEventListener(TouchEvent.TOUCH_END, dropobject2);
melonMC.startX = melonMC.x;
melonMC.startY = melonMC.y;
}
var fl_DragBounds2:Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
function pickobject2(event:TouchEvent):void
{
event.target.startTouchDrag(event.touchPointID, false, fl_DragBounds2);
event.target.parent.addChild(event.target);
objectoriginalX = event.target.x;
objectoriginalY = event.target.y;
}
function dropobject2(event:TouchEvent):void
{
if(event.target.hitTestObject(target_null)){
event.target.buttonMode = false;
event.target.x = target_mc.x;
event.target.y = target_mc.y;
event.target.visible = false;
} else {
event.target.x = event.target.startX;
event.target.y = event.target.startY;
event.target.buttonMode = true;
}
}
How about adding a counter that is equal to number of objects to drag, then every time you drop object (and detect if it was on target) you decrements the counter and at the end of the function you check if it's 0?
An easy way to do this would be to remove your lemons/melons from their arrays when they pass the hit test. Then check if each array is empty and continue to the next scene should that be the case.
You can actually reduce redundant code and use the same function (dropobject) for both lemons and melons.
function dropobject(event:TouchEvent):void {
//Figure out which array this belongs to (is it a lemon or a melon)
var array:Array; //the array the dropped item belongs to
var hitMC:MovieClip; //the hit object for the lemon or melon
if(lemons.indexOf(event.currentTarget) > -1){ //if the lemon array contains the currentTarget
array = lemons;
hitMC = target_mc;
}else{
array = melons;
hitMC = target_null;
}
if(event.currentTarget.hitTestObject(hitMC)){
event.currentTarget.buttonMode = false;
event.currentTarget.x = hitMC.x;
event.currentTarget.y = hitMC.y;
event.currentTarget.visible = false;
//remove the item from it's array
array.removeAt(array.indexOf(event.currentTarget));
//check if there are any items left
if(lemons.length < 1 && melons.length < 1){
//both arrays are empty, so move on
play(); //or however you want to move on
}
}
}
Getting more advanced, a better way to do this would be to make a base class for your lemons, melons and anything else you want to drag in the future. Then you can add the dragging functionality into that base class and add properties for the hit target and an event for when it's hit it's target. This would give you one code base that can be easily applied to any library object.

Adobe air application quits when i try to print after a function called "show bill"?

I am trying to create an air application using flash profession cc. I have functions called show bill and print bill in it. When i print directly with out showing the bill adobe air application works correctly. But when i try to use the show bill function and then try to print the bill it show the print dialog box and when i give a print command an"Adobe Air Application Stop working window shows up" . Here is the code of show bill function
public function ShowBill(e: MouseEvent): void {
total();
Merge();
bswap();
billing.x = 450;
billing.y = 100;
billing.height = 300 ;
billing.width = 500 ;
addChild(billing);
billing.close_btn1.addEventListener(MouseEvent.CLICK, rmvBilling);
billing.close_btn1.visible = true;
if(billing._item.item1.text != "")
{
billing._item.visible = true;
billing._item.close_btn1.visible = true;
}
if(item2.item1.text != "")
{
item2.close_btn1.visible = true;
}
if(item3.item1.text != "")
{
item3.close_btn1.visible = true;
}
if(item4.item1.text != "")
{
item4.close_btn1.visible = true;
}
if(item5.item1.text != "")
{
item5.close_btn1.visible = true;
}
if(item6.item1.text != "")
{
item6.close_btn1.visible = true;
}
if(item7.item1.text != "")
{
item7.close_btn1.visible = true;
}
if(item8.item1.text != "")
{
item8.close_btn1.visible = true;
}
if(item9.item1.text != "")
{
item9.close_btn1.visible = true;
}
if(item10.item1.text != "")
{
item10.close_btn1.visible = true;
}
total();
}
Here is the code for print bill
public function printContent(e: MouseEvent) {
update1();
billing.close_btn1.visible = false;
billing._item.close_btn1.visible = false;
item2.close_btn1.visible = false;
item3.close_btn1.visible = false;
item4.close_btn1.visible = false;
item5.close_btn1.visible = false;
item6.close_btn1.visible = false;
item7.close_btn1.visible = false;
item8.close_btn1.visible = false;
item9.close_btn1.visible = false;
item10.close_btn1.visible = false;
var printJob: PrintJob = new PrintJob();
if (printJob.start()) {
if (billing.width < printJob.pageWidth) {
billing.width = printJob.pageWidth;
billing.scaleY = billing.scaleX;
}
printJob.addPage(billing);
printJob.send();
clear();
}
}
public function update1():void{
var phpVars:URLVariables = new URLVariables();
var phpFileRequest:URLRequest = new URLRequest("http://localhost/icyspicy/update.php");
phpFileRequest.method = URLRequestMethod.POST;
phpFileRequest.data = phpVars;
var phpLoader:URLLoader = new URLLoader();
phpLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
phpVars.systemCall="update";
phpVars.table = String(tabNbill1.getDubTblNo.text);
phpVars.date = String(billing.the_date.text);
phpVars.items = String(billing._item.item1.text+","+item2.item1.text+","+item3.item1.text+","+item4.item1.text+","+item5.item1.text+","+item6.item1.text+","+item7.item1.text+","+item8.item1.text+","+item9.item1.text+","+item10.item1.text );
phpVars.quantity = String(billing._item.q2.text+","+item2.q2.text+","+item3.q2.text+","+item4.q2.text+","+item5.q2.text+","+item6.q2.text+","+item7.q2.text+","+item8.q2.text+","+item9.q2.text+","+item10.q2.text);
phpVars.total =String( billing.total.text);
phpLoader.load(phpFileRequest);
postData(mypath, getResponse);
}
Every function is working correctly but the conflict between printbill and show bill i could not solve ..Please guys need suggestion and help..Thank You
Sometimes spooling display objects with text and shapes can crash the application. While I can't comment on the why, I can share what I've done in the past to work around this problem.
Printing the page as a bitmap can sometimes fix this crashing problem. In your case that would like this:
var printOptions:PrintJobOptions = new PrintJobOptions();
printOptions.printAsBitmap = true;
printJob.addPage(billing,null,printOptions);
OR for a shorter inline way:
printJob.addPage(billing, null, new PrintJobOptions(true));
Do note, that sometimes doing this makes text not as crisp looking, as FlashPlayer is basically drawing the object to pixel data before sending it to the spooler.

save store on Android device with AS3

I'm trying to do a "save" and "restore" function for my game on Android (Adobe AIR).
So far, It seems to work for saving the game, but for I've got an error for the loading.
Here's what I did,
public function save(e){
//Save data in local memory
if(useShared){
shared = SharedObject.getLocal("myApp");
shared.data[saveNum] = jsonSave;
shared.flush();
}
private function restore(e){
if (useShared){
// Get data from local memory
shared = SharedObject.getLocal("myApp");
if(shared.data[saveNum]){
trace("Restoring: " + shared.data[saveNum]);
allSaveData = new Object;
allSaveData = JSON.stringify(shared.data[saveNum]);
}
}
Between I put all the information needed (player's current location...etc).
Did I make a mistake in my functions ?
Thank you for your help,
EDIT :
If I click on "save" everything seems to work, but if then I can't load my game. In debug mode I've got this error :
ReferenceError: Error #1069: Property datetime not found on String and there is no default value.
at com.laserdragonuniversity.alpaca::SaveRestore/populateSaves()[C:\Users\Stéphan\Desktop\18 aout\La Brousse en folie tactile\com\laserdragonuniversity\alpaca\SaveRestore.as:76]
at com.laserdragonuniversity.alpaca::SaveRestore/showSaver()[C:\Users\Stéphan\Desktop\18 aout\La Brousse en folie tactile\com\laserdragonuniversity\alpaca\SaveRestore.as:149]
at com.laserdragonuniversity.alpaca::Toolbar/showSaver()[C:\Users\Stéphan\Desktop\18 aout\La Brousse en folie tactile\com\laserdragonuniversity\alpaca\Toolbar.as:129]
Here's all my code for the save/restore function.
package com.laserdragonuniversity.alpaca {
import flash.events.*;
import com.adobe.serialization.json.*;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.net.SharedObject;
import flash.net.*;
import flash.display.Loader;
import flash.utils.getDefinitionByName;
import flash.text.TextField;
import flash.text.TextFormat;
public class SaveRestore extends MovieClip {
private var inv:Inventory;
private var puzzle:Puzzle;
private var player:Player;
private var back:Background;
private var options:Options;
private var stageRef:Stage;
private var shared:SharedObject;
private var useExternalFile:Boolean = false; //Set this to false if you don't want to deal with server-side scripts
private var useShared:Boolean = true; // Set this to false if you don't want to use Flash player's local memory
private var exLoader:URLLoader;
private var exReq:URLRequest;
private var saveURL:String;
private var saveID:String;
private var userID:String;
private var checkDialog:MovieClip;
private var slotsTaken:Array = new Array(false, false, false);
private var currentEvent;
private var confirm:MovieClip;
private var allSaveData:Object;
public function SaveRestore(stageRef:Stage, saveURL:String, saveID:String) {
this.stageRef = stageRef;
this.saveURL = saveURL;
this.saveID = saveID;
switchSave.gotoAndStop("on");
switchRestore.gotoAndStop("off");
// Un-comment this if you want save data to be cleared each time the SWF is opened
// Probably only necessary for testing purposes
//shared = SharedObject.getLocal(saveID);
//shared.clear();
populateSaves();
restore1.visible = false;
restore2.visible = false;
restore3.visible = false;
checkDialog = new saveOverwrite;
addChild(checkDialog);
checkDialog.visible = false;
addEventListener(Event.ADDED_TO_STAGE, setUpListeners);
}
public function populateSaves(){
if(useExternalFile){
// Here's where you can grab data from external .js files if you choose. This will require the use of server-side scripts
} else if(useShared){
shared = SharedObject.getLocal("myApp");
var saveNum:String;
var shotNum:String;
for (var i = 1; i < 4; i++){
saveNum = "save" + i;
if (shared.data[saveNum]){
slotsTaken[i-1] = true;
var thisSave = JSON.stringify(shared.data[saveNum]);
this[saveNum].savedetail.text = thisSave.datetime;
this["restore"+i].savedetail.text = thisSave.datetime;
// Use a MovieClip of the background as a screenshot
var bg:Object = fakeScreenshot(thisSave.playerLoc.room);
this["save"+i].addChild(bg.bg);
this["save"+i].addChild(bg.bgmask);
var bg2:Object = fakeScreenshot(thisSave.playerLoc.room);
this["restore"+i].addChild(bg2.bg);
this["restore"+i].addChild(bg2.bgmask);
}
}
}
}
public function setUpListeners(e){
switchSave.addEventListener(MouseEvent.CLICK, gotoSave, false, 0, true);
switchSave.buttonMode = true;
switchRestore.addEventListener(MouseEvent.CLICK, gotoRestore, false, 0, true);
switchRestore.buttonMode = true;
save1.btn.addEventListener(MouseEvent.CLICK, overwriteCheck, false, 0, true);
save2.btn.addEventListener(MouseEvent.CLICK, overwriteCheck, false, 0, true);
save3.btn.addEventListener(MouseEvent.CLICK, overwriteCheck, false, 0, true);
restore1.btn.addEventListener(MouseEvent.CLICK, restore, false, 0, true);
restore2.btn.addEventListener(MouseEvent.CLICK, restore, false, 0, true);
restore3.btn.addEventListener(MouseEvent.CLICK, restore, false, 0, true);
checkDialog.canceller.addEventListener(MouseEvent.CLICK, cancelled, false, 0, true);
checkDialog.saver.addEventListener(MouseEvent.CLICK, overwrite, false, 0, true);
closer.addEventListener(MouseEvent.CLICK, closeSaver, false, 0, true);
addEventListener("closeThis", closeSaver);
}
public function gotoSave(e){
gotoAndStop("save");
switchSave.gotoAndStop("on");
switchRestore.gotoAndStop("off");
restore1.visible = false;
restore2.visible = false;
restore3.visible = false;
save1.visible = true;
save2.visible = true;
save3.visible = true;
}
public function gotoRestore(e){
gotoAndStop("restore");
switchSave.gotoAndStop("off");
switchRestore.gotoAndStop("on");
restore1.visible = true;
restore2.visible = true;
restore3.visible = true;
save1.visible = false;
save2.visible = false;
save3.visible = false;
}
public function showSaver(){
if(checkDialog.visible){
checkDialog.visible = false;
}
populateSaves();
visible = true;
Engine.playerControl = false;
gotoSave(null);
}
public function overwriteCheck(e){
currentEvent = e;
var parentBtn = e.target.parent.name;
var slotNum = parentBtn.substr(parentBtn.length-1, 1);
if (slotsTaken[slotNum-1]){
trace("Save taken, confirming overwrite");
checkDialog.visible = true;
} else {
save(e);
}
}
public function cancelled(e){
showSaver();
}
public function overwrite(e){
save(currentEvent);
}
public function save(e){
puzzle = Engine.puzzle;
inv = Engine.inv;
player = Engine.player;
back = Engine.back;
options = Engine.options;
var saveNum:String = e.target.parent.name;
//Get the status of all the puzzles
allSaveData = new Object;
allSaveData.puzzleStatus = new Object;
allSaveData.puzzleStatus = puzzle.returnPuzzles();
//Get the inventory
allSaveData.allInv = new Array();
var allItems = inv.returnItems("all");
for (var i in allItems){
if(allItems[i].displayName){
//trace ("Saving " + allItems[i]);
allSaveData.allInv.push(allItems[i].displayName);
}
}
allSaveData.currentInv = new Array();
var currentItems = inv.returnItems(null);
for (i in currentItems){
allSaveData.currentInv.push([currentItems[i].displayName, currentItems[i].lookTag]);
}
//Get the player's current location
allSaveData.playerLoc = new Object;
allSaveData.playerLoc.x = player.x;
allSaveData.playerLoc.y = player.y;
allSaveData.playerLoc.scaleX = player.scaleX;
allSaveData.playerLoc.room = back.currentBack.name;
//Get the settings
allSaveData.optset = options.saveOptions();
// Get the date and time
var thisDate = new Date;
var dateString = thisDate.toLocaleString();
allSaveData.datetime = dateString;
var jsonSave = JSON.stringify(allSaveData);
trace("Saving: " + jsonSave);
//Save data in local memory
if(useShared){
shared = SharedObject.getLocal("myApp");
shared.data[saveNum] = jsonSave;
shared.flush();
}
if(useExternalFile){
// Here's where you can post the data to a server-side script and save it as an external .js file
// The trick would be to figure out how to distinguish one user from another
// Either by creating login functionality, or just identifying by IP or something like that
}
//Update save info
e.target.parent.savedetail.text = dateString;
showConfirm("saved", saveNum.substr(saveNum.length-1, 1));
dispatchEvent(new Event("closeThis"));
}
private function restore(e){
puzzle = Engine.puzzle;
inv = Engine.inv;
player = Engine.player;
back = Engine.back;
options = Engine.options;
var parentBtn = e.target.parent.name;
var slotNum = parentBtn.substr(parentBtn.length-1, 1);
var saveNum = "save" + slotNum;
trace(saveNum);
Engine.restoring = true;
allSaveData = null;
if(useExternalFile){
// Get data from external .js file
} else if (useShared){
// Get data from local memory
shared = SharedObject.getLocal("myApp");
if(shared.data[saveNum]){
trace("Restoring: " + shared.data[saveNum]);
allSaveData = new Object;
allSaveData = JSON.stringify(shared.data[saveNum]);
}
}
// Restore game data
if(allSaveData){
puzzle.restorePuzzles(allSaveData.puzzleStatus);
inv.restoreInv(allSaveData.currentInv, allSaveData.allInv);
options.restoreOptions(allSaveData.optset);
Engine.newBack = allSaveData.playerLoc.room;
addEventListener("repose", reposePlayer);
stageRef.dispatchEvent(new Event("changeBackground"));
showConfirm("restored", slotNum);
dispatchEvent(new Event("closeThis"));
} else {
trace ("No save data found");
Engine.restoring = false;
}
}
private function fakeScreenshot(bgName:String):Object{
// Flash's local memory is too small to contain real screenshots, so we can fake it by creating an instance of the background
var fakeShot:Object = new Object;
var bgRef = getDefinitionByName(bgName);
var bg = new bgRef;
// Remove all the interface junk from the background movieclip
for (var c = 0; c < bg.numChildren; ++c){
var thisChild = bg.getChildAt(c);
if (thisChild.name.search("_L") != -1 ||
thisChild.name.search("_U") != -1 ||
thisChild.name.search("_G") != -1 ||
thisChild.name.search("_T") != -1 ){
if (thisChild.usePoint)
thisChild.usePoint.visible = false;
}
if(thisChild.name.search("_O") != -1){
thisChild.usePoint.visible = false;
thisChild.depthSplit.visible = false;
thisChild.nodeUL.visible = false;
thisChild.nodeUR.visible = false;
thisChild.nodeLR.visible = false;
thisChild.nodeLL.visible = false;
}
if (thisChild.name.search("EXIT") != -1)
thisChild.visible = false;
if (thisChild.name.search("startPoint") != -1)
thisChild.visible = false;
}
bg.scaleX = .1;
bg.scaleY = .1;
bg.x = 10;
bg.y = 5;
var bgmask:MovieClip = new MovieClip;
bgmask.graphics.beginFill(0x000000, .5);
bgmask.graphics.drawRect(0, 0, 70, 45);
bgmask.graphics.endFill();
bgmask.x = bg.x;
bgmask.y = bg.y;
bg.mask = bgmask;
fakeShot.bg = bg;
fakeShot.bgmask = bgmask;
return fakeShot;
}
private function reposePlayer(e){
player = Engine.player;
player.x = allSaveData.playerLoc.x;
player.y = allSaveData.playerLoc.y;
player.scaleX = allSaveData.playerLoc.scaleX;
}
private function showConfirm(type:String, slot){
confirm = null;
confirm = new MovieClip;
confirm.graphics.beginFill(0x000000, .75);
confirm.graphics.drawRoundRect(0, 0, 200, 25, 10);
confirm.graphics.endFill();
stageRef.addChild(confirm);
var conftext:TextField = new TextField();
conftext.text = "Game " + type + " at slot " + slot;
var format1:TextFormat = new TextFormat();
format1.font = "Arial";
format1.size = 18;
format1.color = 0xFFFFFF;
conftext.setTextFormat(format1);
conftext.width = confirm.width - 5;
conftext.x = 5;
confirm.addChild(conftext);
confirm.addEventListener(Event.ENTER_FRAME, fadeConf);
}
private function fadeConf(e){
if (confirm.alpha > 0){
confirm.alpha -= .05;
} else {
confirm.removeEventListener(Event.ENTER_FRAME, fadeConf);
stageRef.removeChild(confirm);
}
}
private function closeSaver(e):void{
visible = false;
Engine.playerControl = true;
Engine.toolbar.dispatchEvent(new Event("closedWindow"));
}
}
}

#2007: Parameter format must be non-null?

i have a problem with my as3 code,
i try to link a movie clip to different scene (quiz scene).
so,i have 2 quiz in total, first quiz is using external script (as)
And the second quiz have the same script like first quiz, but i placed the action script inside fla. and it had different xml.
but then this error message appeared:
TypeError: Error #2007: Parameter format must be non-null.
at flash.text::TextField/set defaultTextFormat()
at hiragana/createText()[E:\flash\!!!! FLASH JADI\PAK ASHAR FIX\hiragana.as:80]
at hiragana/kuisdua()[hiragana::frame209:48]
at hiragana/frame209()[hiragana::frame209:249]
this is the code:
// creates a text field
public function createText(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField {
var tField:TextField = new TextField();
tField.x = x;
tField.y = y;
tField.width = width;
tField.defaultTextFormat = tf; //looks like this is the source of problem (-.-)
tField.selectable = false;
tField.multiline = true;
tField.wordWrap = true;
if (tf.align == "left") {
tField.autoSize = TextFieldAutoSize.LEFT;
} else {
tField.autoSize = TextFieldAutoSize.CENTER;
}
tField.text = text;
s.addChild(tField);
return tField;
}
and this is the ettire code
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.net.URLLoader;
import flash.net.URLRequest;
///*public class*/ kuisduaa extends MovieClip {
// question data
/*private*/ var dataXML2:XML;
// text formats
/*private*/ var questionFormat2:TextFormat;
/*private*/ var answerFormat2:TextFormat;
/*private*/ var scoreFormat2:TextFormat;
// text fields
/*private*/ var messageField2:TextField;
/*private*/ var questionField2:TextField;
/*private*/ var scoreField2:TextField;
// sprites and objects
/*private*/ var gameSprite2:Sprite;
/*private*/ var questionSprite2:Sprite;
/*private*/ var answerSprites2:Sprite;
/*private*/ var gameButton2:GameButton;
// game state variables
/*private*/ var questionNum2:int;
/*private*/ var correctAnswer2:String;
/*private*/ var numQuestionsAsked2:int;
/*private*/ var numCorrect2:int;
/*private*/ var answers2:Array;
/*public*/ function kuisdua() {
// create game sprite
gameSprite2 = new Sprite();
addChild(gameSprite2);
// set text formats
questionFormat2 = new TextFormat("Arial",80,0xffffff,true,false,false,null,null,"center");
answerFormat2 = new TextFormat("Arial",50,0xffffff,true,false,false,null,null,"left");
scoreFormat2 = new TextFormat("Arial",30,0xffffff,true,false,false,null,null,"center");
// create score field and starting message text
scoreField2 = createText("",scoreFormat,gameSprite,-30,550,550);
messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);
// set up game state and load questions
questionNum2 = 0;
numQuestionsAsked2 = 0;
numCorrect2 = 0;
showGameScore2();
xmlImport2();
}
// start loading of questions
/*public*/ function xmlImport2() {
var xmlURL:URLRequest = new URLRequest("kuis2.xml");
var xmlLoader:URLLoader = new URLLoader(xmlURL);
xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
}
// questions loaded
/*public*/ function xmlLoaded2(event:Event) {
dataXML = XML(event.target.data);
gameSprite.removeChild(messageField);
messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500);
showGameButton("mulai");
}
// creates a text field
/*public*/ function createText2(text:String, tf:TextFormat, s:Sprite, x,y: Number, width:Number): TextField {
var tField2:TextField = new TextField();
tField2.x = x;
tField2.y = y;
tField2.width = width;
tField2.defaultTextFormat = tf;
tField2.selectable = false;
tField2.multiline = true;
tField2.wordWrap = true;
if (tf.align == "left") {
tField2.autoSize = TextFieldAutoSize.LEFT;
} else {
tField2.autoSize = TextFieldAutoSize.CENTER;
}
tField2.text = text;
s.addChild(tField2);
return tField2;
}
// updates the score
/*public*/ function showGameScore2() {
scoreField2.text = "Soal: "+numQuestionsAsked2+" Benar: "+numCorrect2;
}
// ask player if they are ready for next question
/*public*/ function showGameButton2(buttonLabel:String) {
gameButton = new GameButton();
gameButton.label.text = buttonLabel;
gameButton.x = 240;
gameButton.y = 480;
gameSprite2.addChild(gameButton);
gameButton.addEventListener(MouseEvent.CLICK,pressedGameButton2);
}
// player is ready
/*public*/ function pressedGameButton2(event:MouseEvent) {
// clean up question
if (questionSprite2 != null) {
gameSprite2.removeChild(questionSprite2);
}
// remove button and message
gameSprite2.removeChild(gameButton);
gameSprite2.removeChild(messageField2);
// ask the next question
if (questionNum >= dataXML.child("*").length()) {
gotoAndStop(6);
} else {
askQuestion2();
}
}
// set up the question
/*public*/ function askQuestion2() {
// prepare new question sprite
questionSprite2 = new Sprite();
gameSprite2.addChild(questionSprite2);
// create text field for question
var question2:String = dataXML.item[questionNum].question2;
if (dataXML.item[questionNum].question.#type == "text") {
questionField2 = createText(question2,questionFormat2,questionSprite2,50,150,300);
} else {
var questionLoader2:Loader = new Loader();
var questionRequest2:URLRequest = new URLRequest("triviaimages/"+question2);
questionLoader2.load(questionRequest2);
questionLoader2.y = 150;
questionLoader2.x = 180;
questionSprite2.addChild(questionLoader2);
}
// create sprite for answers, get correct answer and shuffle all
correctAnswer2 = dataXML.item[questionNum2].answers.answer[0];
answers2 = shuffleAnswers(dataXML.item[questionNum2].answers);
// put each answer into a new sprite with a icon
answerSprites2 = new Sprite();
var xpos:int = 0;
var ypos:int = 0;
for(var i:int=0;i<answers2.length;i++) {
var answerSprite2:Sprite = new Sprite();
if (answers2[i].type == "text") {
var answerField2:TextField = createText(answers2[i].value,answerFormat2,answerSprite2,30,-35,200);
} else {
var answerLoader2:Loader = new Loader();
var answerRequest2:URLRequest = new URLRequest("triviaimages/"+answers2[i].value);
answerLoader2.load(answerRequest2);
answerLoader2.y = -22;
answerLoader2.x = 25;
answerSprite2.addChild(answerLoader2);
}
var letter:String = String.fromCharCode(65+i); // A-D
var circle:Circle = new Circle(); // from Library
circle.letter.text = letter;
circle.answer = answers[i].value;
answerSprite2.x = 100+xpos*250;
answerSprite2.y = 350+ypos*100;
xpos++
if (xpos > 1) {
xpos = 0;
ypos += 1;
}
answerSprite2.addChild(circle);
answerSprite2.addEventListener(MouseEvent.CLICK,clickAnswer); // make it a button
// set a larger click area
answerSprite2.graphics.beginFill(0x000000,0);
answerSprite2.graphics.drawRect(-50, 0, 200, 80);
answerSprites2.addChild(answerSprite2);
}
questionSprite2.addChild(answerSprites2);
}
// take all the answers and shuffle them into an array
/*public*/ function shuffleAnswers2(answers:XMLList) {
var shuffledAnswers2:Array = new Array();
while (answers2.child("*").length() > 0) {
var r:int = Math.floor(Math.random()*answers.child("*").length());
shuffledAnswers2.push({type: answers2.answer[r].#type, value: answers2.answer[r]});
delete answers2.answer[r];
}
return shuffledAnswers2;
}
// player selects an answer
/*public*/ function clickAnswer2(event:MouseEvent) {
// get selected answer text, and compare
var selectedAnswer2 = event.currentTarget.getChildAt(1).answer;
if (selectedAnswer2 == correctAnswer2) {
numCorrect++;
messageField2 = createText("Hai, kamu benar ! ",scoreFormat2,gameSprite2,-30,280,550);
} else {
messageField2 = createText("Iie, Jawabanmu Salah, yang benar adalah:",scoreFormat2,gameSprite2,53,280,370);
}
finishQuestion();
}
/*public*/ function finishQuestion2() {
// remove all but the correct answer
for(var i:int=0;i<4;i++) {
answerSprites2.getChildAt(i).removeEventListener(MouseEvent.CLICK,clickAnswer);
if (answers2[i].value != correctAnswer2) {
answerSprites2.getChildAt(i).visible = false;
} else {
answerSprites2.getChildAt(i).x = 200;
answerSprites2.getChildAt(i).y = 400;
}
}
// next question
questionNum2++;
numQuestionsAsked2++;
showGameScore2();
showGameButton2("Lanjutkan");
}
// clean up sprites
/*public*/ function CleanUp2() {
removeChild(gameSprite);
gameSprite2 = null;
questionSprite2 = null;
answerSprites2 = null;
dataXML2 = null;
}
the first quiz played perfectly with that code,
and i have no clue why this error appeared,
i'm beginner in as3 so i'm still lack in many ways,
can anyone help me,?
i really apreciate it.. :)
Are you sure that you're parsing a non-null TextFormat instance as the second argument of createText()?
The error means that you're supplying a null value for tf:TextFormat.
Unless I am missing something, your issue is here:
messageField2 = createText("Loading Questions...",questionFormat,gameSprite,0,50,550);
&
messageField = createText("Tap Untuk Memulai",scoreFormat,gameSprite,-10,250,500);
I see questionFormat2 and scoreFormat2 are instantiated, but I never see a questionFormat or scoreFormat. Your error says that the defaultTextFormat (or TextFormat supplied using setTextFormat(), for future reference), cannot be null. Null means that the object has not been instantiated/created yet. questionFormat and scoreFormat are never instantiated. Hell, their variables do not even exist. If you were using a proper development IDE (FlashBuilder, FlashDevelop, etc), you'd never be able to compile this code.
Switch those two lines to use the correct formats and you should be fine.

event listener won't work second time around AS3

I'm stuck! If I need to go into more detail please just leave a comment and I will elaborate.
I've tried to create some code that dynamically adds linked objects to the stage and then removes then when dropped in the correct area, which in turn creates the next and so on. The information is in an array and it cycles through until the game is complete and the targetScore is met. If a timer runs out the games stops, and the win() or lose() functions are called and a retry button is displayed. This works fine until the game has stopped and I try to restart the program using the retry() function. The retry() function attempts to reset everything as it was when the program started, by creating the baseball object again and then letting the releaseToDrop() repeat everything as it did the first time. Depending on where I have stopped, when I get around to the same place a second time, the clicktoDrag1() function fails to pick up the current object. It could be on any 1 of the 8 objects that are created dynamically from the library. When the stage hears the listener on *mouse_up* I can click and drag the object but then it kind of falls apart as it goes slightly out of synch with the arrays (which were reset in the retry() function), the target which it's dropped on doesn't recognise it even though all the trace statement read as they should. I know this is a lot to look though, and I'm not sure if this can be solved via the forum, any general tips would be appreciated though.
I normally keep the code simple, but I want to advance and make the code write itself, which seems to work until things get too complicated for me.
I've never posted for help before, but I've given this everything, if it can't be fixed I'll have to start again and simplify.
Thanks in advance if anyone takes the time to look at this, I would be humbled - and would love to use this forum more to become a better coder.
It's all on the timeline, here's the code.
import flash.display.MovieClip;
import flash.ui.Mouse;
var startPosX = 450;
var startPosY = 400;
//setup first clip
var baseball:MovieClip = new Baseball();
baseball.name = "baseball";
addChild(baseball);
baseball.buttonMode = true;
baseball.x = startPosX;
baseball.y = startPosY;
activity_txt.text = "Swinging a baseball bat";
//setup small clips
baseballSmall.visible = false;
golfSmall.visible = false;
swimSmall.visible = false;
boxingSmall.visible = false;
tennisSmall.visible = false;
dartsSmall.visible = false;
powerSmall.visible = false;
marathonSmall.visible = false;
theEnd.visible = false;
retry_btn.visible = false;
fast1.visible = false;
fast2.visible = false;
fast3.visible = false;
fast4.visible = false;
slow1.visible = false;
slow2.visible = false;
slow3.visible = false;
slow4.visible = false;
//setup vars
var counter:int = 0;
var sportCounter:int = 0;
var startingLife:int = 15;
var playerLife = startingLife;
var lifeBoost:int = 3;
var targetScore:int = 8;
var countdownTimer:Timer = new Timer(500,0);
var questionTimer:Timer = new Timer(250,2);
var score:int = 0;
var smallArray = new Array("baseballSmall","golfSmall", "swimSmall", "boxingSmall","tennisSmall", "dartsSmall", "powerSmall", "marathonSmall");
var sportArray = new Array("baseball","Golf", "Swimming", "Boxing", "Tennis", "Darts", "PowerLifting", "Marathon");
var answersArray = new Array("fast", "fast", "slow", "fast", "fast", "slow", "slow", "slow");
var letArray = new Array("fast1", "fast2", "slow1", "fast3", "fast4", "slow2", "slow3", "slow4");
var activityTXTArray = new Array("Golf swing", "100m swim", "Boxing punch", "Tennis racquet swing", "Darts throw", "Power lifting", "Marathon");
var arraySmall:Array = smallArray;
var arrayLet:Array = letArray;
var arrayActivity:Array = activityTXTArray;
//var draggable = getChildByName(sportArray[0]);
//setup bonus bar
bonusBar.gotoAndStop(2);
bonusBar.x = timeBar.x;
bonusBar.y = timeBar.y - timeBar.height;
bonusBar.height = timeBar.height/startingLife * lifeBoost;
playerLife = startingLife;
timeBar.height = playerLife * (300/startingLife);
/* listeners */
countdownTimer.addEventListener(TimerEvent.TIMER, timerTick);
countdownTimer.start();
retry_btn.addEventListener(MouseEvent.CLICK, retry);
baseball.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag1);
stage.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
function clickToDrag1(event:MouseEvent):void
{
var draggable = getChildByName(sportArray[sportCounter]);
trace("the counter name is "+ sportArray[sportCounter]);
trace("the baseball name is "+ baseball.name);
trace("the draggable name is "+ draggable.name);
trace("the answer array is "+ answersArray[counter]);
trace("the sport array is "+ sportArray[sportCounter]);
this.setChildIndex(draggable,this.numChildren-1);
draggable.startDrag();
}
function releaseToDrop(event:MouseEvent):void
{
//get current obj name from sportArray
var draggable = getChildByName(sportArray[sportCounter]);
//check if this obj is dropped on the Fast or Slow MovieClip
if(draggable.hitTestObject(getChildByName(answersArray[counter])))
{
//move on to the next F/S answer
counter++;
score++;
var tick = new Tick();
addChild(tick);
tick.x = 370;
tick.y = 200;
activity_txt.text = activityTXTArray.shift();
playerLife += lifeBoost;
timeBar.height = playerLife * (300/startingLife);
bonusBar.gotoAndPlay(2);
var smallName = getChildByName(smallArray.shift());
smallName.visible = true;
var letters = getChildByName(letArray.shift());
letters.visible = true;
//remove the drag listenter on the current object (name assigned via sportArray)
draggable.removeEventListener(MouseEvent.MOUSE_DOWN, clickToDrag1);
//stage.removeEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
//remove the current object
removeChild(getChildByName(sportArray[sportCounter]));
//delete ref
var deleteRef = getChildByName(sportArray[sportCounter]);
deleteRef = null;
//move on to the next one
sportCounter++;
//add a new object
var obj:Class = getDefinitionByName(sportArray[sportCounter]) as Class;
var myMclip = new obj();
//name it
myMclip.name = sportArray[sportCounter];
//var clipName = getChildByName(sportArray[0]);
myMclip.x = myMclip.y = 400;
myMclip.buttonMode = true;
trace("myClip name "+myMclip.name);
addChild(myMclip);
//add listener to new obj (is this removed via draggable?)
myMclip.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag1);
//stage.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
}
else{
draggable.x = startPosX;
draggable.y = startPosY;
draggable.stopDrag();
var cross = new Cross();
addChild(cross);
cross.x = 370;
cross.y = 200
}
}
function timerTick(e:TimerEvent):void {
//removes from 40(life) every half a second
playerLife -= 1;
//bar height = % of whats left of life
timeBar.height = playerLife * (300/startingLife);
bonusBar.y = timeBar.y - timeBar.height;
if(playerLife == 0) {
loseGame();
} else if(playerLife>0 && score > targetScore-1) {
winGame();
}
}
function loseGame():void
{
var removeCurrent = getChildByName(sportArray[sportCounter]);
removeCurrent.visible = false;
hideStuff();
theEnd.visible = true;
theEnd.end_txt.text = "sorry you lost"
retry_btn.visible = true;
//baseball.removeEventListener(MouseEvent.MOUSE_DOWN, clickToDrag1);
//stage.removeEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
//baseball = null;
trace(baseball);
}
function winGame():void
{
var removeCurrent = getChildByName(sportArray[sportCounter]);
removeCurrent.visible = false;
hideStuff();
theEnd.visible = true;
theEnd.end_txt.text = "You've won!"
retry_btn.visible = true;
baseball.removeEventListener(MouseEvent.MOUSE_DOWN, clickToDrag1);
//stage.removeEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
}
function retry(e:MouseEvent):void
{
playerLife = startingLife;
timeBar.height = playerLife * (300/startingLife);
score = 0;
counter = 0;
sportCounter = 0;
countdownTimer.reset();
countdownTimer.start();
var baseball:MovieClip = new Baseball();
baseball.name = "baseball";
trace("the type is "+baseball);
trace("the name is " + baseball.name);
addChild(baseball);
baseball.buttonMode = true;
baseball.x = startPosX;
baseball.y = startPosY;
baseball.addEventListener(MouseEvent.MOUSE_DOWN, clickToDrag1);
//stage.addEventListener(MouseEvent.MOUSE_UP, releaseToDrop);
activity_txt.text = "Swinging a baseball bat";
smallArray = arraySmall;
letArray = arrayLet;
activityTXTArray = arrayActivity;
retry_btn.visible = false;
theEnd.visible = false;
showStuff();
smallArray = new Array("baseballSmall","golfSmall", "swimSmall", "boxingSmall","tennisSmall", "dartsSmall", "powerSmall", "marathonSmall");
var sportArray = new Array("baseball","Golf", "Swimming", "Boxing", "Tennis", "Darts", "PowerLifting", "Marathon");
var answersArray = new Array("fast", "fast", "slow", "fast", "fast", "slow", "slow", "slow");
var letArray = new Array("fast1", "fast2", "slow1", "fast3", "fast4", "slow2", "slow3", "slow4");
var activityTXTArray = new Array("Golf swing", "100m swim", "Boxing punch", "Tennis racquet swing", "Darts throw", "Power lifting", "Marathon");
}
function showStuff():void
{
activity_txt.visible = true;
fast.visible = true;
slow.visible = true;
timeBar.visible = true;
bonusBar.visible = true;
}
function hideStuff():void
{
fast1.visible = false;
fast2.visible = false;
fast3.visible = false;
fast4.visible = false;
slow1.visible = false;
slow2.visible = false;
baseballSmall.visible = false;
golfSmall.visible = false;
swimSmall.visible = false;
boxingSmall.visible = false;
tennisSmall.visible = false;
dartsSmall.visible = false;
activity_txt.visible = false;
fast.visible = false;
slow.visible = false;
timeBar.visible = false;
bonusBar.visible = false;
}
The OP has solved the problem, as is indicated in this comment:
I hadn't removed the object on game end, I had hidden it so when it came around again a duplicate was created. I've removed it instead of hiding and it works fine. Having two clips with on the stage created some strange drag and drop behavior which sort of gave it away. "This is not 'my' answer. MAngoPop answered this in the comments but forgot to add it as an answer."