Golf Scores Array - Actionscript 3.0 - arrays

I am making a program which has the user enter a golf score which then stores it in an array. However, the user can only enter up to 18 scores and I have attempted to code a prompt which indicates the number of scores that are in the array/they have entered. The label is called lblPrompt1 and it does not function. I also want to disable the addscore button when the user has entered all 18 scores. The prompt does not function. Please advise. Thanks!
// Purpose: To add golf scores to an array
// This line makes the button, btnAddScore wait for a mouse click
// When the button is clicked, the addName function is called
btnAddScore.addEventListener(MouseEvent.CLICK, addScore);
// This line makes the button, btnDisplayScores wait for a mouse click
// When the button is clicked, the displayScores function is called
btnDisplayScores.addEventListener(MouseEvent.CLICK, displayScores);
// declare the global variables
var scores: Array = new Array(); // array of golf scores
// This is the addName function
// e:MouseEvent is the click event experienced by the button
// void indicates that the function does not return a value
function addScore(e: MouseEvent): void {
// declare the variables
var golfScore: String; // friend's name entered by user
// get the name from the user
golfScore = txtinScore.text;
// append the name to the end of the array
scores.push(golfScore);
// display the length of the array in the label
lblArraySize.text = "Number of Golf Scores Entered: " + scores.length;
}
// This is the displayNames function
// e:MouseEvent is the click event experienced by the button
// void indicates that the function does not return a value
function displayScores(e: MouseEvent): void {
var holeNumber: Number;
lblScores.text = "";
for (var x = 0; x < scores.length; x++) {
lblScores.text += scores[x] + "\r";
}
holeNumber++;
if (holeNumber <= 18) {
lblPrompt1.text = "Enter the score for hole #" + holeNumber.toString() + ":";
} else {
lblPrompt1.text = "All scores are entered.";
txtinScore.text = "";
btnAddScore.enabled = false;
}
}

While it's not very clear what you are asking, one issue you have is that your holeNumber variable will never have a numeric value - it will always be NaN (Not A Number).
Whenever the display scores button is clicked, inside the click handler function (displayScores), you create this variable (holeNumber) and you don't give it a value. Numbers default to NaN, so later when you increment it with holeNumber++, you'll just end up with NaN still (because NaN plus 1 is still NaN).
The other part of that issue, is you create the variable in the scope of the click handler, and only increment it once, so even if you changed the var definition to var holeNumber:Number = 0;, it would still have a value of 1 every time you clicked because every click the variable get's recreated and then incremented by 1.
What you probably want to do, is forgo the holeNumber var altogether and just reference scores.length as that is essentially the current hole.
function displayScores(e: MouseEvent): void {
lblScores.text = "";
for (var x = 0; x < scores.length; x++) {
lblScores.text += scores[x] + "\r";
}
//use scores.length instead of holeNumber
if (scores.length < 18) {
lblPrompt1.text = "Enter the score for hole #" + String(scores.length + 1) + ":";
//adding 1 to the length because that would be the next hole number
} else {
lblPrompt1.text = "All scores are entered.";
txtinScore.text = "";
btnAddScore.enabled = false;
}
}

Related

Retrieving datas within an Array

