AS3 - Best method for dynamically creating a series of text fields? - arrays

I am (successfully) creating a column of boxes via a loop, the meat of which is:
for(var i=0; i < MAX_ROWS + 1; i++){
for(var o=0; o < MAX_COLS + 1; o++){
var currentTile:MemberBox = new MemberBox();
currentTile.x = i*150;
currentTile.y = o*25;
currentTile.name = "b"+o;
memberBox.addChild(currentTile);
}}
Now I need to add a textfield to each box, which will later be populated with data from an array. I tried adding each textfield to an array in the for loop and then calling from the array, but the textfields still all have the same name so only the last one called actually works...
Here is what I have - it almost does what I need, but it only adds text to the last box created.
var txtArray:Array = new Array();
for(var i=0; i < MAX_ROWS + 1; i++){
for(var o=0; o < MAX_COLS + 1; o++){
var currentTile:MemberBox = new MemberBox();
currentTile.x = i*150;
currentTile.y = o*25;
currentTile.name = "b"+o;
memberBox.addChild(currentTile);
currentTile.addChild(memberBoxText);
memberBoxText.width = 150;
memberBoxText.height = 25;
txtArray[o] = memberBoxText;
txtArray[o].text = "test"+o;
}}

Well you didn't declare anywhere memberBoxText so I asume you added it manually through flash builder. You are not making new instance of your textField.Try inserting this into for loop:
var memberTxt:TextField=new TextField(); currentTile.addChild(memberTxt);
:)

Related

Google App Script - How to set a spreadsheet file value from a string formatted through just one array

I am a beginner of programming.
The code snippet below in my GS project works very well.
var nextRow = Sheet_current.getLastRow() + 1; // Line 1
var str = "1,2,3,4,5,6";
var temp = new Array(); //Line 3
temp = str.split(",");
var target = new Array(); //Line 5
for (var i = 0; i < temp.length; i++) {
target.push([temp[i]]);
}
Sheet_current.getRange(Sheet_current.getLastRow() + 1, 1, target.length, target[0].length).setValues(target); //Line 9
Results in my spreadsheet file when running the above code:
result
I use a string as input, then convert it into a temporary array (Line 3).
I continue to declare a target array, to pass the values of the temporary array to the target array. (Lines 5 to 7)
Finally, I use the target array to dump the values into my spreadsheet (vertically, each word in the target array corresponds to a row in the spreadsheet file) (Line 9).
Can someone help me how to optimize the code that only through just one array.
Sincerely thank.
If you just want to provide result on differents row and starting from the first column, you can use the appendRow() method. Here is a example of use in your case:
function myFunction() {
var Sheet_current = SpreadsheetApp.getActiveSheet();
var nextRow = Sheet_current.getLastRow() + 1; // Line 1
var str = "1,2,3,4,5,6";
var target = new Array(); //Line 3
target = str.split(",");
for (var i = 0; i < target.length; i++) {
Sheet_current.appendRow([target[i]]);
}
}
Or you can just made the modification you want on your first array to keep your structure like :
function myFunction2(){
var Sheet_current = SpreadsheetApp.getActiveSheet();
var nextRow = Sheet_current.getLastRow() + 1;
var str = "1,2,3,4,5,6";
var temp = new Array();
temp = str.split(",");
for (var i = 0; i < temp.length; i++) {
temp[i] = [temp[i]]; // To convert your Array[] on Array[][]
}
Sheet_current.getRange(Sheet_current.getLastRow() + 1, 1, temp.length, temp[0].length).setValues(temp);
}
But I don't recommend this method, since it's okay for little program, but can be tricky for larger one.

Google Apps Script .setvalues For loop not working

