Where is the error in my code? as3 - actionscript-3

I'm trying to make a simple quiz game but my code started passing weird things to the questionsbox textbox. The code was running fine the first time I tried it. After a while, questionbox started displaying random characters like a, i, o, r and e when I try to run the test. Also, inputbox also seems to only accept these characters now.
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.events.Event;
stop();
start_btn.addEventListener(MouseEvent.CLICK, startQuiz)
function startQuiz(event:MouseEvent):void {
nextFrame();
var questions:Array = new Array;
var answers:Array = new Array;
var userAnswers:Array = new Array;
var grade:String
var score:int = 0;
var quizProgress:int = 0;
var myTextField = new TextField();
// Edit questions here
questions[0] = "What is x if x - 5 = 3?";
questions[1] = "What is the square root of 49?";
questions[2] = "What is the area of a circle whose diameter is 4?";
questions[3] = "What is 5 + 10?";
questions[4] = "What is -15 * 2?";
// Edit answers here
answers[0] = "8";
answers[1] = "7";
answers[2] = "12.57";
answers[3] = "15";
answers[4] = "-30";
generateQuestion();
function generateQuestion()
{
questionbox.text = questions[quizProgress];
}
function updateScore()
{
for(var i:int = 0; i < questions.length; i++)
{
if(userAnswers[i] == answers[i])
{
score++;
}
}
}
function generateGrade()
{
switch (score)
{
case 0:
grade = "F";
break;
case 1:
grade = "D";
break;
case 2:
grade = "C";
break;
case 4:
grade = "B";
break;
case 5:
grade = "A";
break;
}
}
submit_btn.addEventListener(MouseEvent.CLICK, submitAnswer)
function submitAnswer(event:Event):void
{
if (quizProgress < 4)
{
userAnswers[quizProgress] = inputbox.text;
quizProgress++;
generateQuestion();
inputbox.text = "";
}
else
{
userAnswers[quizProgress] = inputbox.text;
quizProgress++
inputbox.text = "";
questionbox.text = "";
updateScore();
generateGrade();
submit_btn.removeEventListener(MouseEvent.CLICK, submitAnswer)
nextFrame();
grade_text.text = grade;
}
}
}

Related

Can't get dynamic text to change in AS3

