I am currently playing around with flex, I have C++ background, so I am not used to AS3.
The problem is in the main *.mxml file I have fx:script block and I try to define a multidimensional array like that:
public var Board:Array = new Array(25);
I use a function to initialize the 2d-array:
public function initBoard():void {
var i:int;
var j:int;
for (i = 0; i < 25; i++) {
Board[i] = new Array(40);
for (j = 0; i < 40; j++) {
Board[i][j] = 0;
}
}
}
This function gets called later on in the main loop to init and reset the "board" why doesn't it work. The only difference to the AS3 documentation is that it gets done in a function. Is there a scope problem?
Thanking you in anticipation,
Niklas Voss
P.S. I hope someone can tell me why it doesn't work and how to do it right...
You have i where there should be j.
for (j = 0; i < 40; j++) {
This should solve your problems.
for (j = 0; j < 40; j++) {
You don't need to define an array length in AS3 - I just use the [] operator for creating a new array. Also you used i where j was needed in the innermost for loop.
function initBoard():Array
{
var board:Array = [];
var i:int = 0;
var j:int;
for(i; i<25; i++)
{
board[i] = [];
j = 0;
for(j; j<40; j++)
{
board[i][j] = 0;
}
}
return board;
}
trace(initBoard());
Related
I want to initialize a square of textures with sf::sprite elements.
To make the main()-function as clean as possible, I wrote a function in another file, it looks like this:
vector<vector<sf::Sprite>> init_board_graphics(int size) {
sf::Texture _t1;
sf::Texture _t2;
_t1.loadFromFile("images/whitefield.png");
_t2.loadFromFile("images/blackfield.png");
vector<vector<sf::Sprite>> board;
//init vector for insert row-values
vector<sf::Sprite> help_vector;
for (int i = 0; i < size; i++) {
help_vector.clear();
for (int j = 0; j < size; j++) {
sf::Sprite insert_element;
if ((i + j) % 2 == 0) {
insert_element = sf::Sprite(_t1);
}
else {
insert_element = sf::Sprite(_t2);
}
insert_element.setPosition(i * pixel_field, j * pixel_field);
help_vector.push_back(insert_element);
}
board.push_back(help_vector);
}
return board;
}
When I call the function in main(), everything is fine at first, the elements are at the correct positions and the textures are also of correct size.
When I try to debug the next steps, I can observe that the textures of the elements are getting changed in size, even though the next lines have absolutely nothing to do with my object. First, I thought the entries are getting changed because I allocate the entries in the <vector<vector<sf::sprite>> - object in a wrong way but I fixed this:
if (parameters::visual_output) {
//Draw field
for (int i = 0; i < size_board; i++) {
vector<sf::Sprite> help_vec = board[i];
for (int j = 0; j < size_board; j++) {
window.draw(help_vec[j]);
}
}
}
The textures are still getting changed for some reason. Why is this happening?
I'm playing with Typescript and I wonder, how to properly instantiate and declare multidimensional array. Here's my code:
class Something {
private things: Thing[][];
constructor() {
things = [][]; ??? how instantiate object ???
for(var i: number = 0; i < 10; i++) {
this.things[i] = new Thing[]; ??? how instantiate 1st level ???
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing(); ??? how instantiate 2nd lvl item ???
}
}
}
}
Can you give me any hint about selected places?
You only need [] to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.
The same thing applies at the first level in your loop. It is merely an array and [] is a new empty array - job done.
As for the second level, if Thing is a class then new Thing() will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.
class Something {
private things: Thing[][];
constructor() {
this.things = [];
for(var i: number = 0; i < 10; i++) {
this.things[i] = [];
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing();
}
}
}
}
Here is an example of initializing a boolean[][]:
const n = 8; // or some dynamic value
const palindrome: boolean[][] = new Array(n)
.fill(false)
.map(() =>
new Array(n).fill(false)
);
If you want to do it typed:
class Something {
areas: Area[][];
constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[] = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}
You can do the following (which I find trivial, but its actually correct).
For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).
Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following
const myArray: any[][] = [];
And later, when you want to populate it, you can do the following:
myArray.push([<your value goes here>]);
A short example of the above can be the following:
const myArray: string[][] = [];
myArray.push(["value1", "value2"]);
Beware of the use of push method, if you don't use indexes, it won't work!
var main2dArray: Things[][] = []
main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)
gives only a 1 line array!
use
main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray
to get your 2d array working!!!
Other beware! foreach doesn't seem to work with 2d arrays!
I’m new to Handlebars.js and just started using it. Most of the examples are based on iterating over an object. I wanted to know how to use handlebars in basic for loop.
Example.
for(i=0 ; i<100 ; i++) {
create li's with i as the value
}
How can this be achieved?
There's nothing in Handlebars for this but you can add your own helpers easily enough.
If you just wanted to do something n times then:
Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i)
accum += block.fn(i);
return accum;
});
and
{{#times 10}}
<span>{{this}}</span>
{{/times}}
If you wanted a whole for(;;) loop, then something like this:
Handlebars.registerHelper('for', function(from, to, incr, block) {
var accum = '';
for(var i = from; i < to; i += incr)
accum += block.fn(i);
return accum;
});
and
{{#for 0 10 2}}
<span>{{this}}</span>
{{/for}}
Demo: http://jsfiddle.net/ambiguous/WNbrL/
Top answer here is good, if you want to use last / first / index though you could use the following
Handlebars.registerHelper('times', function(n, block) {
var accum = '';
for(var i = 0; i < n; ++i) {
block.data.index = i;
block.data.first = i === 0;
block.data.last = i === (n - 1);
accum += block.fn(this);
}
return accum;
});
and
{{#times 10}}
<span> {{#first}} {{#index}} {{#last}}</span>
{{/times}}
If you like CoffeeScript
Handlebars.registerHelper "times", (n, block) ->
(block.fn(i) for i in [0...n]).join("")
and
{{#times 10}}
<span>{{this}}</span>
{{/times}}
This snippet will take care of else block in case n comes as dynamic value, and provide #index optional context variable, it will keep the outer context of the execution as well.
/*
* Repeat given markup with given times
* provides #index for the repeated iteraction
*/
Handlebars.registerHelper("repeat", function (times, opts) {
var out = "";
var i;
var data = {};
if ( times ) {
for ( i = 0; i < times; i += 1 ) {
data.index = i;
out += opts.fn(this, {
data: data
});
}
} else {
out = opts.inverse(this);
}
return out;
});
Couple of years late, but there's now each available in Handlebars which allows you to iterate pretty easily over an array of items.
https://handlebarsjs.com/guide/builtin-helpers.html#each
So I hava array Links and array Params with same langth N
So what I need is to create an object where for each link from Links I will be able to see
param from Params
And than for example to be abble to call something like
for each( item in object)
if (item.param == "some value") {
// some code
} else...
How to do such thing (Code exaMple, please)
From Array: You could first build a list with elements composed of a item and a param (supposing the length is indeed the same for both lists)
var items:Array = new Array();
for(var i:uint = 0; i < links.length; i++) {
links:Array .push({link:links[i], param:params[i]});
}
You can then filter them easily:
items.forEach(checkValue);
for(var i:uint = 0; i < items.length; i++) {
if (items[i].param == "some value") {
// some code
} else{
...
}
}
I have a Canvas which has many components inside it and those again, have many components inside them.
getChildren() returns only the top level children. What is the best way to retrieve all the children (children of children of children and so on).
Well, I sorta know how to do this by iterating through the children, but the code is really messy. I'd prefer to use a nice recursive function. Has anyone written this before? Or is there a Util class to do this?
private function recuse(display : DisplayObjectContainer) : void {
if(display) {
for (var i : int = 0;i < _display.numChildren;i++) {
var child : DisplayObject = display.getChildAt(i);
trace(child.name);
if(child is DisplayObjectContainer) {
recuse(DisplayObjectContainer(child));
}
}
}
}
Try something likely (note you can return the lists recursively if you want to gather all the references to the top level iteration)
function inspect(object:DisplayObject):void
{
if(object is DisplayObjectContainer)
{
var casted:DisplayObjectContainer = object as DisplayObjectContainer
trace("DisplayObjectContainer ", casted.name)
for(var depth:int = 0; depth < casted.numChildren;depth++)
{
inspect(casted.getChildAt(depth))
}
}else{
trace("DisplayObject", object.name );
}
}
inspect(this)
function theCallbackFunction(obj:DisplayObject):void
{
trace(obj.name);
}
//Visit the children first.
//Deep most objects will be visited first and so on.
//stage is visited at the end.
//Uses recursion
function depthFirst(obj:DisplayObject, func:Function):void
{
if(!(obj instanceof DisplayObjectContainer))
{
func(obj);
return;
}
var p:DisplayObjectContainer = DisplayObjectContainer(obj);
var len:Number = p.numChildren;
for(var i:Number = 0; i < len; i++)
{
var child:DisplayObject = p.getChildAt(i);
depthFirst(child, func);
}
func(obj);
}
//Visit the siblings first.
//stage is visited first, then its children, then the grand children and so on
//No recursion.
function breadthFirst(obj:DisplayObject, func:Function):void
{
var q:Array = [];
q.push(obj);
var p:DisplayObjectContainer;
var i:Number, len:Number;
while(q.length != 0)
{
var child:DisplayObject = queue.shift();
func(child);
if(!(child instanceof DisplayObjectContainer))
continue;
p = DisplayObjectContainer(child);
len = p.numChildren;
for(i = 0; i < len; i++)
q.push(p.getChildAt(i));
}
}
depthFirst(this.stage, theCallbackFunction);
breadthFirst(this.stage, theCallbackFunction);