This is probably easy but I just cannot get the answer. Here is a simple Array:
I want the information to be distributed from an Input textBox to different dynamic textBox after a click. I am OK with buttons.
var ERLQ1:Array = ["ERLQ1", "N09°02.61 / E100°49.11", "ErawanLq"];
InputText = "ERLQ1";
//I want to display:
Txt1 = "ERLQ1" //Being first part of the array as main reference.
Txt2 = "N09°02.61 / E100°49.11" // Should be: String(ERLQ1[1])
Txt3 = "ErawanLq" // Should be: String(ERLQ1[2])
First time I write in a forum like this. Please forgive if not perfect. Thanks in advance.
Andre
If I understand correctly, an array of objects would work well. Since you have a set number of textfields I assume that you also have a set number of details that you want to display in them. If that is the case, this solution should work fine.
arr:Array = [{_name:"ERLQ1",ans1:"N09°02.61 / E100°49.11",ans2:"ErawanLq"},
{_name:"ERLQ2",ans1:"question 2 answer 1",ans2:"ques2ans1"}];
So, I don't really "get" your application, but if it were some sort of a quiz, you'd have a new array element for each question, and that element has a name, and two answers. Easy to modify it to grab answers from an answer pool. Now to find the element in the array that has ._name == "ERLQ1" you will need to loop through all the elements and return the one that has the ._name property that matches your search. Here is an example function:
private function matchName(arr:Array, term:String):int{
for (var i:int = 0; i < arr.length; i++){
if (arr[i]._name == term){
return i;
}
}
return -1;
}
This function will return the array index number of the matching term. If no match exists, it returns -1. So you could use it like this (pseudocode):
// on submit search{
// find the index number in the array of the element that matches the search term
var ind:int = matchName(arr, searchTerm);
// assign the textfield texts to the corresponding associated values
textBox1:text = arr[ind]._name;
textBox2:text = arr[ind].ans1;
textBox3:text = arr[ind].ans2;
}
I perhaps misunderstood (because of my English), but :
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
var ERLQ1:Array = ["ERLQ1", "N09°02.61 / E100°49.11", "ErawanLq"];
var Txt1 : TextField = new TextField();
Txt1.autoSize=TextFieldAutoSize.CENTER;
Txt1.type = TextFieldType.INPUT;
Txt1.border = true;
var Txt2 : TextField = new TextField();
Txt2.autoSize=TextFieldAutoSize.CENTER;
Txt2.type = TextFieldType.INPUT;
Txt2.border = true;
var Txt3 : TextField = new TextField();
Txt3.autoSize=TextFieldAutoSize.CENTER;
Txt3.type = TextFieldType.INPUT;
Txt3.border = true;
addChild(Txt1);
addChild(Txt2);
addChild(Txt3);
Txt1.x = 20, y =40;
Txt2.x = 180, y =40;
Txt1.x = 300, y =40;
Txt1.text = ERLQ1[0]; // is now : first part of the array as main reference (String(ERLQ1[0]).
Txt2.text = ERLQ1[1]; // is now : String(ERLQ1[1]);
Txt3.text = ERLQ1[2]; // is now : String(ERLQ1[2]);
This will display 3 TextFiels as input text like this :
If I misunderstood your question, please tell me more about what You expect!
Best regards.
Nicolas

Array not resetting in Game

