Actionscript 3, Flash CC: Placing Objects In An Array From The Library Onto The Stage - arrays

Hello programming gurus of stackoverflow, I am hoping that at least one of you will be able to help me with my coding problem. This is the first time I'm posting on this site, so if I miss something with the structure of my post, or anything please let me know (preferably not in a condescending matter) and I will gladly change it.
I actually had a different problem I was going to ask about, but I recently realized that some objects from my library weren't showing up on my stage. Hopefully, if this gets solved I won't have my other problem.
I am creating a learning module app using Flash CC and Actionscript 3, I like to think I am fairly proficient with Flash, but right now all my code is on the timeline because when I started I wasn't aware of the package setup. When I finish with the learning module I'll try and move everything to an AS package, so please bear with me.
This current frame of the module is a drag and drop game where the user drags the correct food, for the animal they chose in the previous frame, to the animal in the middle. The animal is dynamically placed on the stage, as well as an array of six possible food choices, all MovieClips pulled from the library. The array of food elements is actually not what I'm having problem with, they appear on my stage with no problems at all. The problem I'm having is when the user drags the correct food onto the animal, and the win condition is met, the array of balloon elements does not show up on the stage. I find it weird because I'm using near identical code for both the food and balloon array.
Here is my full code:
import flash.display.MovieClip;
import flash.events.MouseEvent;
foodPet();
function foodPet():void {
//all of my pet, food, and balloon library objects have been exported for AS
var theBird:pet_bird = new pet_bird;
var theCat:pet_cat = new pet_cat;
var theChicken:pet_chicken = new pet_chicken;
var theDog:pet_dog = new pet_dog;
var theDuck:pet_duck = new pet_duck;
var theGuinea:pet_guinea = new pet_guinea;
var theHamster:pet_hamster = new pet_hamster;
var birdSeed:food_bird_seed = new food_bird_seed;
var catFood:food_cat_food = new food_cat_food;
var chickenFeed:food_chicken_feed = new food_chicken_feed;
var chocolate:food_chocolate = new food_chocolate;
var dogFood:food_dog_food = new food_dog_food;
var duckFood:food_duck_food = new food_duck_food;
var animalList:Array = [theBird, theCat, theChicken, theDog,
theDuck, theGuinea, theHamster];
var food1Array:Array = [birdSeed, catFood, chickenFeed,
chocolate, dogFood, duckFood, 4];
var xPosFood:Array = new Array();
var yPosFood:Array = new Array();
xPosFood = [32, 71, 146, 363, 431, 512];
yPosFood = [304, 222, 123, 123, 222, 304];
var animalClip:MovieClip;
animalClip = animalList[chosenAnimal];
addChild(animalClip);
animalClip.x = 256;
animalClip.y = 287;
animalClip.name = "selectedAnimal";
for (var i:uint = 0; i < food1Array.length - 1; i++){ //Where the food gets added
var isItRight:Boolean = false;
var foodName:String = ("food" + i);
var foodClip:MovieClip;
foodClip = food1Array[i];
foodClip.x = xPosFood[i];
foodClip.y = yPosFood[i];
foodClip.name = foodName;
addChild(foodClip);
trace(foodClip.parent);
foodDragSetup(foodClip, animalClip, food1Array[food1Array.length - 1], isItRight);
}
}
function foodDragSetup(clip:MovieClip, targ:MovieClip, correctNum:uint, isItRight:Boolean) {
var beingDragged:Boolean = false;
var xPos:Number = clip.x;
var yPos:Number = clip.y;
clip.addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
function beginDrag(event:MouseEvent):void
{
clip.startDrag();
if (int(clip.name.substr(4)) == correctNum){
isItRight = true;
}
this.beingDragged = true;
setChildIndex(clip, numChildren - 1);
clip.addEventListener(MouseEvent.MOUSE_UP, endDrag);
}
function endDrag(event:MouseEvent):void
{
if (this.beingDragged) {
this.beingDragged = false;
clip.stopDrag();
if ((isItRight) && (clip.hitTestPoint(targ.x, targ.y, true))){
trace(targ.name + " has been hit.");
clip.x = targ.x;
clip.y = targ.y;
win_animal_food();
} else {
isItRight = false;
clip.x = xPos;
clip.y = yPos;
}
}
}
}
function win_animal_food():void {
const BALLOON_ROW:int = 4;
var count:uint = 0;
var altX:uint = 0;
var bBalloon:blue_balloon = new blue_balloon;
var gBalloon:green_balloon = new green_balloon;
var oBalloon:orange_balloon = new orange_balloon;
var pBalloon:purple_balloon = new purple_balloon;
var rBalloon:red_balloon = new red_balloon;
var yBalloon:yellow_balloon = new yellow_balloon;
var balloonList:Array = [bBalloon, gBalloon, oBalloon,
pBalloon, rBalloon, yBalloon, bBalloon, gBalloon,
oBalloon, pBalloon, rBalloon, yBalloon, bBalloon,
gBalloon, oBalloon, pBalloon];
var balloonY:Array = [144, -205, -265, -325];
var balloonX:Array = [0, 140, 284, 428, 68, 212, 356, 500];
for (var ballY:uint = 0; ballY < balloonY.length; ballY++){ //Where balloons
for (var ballX:uint = altX; ballX < altX + BALLOON_ROW; ballX++){ //get added
var balloonName:String = ("balloon" + count);
var balloonClip:MovieClip;
balloonClip = balloonList[count];
balloonClip.x = balloonX[ballX];
balloonClip.y = balloonY[ballY];
balloonClip.name = balloonName;
addChild(balloonClip);
trace(balloonClip.parent);
trace(balloonClip + " has been added!");
balloonClip.addEventListener(MouseEvent.CLICK, balloonPop);
count++;
}
if (altX == 0) {
altX = BALLOON_ROW;
} else {
altX = 0;
}
}
function balloonPop(event:MouseEvent):void {
event.target.play();
event.target.removeEventListener(MouseEvent.CLICK, balloonPop);
}
}
I thought there might have been a problem with my balloon MovieClips, so I subbed them in the food array:
var birdSeed:blue_balloon = new blue_balloon;
var catFood:green_balloon = new green_balloon;
var chickenFeed:orange_balloon = new orange_balloon;
var chocolate:purple_balloon = new purple_balloon;
var dogFood:red_balloon = new red_balloon;
var duckFood:yellow_balloon = new yellow_balloon;
They all showed up on the stage, so there's nothing wrong with the MovieClips.
Added: The first values of balloonXArray and balloonYArray were originally -4 and -145 respectively, but when I started having problems I wanted to make sure the balloons were showing up so I set the first values to 0 and 144 the balloon height and width are both 144 and their cross (not sure on it's name) is in the top left corner.
Added: The reason why there are multiple instances of the same balloon in the balloonList is because I need four rows of four balloons, but only have six different balloons.
I know the balloons are on the stage because the debug display shows their x and y values on the viewable stage. Using trace(foodClip.parent) and trace(balloonClip.parent) shows that the balloons and food all have the same parent, MainTimeline, so I know the balloons aren't getting added to some different space.
I have searched online, but have not come across anyone with a similar problem. Thus, I am asking on this forum if anyone can tell me why my balloons will not show up on the stage.
Please and thank you.

One thing I see straight off in the baloonList is that you have the same object instances listed multiple times. Each instance can only exist on stage exactly once. If you addChild() an instance that is already on stage, the instance is first removed, then re-added at the top of the display list.
You should change:
var bBalloon:blue_balloon = new blue_balloon;
var gBalloon:green_balloon = new green_balloon;
var oBalloon:orange_balloon = new orange_balloon;
var pBalloon:purple_balloon = new purple_balloon;
var rBalloon:red_balloon = new red_balloon;
var yBalloon:yellow_balloon = new yellow_balloon;
var balloonList:Array = [bBalloon, gBalloon, oBalloon,
pBalloon, rBalloon, yBalloon, bBalloon, gBalloon,
oBalloon, pBalloon, rBalloon, yBalloon, bBalloon,
gBalloon, oBalloon, pBalloon];
to:
var balloonList:Array = [
new blue_balloon,
new green_balloon,
new orange_balloon,
new purple_balloon,
new red_balloon,
new yellow_balloon,
new blue_balloon,
new green_balloon,
new orange_balloon,
new purple_balloon,
new red_balloon,
new yellow_balloon,
new blue_balloon,
new blue_balloon,
new green_balloon,
new orange_balloon,
new purple_balloon
];

Related

Pushing Distinct Values to Array and Finding New Length

Trying to sort and push only the distinct values into a new array and then find the length of the resulting array. See code below. The UniqueTeams.length is coming out to be 1, when it should be 5 (I thought).
var teams = [[formSS.getRange("F8").getValue(),
formSS.getRange("F10").getValue(),
formSS.getRange("F12").getValue(),
formSS.getRange("F14").getValue(),
formSS.getRange("F16").getValue()]];
var uniqueTeams = removeDups(teams);
if(uniqueTeams.length < 5){
{SpreadsheetApp.getUi().alert(uniqueTeams);
return;}
}
function removeDups(array) {
var outArray = [];
array.sort();
outArray.push(array[0]);
for(var n in array){
if(outArray[outArray.length-1]!=array[n]){
outArray.push(array[n]);
}
}
return outArray;
}
uniqueTeams = Alabama (2),Maryland (10),Cleveland St (15),BYU (6),Liberty (13)
uniqueTeams.length = 1
Get unique elements
function remdup() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getActiveSheet();
const t = sh.getRange('F8:F16').getValues().flat();
let teams = [t[0], t[2], t[4], t[6], t[8]];
let s = new Set(teams)
teams = [...s];
Logger.log(teams.join(','))
}
Set
Cooper's answer it the best ultimate solution. But if you want just to fix your code you can try to change the line:
var uniqueTeams = removeDups(teams);
with:
var uniqueTeams = removeDups(teams[0]);
Since the teams is a 2D array [[...]].