Here's the link to the whole project including all the dependencies if needed.
https://www.dropbox.com/sh/3d3towtkhb4c38r/AADdxDJq9ix7bK9hTkt_VTSAa?dl=0
Basically trying to clean up some script I was left to deal with and have been banging my head against the wall as to why this isn't working. I don't get any debug errors, everything seems to be linked where it needs to be linked. My font seems to be embedded, all my instance names seem to be right... the only thing I can think of is I'm missing something silly in the code. Any help would be really appreciated! Nothing like being left a mess and having to fix it.
Basically the text box is supposed to have a countdown timer based on what race is approaching (e.g Race X is in xxx minutes) and If there isn't a race approaching, it should show some default text. At the moment, It doesn't seem to want to change the dynamic text at all!
EDIT: I'll also mention the RaceRibbon Movieclip that the text is contained in is also exported for as3 to the com.RaceRibbon class.
package {
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.ui.Mouse;
import flash.utils.Timer;
import com.boo.CustomDate;
import com.boo.ScreensaverSimple;
import com.RaceRibbon;
// This sections is for the image slides and Hour Of Power setting.
public class Generic extends MovieClip {
// This is where you can set the Hour of Power time start and end time (in 24 hour format e.g. 1330 for 1:30pm)
// If there is no hour of power, simply set both numbers to 0
private var HourOfPowerStartTime:Number = 0;
private var HourOfPowerEndTime:Number = 0;
private var HourOfPower1StartTime:Number = 0;
private var HourOfPower1EndTime:Number = 0;
public var race_ribbon:RaceRibbon;
private var ss:ScreensaverSimple;
public var time_check_timer:Timer;
public var is_race_time:Boolean;
public var current_state:String;
public var next_race:Date;
public var race_time_arr:Array;
public var race_num:int;
private var ss_time_arr:Array;
private var delay_add_timer:Timer;
//Set default text
private var default_ribbon_text:String = "THERACES.COM.AU";
// Set Race Times
private var r1:Date = new Date(2017,5,5,12,15);
private var r2:Date = new Date(2017,5,5,12,50);
private var r3:Date = new Date(2017,5,5,13,25);
private var r4:Date = new Date(2017,5,5,14,00);
private var r5:Date = new Date(2017,5,5,14,35);
private var r6:Date = new Date(2017,5,5,15,15);
private var r7:Date = new Date(2017,5,5,15,55);
private var r8:Date = new Date(2017,5,5,16,35);
private var r9:Date = new Date(2017,5,5,17,15);
// Hide the mouse
public function Generic() {
Mouse.hide();
// Set Race Ribbon
race_ribbon = new RaceRibbon;
race_ribbon.x = 1109;
race_ribbon.y = 983;
race_time_arr = [r1,r2,r3,r4,r5,r6,r7,r8,r9];
// Display Slideshow
ss = new ScreensaverSimple;
ss.setScreensaver(screens);
// Make sure Hour of Power is not visible
HOP1.visible = false;
HOP2.visible = false;
time_check_timer = new Timer(1000);
time_check_timer.addEventListener(TimerEvent.TIMER, checkTime);
delay_add_timer = new Timer(1,1);
delay_add_timer.addEventListener(TimerEvent.TIMER, addAllChildren);
delay_add_timer.start();
}
public function addAllChildren(evt:TimerEvent=null):void {
delay_add_timer.removeEventListener(TimerEvent.TIMER, addAllChildren);
delay_add_timer.stop();
delay_add_timer = null;
addChild(race_ribbon);
time_check_timer.start();
checkTime();
}
public function checkTime(evt:TimerEvent=null):void {
setDatesToCurrent(race_time_arr);// This makes every day race day
setDatesToCurrent(ss_time_arr);// This makes all screensaver dates current
checkNextRace();
if(next_race != null && is_race_time == false)// If it isn't race time
{
setCountdown();
}
if(next_race == null && is_race_time == true)// If it's race time
{
setDefaultText();
}
checkHOP1();
checkHOP2();
}
//Call to make Hour Of Power 1 visible/invisible based on set times
private function checkHOP1():void {
HOP1.visible = (HourOfPowerStartTime || HourOfPowerEndTime);
if (!HOP1.visible) return;
var CurrentTime:Number = CustomDate.return24HourNumber();
HOP1.visible = (CurrentTime >= HourOfPowerStartTime && CurrentTime <= HourOfPowerEndTime);
}
//Call to make Hour Of Power 2 visible/invisible based on set times
private function checkHOP2():void {
HOP2.visible = (HourOfPower1StartTime || HourOfPower1EndTime);
if (!HOP2.visible) return;
var CurrentTime:Number = CustomDate.return24HourNumber();
HOP2.visible = (CurrentTime >= HourOfPower1StartTime && CurrentTime <= HourOfPower1EndTime);
}
public function setDatesToCurrent(arr:Array):void {// This makes every day race day
var cd:Date = new Date();// Current Date
for(var i:int=0;i<arr.length;i++){
arr[i].fullYear = cd.fullYear;
arr[i].month = cd.month;
arr[i].date = cd.date;
}
}
public function checkNextRace():void {
var ct:Date = new Date();// Current Time as a Date
next_race = null;
is_race_time = false;
// FOR LOOP THIS... one day
if(ct < r1) {
next_race = r1;
} else if(raceTimeSpan(r1) == true) {
is_race_time = true;
race_num = 1;
} else if(ct > raceTimeSpan(r1) && ct < r2) {
next_race = r2;
} else if(raceTimeSpan(r2) == true) {
is_race_time = true;
race_num = 2;
} else if(ct > raceTimeSpan(r2) && ct < r3) {
next_race = r3;
} else if(raceTimeSpan(r3) == true) {
is_race_time = true;
race_num = 3;
} else if(ct > raceTimeSpan(r3) && ct < r4) {
next_race = r4;
} else if(raceTimeSpan(r4) == true) {
is_race_time = true;
race_num = 4;
} else if(ct > raceTimeSpan(r4) && ct < r5) {
next_race = r5;
} else if(raceTimeSpan(r5) == true) {
is_race_time = true;
race_num = 5;
} else if(ct > raceTimeSpan(r5) && ct < r6) {
next_race = r6;
} else if(raceTimeSpan(r6) == true) {
is_race_time = true;
race_num = 6;
} else if(ct > raceTimeSpan(r6) && ct < r7) {
next_race = r7;
} else if(raceTimeSpan(r7) == true) {
is_race_time = true;
race_num = 7;
} else if(ct > raceTimeSpan(r7) && ct < r8) {
next_race = r8;
} else if(raceTimeSpan(r8) == true) {
is_race_time = true;
race_num = 8;
} else if(ct > raceTimeSpan(r8) && ct < r9) {
next_race = r9;
} else if(raceTimeSpan(r9) == true) {
is_race_time = true;
race_num = 9;
} else if(ct > raceTimeSpan(r9)) {// If all races are finished
setDefaultText();
}
}
public function raceTimeSpan(d:Date):Boolean {
var race_mins:int = 2;
var race_on:Boolean = false;
var ct:Date = new Date();
if(ct.hours == d.hours) {
var max_mins:int = d.minutes + race_mins;
if(ct.minutes >= d.minutes && ct.minutes < max_mins) {
race_on = true;
}
}
return race_on;
}
public function setCountdown():void {
var hours_left:int = int(String(CustomDate.countdownTime(next_race)).split(":")[0]);
var mins_left:int = int(String(CustomDate.countdownTime(next_race)).split(":")[1]);
mins_left = (60*hours_left)+mins_left;
is_race_time = false;
if(mins_left > 2) {
race_ribbon.setText("NEXT RACE IN <font color='#000000' letterspacing='-1'>"+(mins_left+1)+" MINUTES</font>");
race_ribbon.setBG(0);
} else if(mins_left < 3) {
if((mins_left+1) <= 1) {
race_ribbon.setText("NEXT RACE IN <font color='#fdb913' letterspacing='-1'>"+(mins_left+1)+" MINUTE</font>");
} else {
race_ribbon.setText("NEXT RACE IN <font color='#fdb913' letterspacing='-1'>"+(mins_left+1)+" MINUTES</font>");
}
race_ribbon.setBG(1);
}
}
public function setDefaultText():void {
race_ribbon.setText("<font color='#fdb913' letterspacing='-1'>"+default_ribbon_text+"</font>");
race_ribbon.setBG(1);
}
}
}
And just in case you don't want to go through the files individually the com.RaceRibbon code is
package com {
import flash.display.MovieClip;
import fl.motion.Color;
import flash.display.Sprite;
import flash.text.*;
public class RaceRibbon extends MovieClip {
private var c1:Color;
private var c2:Color;
public function RaceRibbon() {
c1 = new Color();
c1.setTint(0xfdb913,1);
c2 = new Color();
c2.setTint(0x000000,1);
}
public function setText(str:String=""):void {
str = str.toUpperCase();
this.tb.htmlText = str;
}
public function setBG(p:int=0):void {
switch(p){
case 0:
bg.transform.colorTransform = c1;
break;
case 1:
bg.transform.colorTransform = c2;
break;
}
}
}
}
I've not had a chance to test your project files but just a suggestion on elimination :
Either manually trigger setDefaultText(); or else directly target the RaceRibbon's textField (so just comment // out the other two you aren't testing from those shown 3 lines of code).
If any Update test below work correctly to update text then your true problem lies in either :
IF statement of function setCountdown():(before if(mins_left > 2) what does trace ("minutes left: " + mins_left); say about the amount? Does it look like it could ever become > 2 or < 3 or +1 <= 1? If not, then your text will not update either.)
or function checkNextRace() (especially if you set next_race = null; then surely following that with next_race = r1; should give a debugger error like "Cannot set a value to a variable that is NULL (non-existent)" but you said you got no errors so I'm confused why mine does that. (use ctrl+shift_+enter to debug not that Test Movie option).
Anyways the code...
public function Generic() {
Mouse.hide();
// Set Race Ribbon
race_ribbon = new RaceRibbon;
race_ribbon.x = 1109; race_ribbon.y = 983;
// Update test #1
setDefaultText(); //did via Function work?
// Update test #2
race_ribbon.tb.htmlText = "testing123"; //did via Direct Targeting work?
race_ribbon.tb.htmlText = "<font color='#fdb913' letterspacing='-1'>" + "testing123" + "</font>"; //maybe works with HTML?
// Temp disable other code for above elimination tests
/*
race_time_arr = [r1,r2,r3,r4,r5,r6,r7,r8,r9];
// Display Slideshow
ss = new ScreensaverSimple; ss.setScreensaver(screens);
// Make sure Hour of Power is not visible
HOP1.visible = false; HOP2.visible = false;
time_check_timer = new Timer(1000);
time_check_timer.addEventListener(TimerEvent.TIMER, checkTime);
delay_add_timer = new Timer(1,1);
delay_add_timer.addEventListener(TimerEvent.TIMER, addAllChildren);
delay_add_timer.start();
*/
}

Action Script 3.0: how can I type other languages in the array or how can I use the other languages in grids

Here is my code. This is my word search game ...In word list array ...these are my questions to find in grid in the game...my questions how can I type other languages in the array or how can I use the other languages in grids
import flash.display.*;
import flash.text.*;
import flash.geom.Point;
import flash.events.*;
import flash.net.FileFilter;
import flash.filters.GlowFilter;
const puzzleSize:uint = 20;
const spacing:Number = 24;
const outlineSize:Number = 20;
const offsetoint = new Point(162.9,179.7);
const offsettoint = new Point(300,265);
const spacingg:Number = 36;
const letterFormat:TextFormat = new TextFormat("Bamini",18,0x000000,true,false,false,null,null,TextFormatAlign.CENTER);
// words and grid
var wordList:Array;
var usedWords:Array;
var grid:Array;
// game state
var dragModetring;
var startPoint,endPointoint;
var numFound:int;
// sprites
var gameSpriteprite;
var outlineSpriteprite;
var oldOutlineSpriteprite;
var letterSpritesprite;
var wordsSpriteprite;
startWordSearch();
function startWordSearch() {
**// word list**
wordList = ("Lion,Tiger,Cheetah,Panther".split(",";
// set up the sprites
gameSprite = new Sprite();
addChild(gameSprite);
oldOutlineSprite = new Sprite();
gameSprite.addChild(oldOutlineSprite);
outlineSprite = new Sprite();
gameSprite.addChild(outlineSprite);
letterSprites = new Sprite();
gameSprite.addChild(letterSprites);
wordsSprite = new Sprite();
gameSprite.addChild(wordsSprite);
// array of letters
var letters:Array = placeLetters();
// array of sprites
grid = new Array();
for(var x:int=0;x<puzzleSize;x++) {
grid[x] = new Array();
for(var y:int=0;y<puzzleSize;y++) {
// create new letter field and sprite
var newLetter:TextField = new TextField();
newLetter.defaultTextFormat = letterFormat;
newLetter.x = x*spacing + offset.x;
newLetter.y = y*spacing + offset.y;
newLetter.width = spacing;
newLetter.height = spacing;
newLetter.text = letters[x][y];
newLetter.selectable = false;
var newLetterSpriteprite = new Sprite();
newLetterSprite.addChild(newLetter);
letterSprites.addChild(newLetterSprite);
grid[x][y] = newLetterSprite;
// add event listeners
newLetterSprite.addEventListener(MouseEvent.MOUSE_DOWN, clickLetter);
newLetterSprite.addEventListener(MouseEvent.MOUSE_OVER, overLetter);
}
}
// stage listener
stage.addEventListener(MouseEvent.MOUSE_UP, mouseRelease);
// create word list fields and sprites
for(var i:int=0;i<usedWords.length;i++) {
//var myglow:GlowFilter=new GlowFilter();
//myglow.color = 0x0000FF;
//myglow.blurX=5;
//myglow.blurY=5;
//myglow.strength=200;
var newWord:TextField = new TextField();
newWord.defaultTextFormat = letterFormat;
newWord.x = 700;
newWord.y = i*spacingg+offsett.y;
newWord.width =140;
newWord.height =spacing;
newWord.text = usedWords[i];
//newWord.filters=[myglow];
newWord.selectable = false;
wordsSprite.addChild(newWord);
}
// set game state
dragMode = "none";
numFound = 0;
}
// place the words in a grid of letters
function placeLetters():Array {
// create empty grid
var letters:Array = new Array();
for(var x:int=0;x<puzzleSize;x++) {
letters[x] = new Array();
for(var y:int=0;y<puzzleSize;y++) {
letters[x][y] = "*";
}
}
// make copy of word list
var wordListCopy:Array = wordList.concat();
usedWords = new Array();
// make 1000 attempts to add words
var repeatTimes:int = 1000;
repeatLoop:while (wordListCopy.length > 0) {
if (repeatTimes-- <= 0) break;
// pick a random word, location and direction
var wordNum:int = Math.floor(Math.random()*wordListCopy.length);
var wordtring = wordListCopy[wordNum].toUpperCase();
x = Math.floor(Math.random()*puzzleSize);
y = Math.floor(Math.random()*puzzleSize);
var dx:int = Math.floor(Math.random()*3)-1;
var dy:int = Math.floor(Math.random()*3)-1;
if ((dx == 0) && (dy == 0)) continue repeatLoop;
// check each spot in grid to see if word fits
letterLoop:for (var j:int=0;j<word.length;j++) {
if ((x+dx*j < 0) || (y+dy*j < 0) || (x+dx*j >= puzzleSize) || (y+dy*j >= puzzleSize)) continue repeatLoop;
var thisLettertring = letters[x+dx*j][y+dy*j];
if ((thisLetter != "*" && (thisLetter != word.charAt(j))) continue repeatLoop;
}
// insert word into grid
insertLoop:for (j=0;j<word.length;j++) {
letters[x+dx*j][y+dy*j] = word.charAt(j);
}
// remove word from list
wordListCopy.splice(wordNum,1);
usedWords.push(word);
}
// fill rest of grid with random letters
for(x=0;x<puzzleSize;x++) {
for(y=0;y<puzzleSize;y++) {
if (letters[x][y] == "*" {
letters[x][y] = String.fromCharCode(65+Math.floor(Math.random()*26));
}
}
}
return letters;
}
// player clicks down on a letter to start
function clickLetter(event:MouseEvent) {
var lettertring = event.currentTarget.getChildAt(0).text;
startPoint = findGridPoint(event.currentTarget);
dragMode = "drag";
}
// player dragging over letters
function overLetter(event:MouseEvent) {
if (dragMode == "drag" {
endPoint = findGridPoint(event.currentTarget);
// if valid range, show outline
outlineSprite.graphics.clear();
if (isValidRange(startPoint,endPoint)) {
drawOutline(outlineSprite,startPoint,endPoint,0x66CCFF);
}
}
}
// mouse released
function mouseRelease(event:MouseEvent) {
if (dragMode == "drag" {
dragMode = "none";
outlineSprite.graphics.clear();
// get word and check it
if (isValidRange(startPoint,endPoint)) {
var word = getSelectedWord();
checkWord(word);
}
}
}
// when a letter is clicked, find and return the x and y location
function findGridPoint(letterSpritebject)oint {
// loop through all sprites and find this one
for(var x:int=0;x<puzzleSize;x++) {
for(var y:int=0;y<puzzleSize;y++) {
if (grid[x][y] == letterSprite) {
return new Point(x,y);
}
}
}
return null;
}
// determine if range is in the same row, column, or a 45 degree diagonal
function isValidRange(p1,p2oint):Boolean {
if (p1.x == p2.x) return true;
if (p1.y == p2.y) return true;
if (Math.abs(p2.x-p1.x) == Math.abs(p2.y-p1.y)) return true;
return false;
}
// draw a thick line from one location to another
function drawOutline(sprite,p1,p2oint,c:Number) {
var offoint = new Point(offset.x+spacing/2, offset.y+spacing/2);
s.graphics.lineStyle(outlineSize,c);
s.graphics.moveTo(p1.x*spacing+off.x ,p1.y*spacing+off.y);
s.graphics.lineTo(p2.x*spacing+off.x ,p2.y*spacing+off.y);
}
// find selected letters based on start and end points
function getSelectedWord()tring {
// determine dx and dy of selection, and word length
var dx = endPoint.x-startPoint.x;
var dy = endPoint.y-startPoint.y;
var wordLength:Number = Math.max(Math.abs(dx),Math.abs(dy))+1;
// get each character of selection
var wordtring = "";
for(var i:int=0;i<wordLength;i++) {
var x = startPoint.x;
if (dx < 0) x -= i;
if (dx > 0) x += i;
var y = startPoint.y;
if (dy < 0) y -= i;
if (dy > 0) y += i;
word += grid[x][y].getChildAt(0).text;
}
return word;
}
// check word against word list
function checkWord(wordtring) {
// loop through words
for(var i:int=0;i<usedWords.length;i++) {
// compare word
if (word == usedWords[i].toUpperCase()) {
foundWord(word);
}
// compare word reversed
var reverseWordtring = word.split("".reverse().join("";
if (reverseWord == usedWords[i].toUpperCase()) {
foundWord(reverseWord);
}
}
}
// word found, remove from list, make outline permanent
function foundWord(wordtring) {
// draw outline in permanent sprite
drawOutline(oldOutlineSprite,startPoint,endPoint,0xE01212);
// find text field and set it to gray
for(var i:int=0;i<wordsSprite.numChildren;i++) {
if (TextField(wordsSprite.getChildAt).text.toUpperCase() == word) {
TextField(wordsSprite.getChildAt).textColor = 0xFF0000;
}
}
// see if all have been found
numFound++;
if (numFound ==usedWords.length) {
endGame();
}
}
function endGame() {
gotoAndStop("gameover";
cleanUp();
Timee.stop();
}
function cleanUp() {
removeChild(gameSprite);
gameSprite = null;
grid = null;
vv=null;
}

error while converting AS2 starfield code to AS3

I've tried to convert a nice AS2 script for starfirld effect to AS3 But i'm still getting strange errors
would really appreciate if any one could help me understand what am i doing wrong
here is the original AS2 code:
var stars = 100;
var maxSpeed = 16;
var minSpeed = 2;
var i = 0;
while (i < stars)
{
var mc = this.attachMovie("star", "star" + i, i);
mc._x = random(Stage.width);
mc._y = random(Stage.height);
mc.speed = random(maxSpeed - minSpeed) + minSpeed;
var size = random(2) + 6.000000E-001 * random(4);
mc._width = size;
mc._height = size;
++i;
} // end while
this.onEnterFrame = function ()
{
for (var _loc3 = 0; _loc3 < stars; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = Stage.height;
_loc2.speed = random(maxSpeed - minSpeed) + minSpeed;
_loc2._x = random(Stage.width);
} // end of for
};
and here is my AS3 version:
import flash.events.Event;
import flash.events.MouseEvent;
function starField():void
{
var stars:int = 100;
var maxSpeed:int = 16;
var minSpeed:int = 2;
var i:int = 0;
while (i < stars)
{
var mc = new Star();
addChild(mc)
mc._x = Math.random()(stage.stageWidth);
mc._y = Math.random()(stage.stageHeight);
mc.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
var size = Math.random()(2) + 6.000000E-001 * Math.random()(4);
mc._width = size;
mc._height = size;
++i;
} // end while
}
addEventListener(Event.ENTER_FRAME, update);
function update(_e:Event):void
{
for (var _loc3 = 0; _loc3 < 100; ++_loc3)
{
var _loc2 = this["star" + _loc3];
if (_loc2._y > 0)
{
_loc2._y = _loc2._y - _loc2.speed;
continue;
} // end if
_loc2._y = stage.stageHeight;
_loc2.speed = Math.random()(maxSpeed - minSpeed) + minSpeed;
_loc2._x = Math.random()(stage.stageWidth);
} // end of for
};
the error message I'm getting is: "TypeError: Error #1010: A term is undefined and has no properties. at _fla::MainTimeline/update()"
I understand it has a problem with the 'update' function but I'm net sure which term it refer to?
I'll bet a can of juice here is your problem:
var _loc2 = this["star" + _loc3];
put these into an associative array and access them from there.
#Discipol is right.
Just wanted to add a few more notes:
You can also use the display list to get the movie clip by name:
var _loc2:MovieClip = MovieClip(getChildByName("star" + _loc3));
You've got untyped variables and your are relying on MovieClip as a dynamic class to add properties (such as speed) at runtime. For a really simple project the impact is barely noticeable, but on the long run, for bigger projects, it's worth extending Sprite if you don't use the timeline and add the properties you need:
package {
import flash.display.Sprite;
import flash.events.Event;
public class Star extends Sprite {
private var speed:Number;
private var minSpeed:Number;
private var maxSpeed:Number;
public function Star(min:Number,max:Number) {
minSpeed = min;
maxSpeed = max;
var size = (Math.random()*2) + 1.82211880039 * (Math.random()*4);
width = size;
height = size;
this.addEventListener(Event.ADDED_TO_STAGE,reset);
}
private function reset(e:Event = null):void{
speed = (Math.random() * (maxSpeed-minSpeed)) + minSpeed;
x = Math.random() * stage.stageWidth;
if(e != null) y = Math.random() * stage.stageHeight;//initialized from added to stage event
else y = stage.stageHeight;//otherwise reset while updating
}
public function update():void{
if (y > 0) y -= speed;
else reset();
}
}
}
and the rest of the code would be as simple as:
var stars:int = 100;
var starClips:Vector.<Star> = new Vector.<Star>(stars,true);//a typed fixed vector is faster than a dynamically resizable untyped Array
for(var i:int = 0 ; i < stars; i++) starClips[i] = addChild(new Star(16,2)) as Star;
this.addEventListener(Event.ENTER_FRAME,updateStars);
function updateStars(e:Event):void{
for(var i:int = 0 ; i < stars; i++) starClips[i].update();
}

Flash only removing objects not created through code

I'm trying to make a simple game in Flash. So far, I've added a bunch of objects to the stage using addChild(objName);. However, now I'm trying to remove the objects completely. I don't want to have to cycle through every object's name and I'm sure there must be a more efficient way to select each object (maybe by index on the stage) and removeChildAt(index); it. However, when I try this, Flash only removes the objects that were manually placed by me on the stage. It doesn't remove the ones that were placed through code. I've done some searching and I tried multiple methods, all of which yield the same result. The one that most people agree on is this one:
while (numChildren > 0)
{
removeChildAt(0);
}
Can you help me figure out why this isn't removing anything that was coded onto the stage?
Thanks in advance :D
Edit: Here is my code for the frames:
Frame 1 (Randomly generates and displays the dots):
import flash.events.MouseEvent;
import fl.motion.easing.Linear;
var dotList = new Array(); var level:int = 3; var invisoDotList = new Array();
var loop:int;
var line:Line = new Line();
line.x = 274;
line.y = 187;
addChild(line);
for(loop = 0; loop < level; loop++)
{
var dot:Dot = new Dot();
var invisoDot:InvisoDot = new InvisoDot();
var tester:Boolean = true;
var xval:int = Math.floor(Math.random()*(1+520))+14;
var looper:int = 0;
while(looper < dotList.length)
{
if(Math.abs(xval - dotList[looper].x) > 30)//minimum spacing
{
looper++;
}
else
{
looper = 0;
xval = Math.floor(Math.random()*(1+520))+14;
}
}
dot.x = xval;
dot.y = 187;
invisoDot.x = xval;
invisoDot.y = 187;
invisoDot.alpha = 0;
dotList[loop] = dot;
invisoDotList[loop] = invisoDot;
addChild(invisoDot);
addChild(dot);
}
//trace(dotList); test to ensure that dots are added to the array
var nb1:NextButton = new NextButton();
nb1.x = 0;
nb1.y = 0;
nb1.alpha = 0;
addChild(nb1);
nb1.addEventListener(MouseEvent.CLICK, hideDots);
function hideDots(e:MouseEvent)
{
for(var loop:int = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
line.alpha = 0;
nextFrame();
}
stop();
Frame 2 (Displays further instructions and contains a couple of methods that will be used later on):
import flash.events.MouseEvent;
removeChild(nb1);
var nb2:NextButton = new NextButton();
nb2.x = 0;
nb2.y = 0;
nb2.alpha = 0;
addChild(nb2);
nb2.addEventListener(MouseEvent.CLICK, next);
function next(e:MouseEvent)
{
nextFrame();
}
function clearStage()
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
stop();
Frame 3 (Makes the dots disappear when they are clicked and keeps an accuracy count):
import flash.events.MouseEvent;
import flash.utils.Timer;
line.alpha = 1;
removeChild(nb2);
//setChildIndex(line,0);
var clicks:int = -1;
var passed:int = 0;
var fromLine:Boolean = false;
//trace(dotList.length);
stage.addEventListener(MouseEvent.CLICK, clickCount);
for(var loopvar:int = 0; loopvar < dotList.length; loopvar++)
{
//trace("loop");
dot = dotList[loopvar];
invisoDot = invisoDotList[loopvar];
dot.addEventListener(MouseEvent.CLICK, onClick);
invisoDot.addEventListener(MouseEvent.CLICK, onClick);
//trace("event");
}
//trace(dotList.length);
function onClick(e:MouseEvent)
{
//e.currentTarget.alpha = .5;
for(var hitcheck:int = 0; hitcheck < dotList.length; hitcheck++)
{
if(dotList[hitcheck].x == e.currentTarget.x)
{
dotList[hitcheck].alpha = 1;
}
}
//trace("check");
}
var numChanged:int = 0;
function clickCount(e:MouseEvent)
{
clicks++;
//trace(clicks);
numChanged = 0;
for(var index:int = 0; index < dotList.length; index++)//check whether the user has gotten all the dots
{
if(dotList[index].alpha == 1)
{
numChanged++;
}
}
if(numChanged == level)//if the user has gotten all the dots
{
/*trace("next screen for sucess");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
if((clicks - level) == 1)
{
passed = 2
}
else if((clicks - level) == 0)
{
passed = 1;
}
passed = 1;
fromLine = true;
nextFrame();
}
else if((clicks - numChanged) >= 2)//this ends the session as soon as 2 mistakes are made
{
/*trace("next screen for failed number of clicks");
trace(clicks);*/
line.visible = false;
for(loop = 0; loop < dotList.length; loop++)
{
dotList[loop].alpha = 0;//make dots disappear
}
passed = 3;
fromLine = true;
nextFrame();
}
/*else if((clicks - level) >= 2)//if the user has made too many mistakes. This ends the session after the maximum number of tries have been used
{
trace("next screen too many clicks");
trace(clicks);
}*/
}
//trace("end");
stop();
Frame 4 (Generates the results table. A sidenote: there is a bug where "Okay" is never a result because in Frame 3, the value of passed never equals 2. Not sure why though):
import flash.text.TextFormat;
import flash.text.TextField;
var failFormat:TextFormat = new TextFormat();
failFormat.color = 0xFF0000;
failFormat.font = "Arial";
failFormat.size = 18;
var passFormat:TextFormat = new TextFormat();
passFormat.color = 0x00FF00;
passFormat.font = "Arial";
passFormat.size = 18;
var okayFormat:TextFormat = new TextFormat();
okayFormat.color = 0x808000;
okayFormat.font = "Arial";
okayFormat.size = 18;
var normalFormat:TextFormat = new TextFormat();
normalFormat.color = 0x000000;
normalFormat.font = "Arial";
normalFormat.size = 18;
var lineResults = new Array();
var squareResults = new Array();
trace(passed);
if(fromLine == true)
{
if(passed == 1)
{
lineResults[lineResults.length] = "Pass";
}
else if(passed == 2)
{
lineResults[lineResults.length] = "Okay";
}
else if(passed == 3)
{
lineResults[lineResults.length] = "Fail";
}
}
fromLine = false;
lineResults = lineResults.reverse();
squareResults = squareResults.reverse();
var loopLength:int = (lineResults.length >= squareResults.length) ? lineResults.length : squareResults.length;
var loopStart:int = 0;
if(loopLength > 11)
{
loopStart = loopLength - 12
}
var cb:CellBlock = new CellBlock();
cb.x = 283.05;
cb.y = 20.35;
addChild(cb);
var col1Head:TextField = new TextField();
col1Head.defaultTextFormat = normalFormat;
col1Head.text = "# of Dots";
col1Head.x = 114.95
col1Head.y = 8.3;
addChild(col1Head);
var col2Head:TextField = new TextField();
col2Head.defaultTextFormat = normalFormat;
col2Head.text = "Line";
col2Head.x = 259.95
col2Head.y = 8.3;
addChild(col2Head);
var col3Head:TextField = new TextField();
col3Head.defaultTextFormat = normalFormat;
col3Head.text = "Square";
col3Head.x = 381.95
col3Head.y = 8.3;
addChild(col3Head);
for(loop = loopStart; loop < loopLength; loop++)
{
var block:CellBlock = new CellBlock();
block.x = 283.05;
block.y = 20.35 + (loop - loopStart + 1)*33;
addChild(block);
var col2:TextField = new TextField();
var col3:TextField = new TextField();
var col1:TextField = new TextField();
/*col2.defaultTextFormat = passFormat;
col3.defaultTextFormat = okayFormat;*/
col1.defaultTextFormat = normalFormat;
switch(lineResults[loop])
{
case "Pass":
col2.defaultTextFormat = passFormat;
break;
case "Okay":
col2.defaultTextFormat = okayFormat;
break;
case "Fail":
col2.defaultTextFormat = failFormat;
break;
}
switch(squareResults[loop])
{
case "Pass":
col3.defaultTextFormat = passFormat;
break;
case "Okay":
col3.defaultTextFormat = okayFormat;
break;
case "Fail":
col3.defaultTextFormat = failFormat;
break;
}
//col2.text = "Pass";
col2.text = lineResults[loop];
col2.x = 260.95;
col2.y = block.y - 12;
addChild(col2);
//col3.text = "Okay";
try
{
col3.text = squareResults[loop];
}
catch(e:Error)
{
}
col3.x = 386.95;
col3.y = block.y - 12;
addChild(col3);
col1.text = String(loop + 1);
col1.x = 133.95;
col1.y = block.y - 12;
addChild(col1);
}
var nb4:NextButton = new NextButton();
nb4.x = 0;
nb4.y = 0;
nb4.alpha = 0;
addChild(nb4);
nb4.addEventListener(MouseEvent.CLICK, clearStage);
stop();
Frame 5 (Next frame which is a test to make sure that everything gets erased, which it doesn't):
removeChild(nb4);
stop();
This error:
ArgumentError: Error #1063: Argument count mismatch on Game_fla::MainTimeline/clearStage(). Expected 0, got 1. clearStage()
Occurs because your clearStage() method has been added as the click event handler of a button. If your clearStage() function is going to be used an an event handler, it needs to accept an "event" parameter. So you should define the function like this:
function clearStage(event:Event)
{
while (numChildren > 0)
{
trace("before" + numChildren);
removeChildAt(0);
trace("after" + numChildren);
}
}
As a side note, this means that if you want to also call clearStage() manually, that is use it without adding it as an event handler, that you'll need to include this event parameter... but you can just pass in a null, because your code doesn't need to actually use the event parameter:
clearStage(null);
I'm not sure I see anything else wrong. I'd start by adding that event parameter to your clearStage() function as I shown above.
I should also add I mostly worked in Flex or pure AS3, and am not super skilled in Flash CS6 and programming on the timeline :)
From memory, I don't think Flash re-orders when you remove a child. If you remove a child at index 0, every other child is still numbered 1 to x. childAt(0) is just null now. Keep that in mind with this sort of process.

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;