The goal of the loop is to fill each cell over 797 rows across 5 columns A, B, C, D and E with a formula whose cell reference increments by 1.
E.g. Column A rows 6 onwards will have formula "=indirect("'Data Repository'!A3++")"
Column B rows 6 onwards will have formula "=indirect("'Data Repository'!B3++")"
What happens when I run the function however is it only fills in column A. I've checked the execution transcript and execution succeeded is logged after the first column has been filled up. I've tried various variations to no avail.
Below is the last variation I've tested:
function indirect(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Fleet - Weekly V3");
var formulaArray = [];
var columns = ["A","B","C","D","E"];
var row = 2;
var text = '=indirect(\"\'Data Repository\'!';
var headerRow = 6;
var column;
for(i = 0; i < 5; i++) {
column = parseInt(i) + 1;
formula = text + columns[i];
for(i = 0; i < 797; i++) {
row += 1;
if (formulaArray.length == 797) {
sheet.getRange(headerRow, column).offset(0, 0, formulaArray.length).setValues(formulaArray);
} else {
formulaArray.push([formula + row + '")']);
}
Logger.log(formulaArray.length);
}
Logger.log(i)
formulaArray = [];
}
}
Here is where you might be making an error - you need to create the variable i (var i = 0 instead of just i = 0) and if you're nesting loops, you need to have different variables increasing (first loop use i, then nest with j, then nest in that with k etc as needed)
for(var i = 0; i < 5; i++) {
column = parseInt(i) + 1;
formula = text + columns[i];
for(var j = 0; j < 797; j++) {
Untested but I believe it should work if you just substitute that in.
Your problem is in your loops. You are using the 'i' variable twice. Change the for loop that you have nested to iterate over the variable 'j' or something other than 'i'.

AS3 Picking a random object from an Array with certain conditions

I'm looking for the fastest way to pick a random object that has a certain condition (from an array).
In the example below I have a multidimensional array, 50 * 50 that contains objects. I want to pick a random object from that array but that object needs to have a size larger than 100.
while (object.size <= 100)
{
attempts++;
object = grid_array[Math.round(Math.random() * 49)][Math.round(Math.random() * 49)];
}
Currently I have tested this and in some instances it takes over 300+ attempts. Is there a more elegant way to do this?
Thanks,
What I would do is first filter the source array to extract only valid candidates, then return a random one (if there are any).
For example:
function getRandomObject(grid_array:Array, minSize:Number):Object {
var filtered:Array = [];
for(var i:int = 0; i < grid_array.length; i++){
var inner:Array = grid_array[i];
for(var ii:int = 0; ii < inner.length; ii++){
var object:Object = inner[ii];
if(object.size >= minSize){
filtered.push(object);
}
}
}
return filtered.length ? filtered[int(Math.random() * filtered.length)] : null;
}
// example:
var object:Object = getRandomObject(grid_array, 100);
if(object){
// do stuff with `object`
}
I asked if you need the indexes because you could do this with RegExps and the JSON Class (Flash Player 11). With this example I stored the indexes of the objects:
Create random multidimensional Array to test the function
//---I stored a variable size and the indexes inside the Object
//---Size variable will be numbers between 0 and 500
var array:Array = [];
var i;
var j;
var size:uint = 50;
var obj:Object;
for(i = 0; i < size; i++){
array[i] = [];
for(j = 0; j < size; j++){
obj = new Object();
obj.size = Math.floor(Math.random() * 500);
obj.files = i;
obj.columns = j;
array[i][j] = obj;
}
}
Method to get random Object with size property bigger than 100
//---I'll use to search the object a JSON string
var str:String = JSON.stringify(array);
//---Function to get the random Object
function getRandom():Object{
//---RegExp to search object with size between 100 and 500
var reg:RegExp = /\{[^\}]*"size":(?:10[1-9]|1[1-9]\d|[2-5]\d\d)[^\}]*\}/g;
//---Get all matches
var matches:Array = str.match(reg);
//---Return a random match converted to object
//---If no match founded the return will be null
return matches ? JSON.parse( matches[Math.floor(Math.random() * matches.length)] ) : null;
}