Accessing Items in an Array - AS3

I've got an Object item.movieimage that contain some texts (item:Object) that is retrieve from my database. The text is changing every week automatically.
If I do trace(item.movieimage) the output is something like this :
text1
text2
text3
text4
The words changes as the code is taking them from my database. The database changes the words every week.
Now, I want my AS3 code to display the third element of item.movieimage.
I've tried to do this :
var my_str:String = item.movieimage+",";
var ary:Array = my_str.split(",");
trace(ary[2]);
But it's not working. The output is "undefined".
Do you know how can I access a specific item in the Array that I've created ? Or how can I access the third item of item.movieimage ?
If I do trace(ary);, the output is :
text1,
text2,
text3,
text4,
EDIT :
For infos :
trace(typeof(item.movieimage)) and trace(typeof(ary)) are :
typeof(item.movieimage)=string
typeof(ary)=object
EDIT 2 :
Here's a screen capture of item.movieimage
Screen Cap of item.movieimage
EDIT 3
Here's my code in order to understand how "item.movieimage"is working
//Variables for downloading content from my database to my AS3 code
var urlReqSearchAll: URLRequest = new URLRequest("http://www.myWebSite/searchMovie4.php");
var loader5:URLLoader = new URLLoader();
//downloading content
function searchAll():void {
if (contains(list)){
list.removeChildren();
}
urlReqSearchAll.method = URLRequestMethod.POST;
loader5.load(urlReqSearchAll);
loader5.addEventListener(Event.COMPLETE,complete);
var variables:URLVariables = new URLVariables();
}
//Content Downloaded.
function complete(e:Event):void {
addChild(list);
products = JSON.parse(loader5.data) as Array;
hourSaved.data.saved=loader5.data;
products.reverse();
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
displayPage(0);
showList();
}
// If too much items --> creates multiple page
const itemsPerPage:uint = 7;
var currentPageIndex:int = 0;
function displayPage(pageIndex:int):void {
list.removeChildren();
currentPageIndex = pageIndex;
var firstItemIndex:int = pageIndex * itemsPerPage;
var j:int = 0;
var lastItemIndex: int = firstItemIndex + 7; // as lastItemIndex should be 10 more
if (lastItemIndex > products.length) // if lastindex is greater than products length
lastItemIndex = products.length;
for(var i:int = firstItemIndex; i< lastItemIndex; i++){
createListItem( j, products[i]); // j control the position and i points to particular element of array..
j++;
}
next.visible = lastItemIndex < products.length - 1;
if(currentPageIndex==0){
previous.visible=false;
}
}
// Display the information downloded from my database
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
var myFormat:TextFormat = new TextFormat();
myFormat.size = item.title.length > 13 ? 22 : 26
listItem.multiline = true;
listItem.wordWrap = true;
myFormat.align = TextFormatAlign.CENTER;
myFormat.color = 0xA2947C;
myFormat.font = "Ebrima";
myFormat.bold = true;
listItem.defaultTextFormat = myFormat;
listItem.x = 135;
listItem.y = 123+ index * 84;
listItem.width = 200;
listItem.height = 80;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
str = item.title;
}
My php file "SearchMovie4.php" is like this :
$products = array();
while ($row = mysql_fetch_array($sql_result)) {
$products[] = array(
"title" => $row["theTitle"],
"movieimage" => $row["movieimage"],
"movielength" => $row["movielength"],
"story" => $row["story"],
);
}
echo json_encode($products);
So, if I do trace(item.movieimage) in AS3 code, it will display all the items in the row movieimage of my database.
If I do trace(item.title) in AS3 code, it will display all the items in the row title of my database.
What I'd like is to be able to do, in my AS3 code, trace(item.movieimage[2]) in order to show me the third item in the row "movieimage".
Well, the text you've provided to the movieimage property of the item object has not the same delimiter as what you have provided to the split() method; in your case the character of comma!
I suspect the delimiter you have, is the "space" character or a new-line character, like the character of carriage retrun.
In the following code snippet, I've used the "space" as the delimiter character:
var item:Object = new Object();
item.movieimage = "text1 text2 text3 text4";
var my_str:String = item.movieimage;
var ary:Array = my_str.split(" ");
trace(ary[2]); // text3
As #someOne said the output shows the list items are each on a new line, so you need to split() against newlines. One of these should work:
// if server uses "\n" newline char
var movies:Array = item.movieimage.split("\n");
// if server uses "\r" carriage return char
var movies:Array = item.movieimage.split("\r");
// if you aren't sure or there's a mixture of newline chars
var movies:Array = item.movieimage.split(/[\r|\n]+/);
Also note that if you have any control over how the server returns these values, you should just return a JSON array (since I see in your screenshot you are already decoding JSON), then you won't have to do any string splitting.