Hey guys so i am developing a Game and i have an Array that keeps track of my 5 movie clips that are added to the stage by the array. I have a Player movie clip as well so the Player movie clip is Hittesting with all the 5 diamond movie clips which are added to the stage like so:
private var nPoints:Number = 5;..........
public function addPointsToStage():void
{
for (var i = 0; i < nPoints; i++)
{
trace(aPointsArray.length);
points = new mcGainPoints();
stage.addChild(points);
points.x = startPoint.x + (xSpacing * i);
points.y = startPoint.y - (ySpacing * i);
aPointsArray.push(points);
}
}
Now when the Player comes in contact with all the 5 movie clips everything works fine and the output for the array looks like this:
0
1
2
3
4
Then it continues to the next level.
But say that my Player doesnt hit any of the 5 movie clips or only hits a couple of them, when the next level is started the output looks like this:
5
6
7
8
9
and when the next level is started weird things start happening like points start adding to the highscore by themselves.
I think the problem is that im not destroying the array holding the 5 movie clips correctly this is the code i use to start the next level and destroy the array:
if(player.hitTestObject(mcGoal_1))
{
//Remove all points from array/stage
for (var i:int = 0; i < aPointsArray.length; i++)
{
if (aPointsArray[i].parent)
{
parent.removeChild(aPointsArray[i]);
}
startNextLevel();
}
The mcGoal_1 is the object of the game so if the player hits the goal_1 then destroy all array objects on screen and start next level. This is the startnextlevel function.
private function startNextLevel():void
{
//add points to next stage
addPointsToStage();
}
So can you see why when the next level starts the array isnt reset back to 01234? I think thats why the game has that bug of randomly adding points. Please any help will be appreciated
//Remove all points from array/stage
for (var i:int = 0; i < aPointsArray.length; i++)
if (aPointsArray[i].parent)
parent.removeChild(aPointsArray[i]);
// just one statement, no braces
aPointsArray.length=0; // clear the array itself, not just
// points from display list!
startNextLevel(); // now start level
An incorrect order of correct statements leads to a disaster. Always check your code flow, what executes now and what then, and how many times.
It doesn't look like you're removing anything from the array.
You can use a combination of .indexOf() and .splice() to remove items from an array:
function removeMc(clip:MovieClip):void
{
if(clip.parent) clip.parent.removeChild(clip);
// Also remove from array.
var index:int = aPointsArray.indexOf(clip);
aPointsArray.splice(index, 1);
}
It might also be worth simply emptying the array when you startNextLevel():
private function startNextLevel():void
{
aPointsArray.length = 0;
//add points to next stage
addPointsToStage();
}
Just assign your array to null value. so that array will start from begining whenever you require. i hope the following code code would helps you.
var nPoints:Number = 5;
var points:poin;
var aPointsArray:Array;
var startPoint:Number = 0;
var xSpacing:Number = 20;
var ySpacing:Number = 20;
addPointsToStage();
function addPointsToStage():void
{
aPointsArray = null;
aPointsArray = new Array();
for (var i:int = 0; i < 6; i++)
{
trace(aPointsArray.length);
points = new poin();
addChild(points);
points.x = 100+ (xSpacing * i);
points.y = 200 - (ySpacing * i);
aPointsArray.push(points);
}
}

#1023 StackOverflow ERROR

I have problem with this array thing I am doing. U can just plug in the code and run.
I need to have 2 things display out of the same array and which ever is picked gets kickedout from the array and stashed into another one.
One of the 2 things that are displaying out is picked at random and the other one goes in order it was put in.
So the logic I applied, or tried applying and is not working very well is..
Once the 2 things display out and if u pick the index count, no numbers change since the index count becomes subtracted by one, so the object after it gets pushed up.
but if the random choice is picked the index count moves up by one since it needs to keep moving...
The error i get is this:
TypeError: Error #2007: Parameter child must be non-null.
at flash.display::DisplayObjectContainer/addChild()
at Level3Torture_fla::MainTimeline/civilizedorder()[Level3Torture_fla.MainTimeline::frame1:87]
at Level3Torture_fla::MainTimeline/goNext()[Level3Torture_fla.MainTimeline::frame1:114]
at Level3Torture_fla::MainTimeline/switchpic()[Level3Torture_fla.MainTimeline::frame1:79]
This is the Code:
import flash.sampler.NewObjectSample;
import flash.display.Sprite;
import flash.events.MouseEvent;
var eating_breakfast:Sprite;
var walking:Sprite;
var swimming:Sprite;
var art:Sprite;
var choices:Array = new Array ();
//Sprite Creation
eating_breakfast = new Sprite ();
eating_breakfast.graphics.beginFill(0xE39D43);
eating_breakfast.graphics.drawRect(0,0,50,50);
eating_breakfast.graphics.endFill();
eating_breakfast.x = 50;
eating_breakfast.y = 50;
walking = new Sprite ();
walking.graphics.beginFill(0xC3266C);
walking.graphics.drawRect(0,0,50,50);
walking.graphics.endFill();
walking.x = 100;
walking.y = 100;
swimming = new Sprite ();
swimming.graphics.beginFill(0x48AFD1);
swimming.graphics.drawRect(0,0,50,50);
swimming.graphics.endFill();
swimming.x = 150;
swimming.y = 150;
art = new Sprite ();
art.graphics.beginFill(0xafdb44);
art.graphics.drawRect(0,0,50,50);
art.graphics.endFill();
art.x = 200;
art.y = 200;
//adding sprites into array
choices.push( eating_breakfast);
choices.push(walking);
choices.push(swimming);
choices.push(art);
var indexcount = 0;
var randomize:Number;
var storageArray: Array = new Array ();
civilizedorder();
randomizedorder();
this.addEventListener(MouseEvent.CLICK,switchpic);
//pick the target generated object
function switchpic(t:MouseEvent)
{
//for index count
if (t.target == choices[indexcount])
{
storageArray.push(choices[indexcount]);
removeChild(choices [indexcount]);
removeChild(choices [randomize]);
choices.splice(indexcount,1);
goNext();
};
// for randomize
if (t.target == choices[randomize])
{
storageArray.push(choices[randomize]);
removeChild(choices [indexcount]);
removeChild(choices [randomize]);
choices.splice(randomize,1);
indexcount++;
trace("The Index count is" + indexcount);
goNext();
}
}
//generates the index count object
function civilizedorder()
{
addChild(choices [indexcount]);
choices[indexcount].x = 300;
}
trace("The number of choices in the choice array is " + choices.length);
//generates the randomized object
function randomizedorder()
{
randomize = Math.floor(Math.random() * choices.length);
trace("the random number is" + randomize);
if (randomize == indexcount )
{
randomizedorder();
}
else
{
addChild(choices [randomize]);
}
}
//EDIT
function goNext()
{
trace("The storagearray has " + (storageArray.length));
if (choices.length < 0 || choices.length > 0)
{
if (indexcount > choices.length-1)
{
indexcount = choices.length - 1;
}
civilizedorder();
randomizedorder();
}
}
It is giving me a new error now. It's called StackOverflow. I am not entirely sure what is going wrong now.
EDIT: To add a conditional and check if you will be out of bounds for adding a child in this array, try this:
if(indexcount <= choices.length){
addChild(choices [indexcount]);
}
Try commenting out the splicing in the switchpic() method. That or re-add those values/sprite instances to the array.
I think that you've sliced from the "choices" array twice in the switchpic() method, and never actually add to the array ever again. So you'll eventually end up with an empty choices array. Hence the error.
In the second conditional, if (t.target == choices[randomize]), you increment indexcount, and then call goNext() which regenerates the randomize value to not equal the indexcount, but also tries to re-add a child sprite.
This could cause an array of 4 items to become 2 items, and then, possibly, randomize = 0, indexcount = 1. In the second pass, you might have an array of 0 items, with randomize = 0, indexcount = 1 and the error to occur.
Here's the flow, I imagine:
It looks like you're clicking on an instance of a sprite.
Then it calls switchpic(), which executes:
...
choices.splice(indexcount,1);
...
and then goNext()
which calls civilizedorder()
which executes:
...
addChild(choices [indexcount]);
...
you should check indexcount is never outside of 0-3 range.
in function goNext(), change the code as follows:
function goNext()
{
trace("The storagearray has " + (storageArray.length));
if(choices.length <> 0)
{
if(indexcount > choices.length-1)
indexcount = choices.length-1;
civilizedorder();
randomizedorder();
}
}

hitTestObject not hitTesting with all MovieClips

Hey guys having a little trouble this might be easier than i am making it out to be.
But the problem that i am having is when i hittest my mcPoints with my mcPlayer it is only interacting with 4 out of 5 of the movie clips that are added to the stage by a for loop.
I have been struggling with this for the past two days and cant seem to pin point the problem, everything seems set up perfectly but maybe you can help.
These are my Variables:
public var mcPoints:smallGainPoints;
private var nPoints:Number = 5;
private var aPointsArray:Array;
Here is how i set up the 5 mcPoints Movie Clips to be added to stage:
private function addPointsToStage():void
{
var startPoint:Point = new Point((stage.stageWidth / 2) - 100, stage.stageHeight / 2);
var spacing:Number = 50;
for (var i = 0; i < nPoints; i++)
{
trace(aPointsArray.length);
mcPoints = new smallGainPoints();
aPointsArray.push(mcPoints);
stage.addChild(mcPoints);
mcPoints.x = startPoint.x + (spacing * i);
mcPoints.y = startPoint.y;
}
}
So that adds the 5 points movie Clips to the stage which are aligned horizontally.
And finally here is the loop that listens for the HitTestObject to Initiate:
private function checkPlayerHitPoints():void
{
for (var i:int = 0; i < aPointsArray.length; i++)
{
//get current point in i loop
var currentPoints:smallGainPoints = aPointsArray[i];
//test if player is hitting current point
if(player.hitTestObject(currentPoints))
{
//Add points sound effects
var pointsSound:Sound = new pointsPickUpSound();
pointsSound.play();
//remove point on stage
currentPoints.destroyPoints()
//remove points from array
aPointsArray.splice(i, 1);
trace(aPointsArray.length);
//Add plus 5 text to current points position
mcPlus5 = new plusFiveText();
stage.addChild(mcPlus5);
mcPlus5.x = (currentPoints.x);
mcPlus5.y = (currentPoints.y);
//Update high score text
nScore += 5;
updateHighScore();
}
}
}
So i added traces both for when the movie clips are added and when they are hit here are the values i get:
0
1
2
3
4
Hit: 4
Hit: 3
Hit: 2
Hit: 1
Also i call the addPointsToStage(); in my constructor for more information.
So from the values im getting it seems that the last value "0" isn't being interacted with, any ideas why? Please anything would be of use. Thanks so much!
i'm not exactly sure what your code is suppose to be doing. But when you remove element from array in loop you are lose one item.
You array is
[1][2][3][4][5]
When i=1 you remove element and get
[1][3][4][5]
next interation i=2 which means you never test agains value 3.
You should decrement i whenever you remove element from an array.

How do i set the minimum value to 70 and how can i stop people inputting letters and symbols. And how do i get the running total to add up?

Running Total
function CalculateTotal()
{
var intCalculateTotal = 0;
var intMinValue = 70;
var intInput;
var boolMoreNumbers = true;
var boolCorrectInput = true;
for (var intCount= 70; intCount<=15; intCount++)
{
intInput=parseInt(prompt("Please Enter a number higher than 70", ""));
if (i <=70)
{
alert ("Minimum number needs to be 70");
}
if (intInput > intMinValue)
{
intCalculateTotal = intCalculateTotal + intMinValue;
}
}
alert("The running Total is " + intCalculateTotal);
}
Calculate Running Total
You can't stop people from putting in letters and symbols... but you can look for them with a regex and put up another alert. Alternatively you can just ignore them - your parseInt will just ignore non-digits and give you the digit-part of the input as though they weren't there.
You code already only adds the int if it's > 70, though you're not alerting the user of this, because instead your code checks that the loop variable is > 70. If you'd like to alert the user, you'd need:
if (intInput <=70)
{
alert ("Minimum number needs to be 70");
}

Resources