Assigning instance names to array Objects: ActionScript 3.0

I'll just start by saying that I am a bit new to programming, and I apologize if this is a stupid question.
I have a timer running in my application that at every interval, creates an a new instance of a MovieClip called blueBall.Here is my code:
var randomX:Number = Math.random() * 350;
var newBlue:mc_BlueBall = new mc_BlueBall ;
newBlue.x = randomX;
newBlue.y = -20;
for(var i:Number = 0;i < blueArray.length; i++)
{
newBlue.name = "newBlue" + i;
}
blueArray.push(newBlue);
addChild(newBlue);
}
var randomX:Number = Math.random() * 350;
var newBlue:mc_BlueBall = new mc_BlueBall ;
newBlue.x = randomX;
newBlue.y = -20;
for(var i:Number = 0;i < blueArray.length; i++)
{
newBlue.name = "newBlue" + i;
}
blueArray.push(newBlue);
addChild(newBlue);
}
My question is: How do I make it so that each newly created object in the array has it's own hitTestObject Event? I want to make it so that if the if the user's icon touches one of the newBlue objects, that newBlue object with be removed, and the score will go up a point.
Thanks!
this is my first time answering a question here but I hope I can help! Assuming you have a timer for your main game loop, you should try something like this once per frame:
//For each blue ball in the array
for(var i:int = 0; i < blueArray.length; i++) {
//If it touches the player
if(blueArray[i].hitTestObject(thePlayerMC)) {
//Increment the score
score++;
//Remove from stage and array
removeChild(blueArray[i]);
blueArray.splice(i, 1); //<-At index i, remove 1 element
//Decrement i since we just pulled it out of the array and don't want to skip the next array item
i--;
}
}
This is sort of the quick and dirty solution, but highly effective and commonly used.

Two Dimension Array with Custom Type Elements

I'm trying to create on my scene an n x n size matrix, each element should be a Movie Clip, named Table, already prepared in the Library.
var tables:Array.<Table> = new Array.<Table>(tablesDimension, tablesDimension);
for (var i:int = 0; i < tablesDimension; i++) {
for (var j:int = 0; j < tablesDimension; j++) {
var tempTable:Table = new Table();
tempTable.x = i * 150 + 100;
tempTable.y = j * 100 + 100;
stage.addChild(tempTable);
tables.push(tempTable);
trace(tables[0][0].x);
}
}
A Movie Clip (in this case, Table) cannot be put in two dimensional arrays? Should I use some type conversion in my last line, at the trace(tables[0][0].x); to suggest to the compiler: it's about a Table type object?
The error message I receive: "Type parameters with non-parameterized type"
I'm not sure why you're trying to do with your first line but it's incorrect.
To quote the adobe actionscript reference:
The Array() constructor function can be used in three ways.
See this adobe reference link on Array creation. Or you can use Vectors (which are typed, like you seem to want to have).
So basically you want to create an Array, that will itself contain arrays. You need to create the arrays contained in it when you go through the first one. Else you will try to push into non existing elements. Also, you need to add the index as RST said.
var tables:Array.<Table> = new Array();
for (var i:int = 0; i < tablesDimension; i++) {
tables[i] = new Array();
for (var j:int = 0; j < tablesDimension; j++) {
var tempTable:Table = new Table();
tempTable.x = i * 150 + 100;
tempTable.y = j * 100 + 100;
stage.addChild(tempTable);
tables[i].push(tempTable);
}
}
trace(tables[0][0].x);
This should work.
I think you are missing an index. Try this
for (var i:int = 0; i < tablesDimension; i++) {
for (var j:int = 0; j < tablesDimension; j++) {
var tempTable:Table = new Table();
tempTable.x = i * 150 + 100;
tempTable.y = j * 100 + 100;
stage.addChild(tempTable);
tables[i].push(tempTable);
trace(tables[0][0].x);
}
}

Resources