Cannot convert Array to Odject[][] Even though it is a 2D array

Still new and just learning how to use arrays. I am getting the error "Cannot convert Array to Object[][]. (line 46, file "Submit to Record")
Line 46 is
targetSheet.getRange(lastRow+1, 1, 1, arrayOfData.length).setValues(arrayOfData);
I had this error once before, but it was because of an array inside an array issue. Now I don't know what's wrong.
The entire code is
function submitButtonClick() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
Logger.log('sheet.getName(): ' + sheet.getName());
if (sheet.getName() !== "SubmitReceipt") {return;};
var targetSheet = ss.getSheetByName("ReceiptRecord");
var arrayOfData = [];
var week = sheet.getRange(6,9).getValue();
var emplN = sheet.getRange(4,9).getValue();
var purDate = sheet.getRange(9,9).getValue();
var purFrom = sheet.getRange(11,9).getValue();
var custC = sheet.getRange(14,9).getValue();
var deptC = sheet.getRange(16,9).getValue();
var lotC = sheet.getRange(18,9).getValue();
var laborC = sheet.getRange(20,9).getValue();
var itemC = sheet.getRange(22,9).getValue();
var hyperL = sheet.getRange(28,9).getValue();
var notes = sheet.getRange(44,8).getValue();
arrayOfData[0] = week;
arrayOfData[1] = emplN;
arrayOfData[2] = purDate;
arrayOfData[3] = purFrom;
arrayOfData[4] = custC;
arrayOfData[5] = deptC;
arrayOfData[6] = lotC;
arrayOfData[7] = laborC;
arrayOfData[8] = itemC;
arrayOfData[9] = hyperL;
arrayOfData[10] = notes;
Logger.log('arrayOfData '+ arrayOfData)
var lastRow = targetSheet.getLastRow();
Logger.log('lastRow: ' + lastRow);
Logger.log('arraylength ' + arrayOfData.length);
targetSheet.getRange(lastRow+1, 1, 1, arrayOfData.length).setValues(arrayOfData);
sheet.getRange(6,9).clearContent();
sheet.getRange(4,9).clearContent();
sheet.getRange(9,9).clearContent();
sheet.getRange(11,9).clearContent();
sheet.getRange(14,9).clearContent();
sheet.getRange(16,9).clearContent();
sheet.getRange(18,9).clearContent();
sheet.getRange(20,9).clearContent();
sheet.getRange(22,9).clearContent();
sheet.getRange(28,9).clearContent();
sheet.getRange(44,8).clearContent();
}
I know this code is clunky and could be written more efficiently and condensed, but I am writing this way on purpose because I am new to JS and this is an easy way for me to keep my head on straight about what is happening in the code. I hope my sanity efforts are not the cause of my problem. Please help. :)
Serge insas answered the question in the comments. He said:
I guess you should simply write
setValues([arrayOfData])
but I'm just guessing ;-)"
That did indeed fix the problem. Thanks, Serge insas!

Action Script 3 URLLoader in for loop

I have 7 Arrays to begin with:
private var listArray:Array = new Array();
private var oneArray:Array = new Array();
private var twoArray:Array = new Array();
private var threeArray:Array = new Array();
private var fourArray:Array = new Array();
private var fiveArray:Array = new Array();
private var sixArray:Array = new Array();
listArray contain 6 string element of text file name.
something like:
1.txt
2.txt
3.txt
4.txt
5.txt
6.txt
All other array is empty at the moment.
I have wrote a for loop like this:
for (var i:int = 0; i < listArray.length; i++)
{
var urlRequest:URLRequest = new URLRequest(File.documentsDirectory.resolvePath(listArray[i]).url);
var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
try
{
urlLoader.load(urlRequest);
}catch (error:Error){
trace("Cannot load : " + error.message);
}
}
if without for loop I know I can do this for only one array of data:
private function completeHandler(e:Event):void
{
oneArray = e.target.data.split(/\r\n/);
}
Here I am trying to get something to work like:
oneArray contain the data from 1.txt
twoArray contain the data from 2.txt
so on...
sixArray contain the data from 6.txt
problem:
I known the completeHandler function only execute after for loop looped six times.
is there anyway I could get the correct data to the correct array.
Thanks
Since you are using AIR to load data from the file-system, you don't have to do it asynchronously. You can load it synchronously like this:
function readTxtList(url:String):Array {
var file:File = File.documentsDirectory.resolvePath(url);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var text:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
fileStream.close();
return text.split("\r\n");
}
Now you can just assign each value directly:
var oneArray:Array = readTxtList("1.txt");
var twoArray:Array = readTxtList("2.txt");
// etc
I recommend you to use Dictionary.
Create new Dictionary:
var dict:Dictionary = new Dictionary();
Bind an instance of the URLLoader class to the file name:
var urlRequest:URLRequest = ...
var urlLoader:URLLoader = new URLLoader();
dict[urlLoader] = listArray[i];
In the completeHandler you can get the file name:
trace(dict[e.currentTarget]);
Add if statements to reach your goal.
if (dict[e.currentTarget] == "1.txt")
oneArray = e.target.data.split(/\r\n/);
else if (dict[e.currentTarget] == "2.txt")
twoArray = e.target.data.split(/\r\n/);
...

Can i display multiple copies of a movieclip inside a array at once

Is there a way to make the code below work properly? When I use this code it only shows one movieclip:
var tempHead:head001 = new head001();
var mcArr:Array = new Array( tempHead );
var firstHead:MovieClip = mcArr[0];
firstHead.y = 30;
addChild(firstHead);
var secondHead:MovieClip = mcArr[0];
secondHead.y = 180;
addChild(secondHead);
`
You were just assigning a reference to the MovieClip. That'y, its not working.
First take instance of head001 class using new operator as much you want and store it to an array, then you can access very easily.
var tempHead: head001;
var mcArr: Array = new Array();
for (var i: uint = 0; i < 2; i++) {
tempHead = new head001();
addChild(tempHead);
mcArr.push(tempHead);
mcArr[i].y = mcArr[i].height * i;
}

Resources