How to instantiate and get a length of a multidimensional array / matrix? - javascript

How do i instantiate a multidimensional array / matrix in JavaScript and Typescript, and how do i get the matrix length (number of rows) and lengths of the matrix rows?

In Typescript you would instantiate a 2x6 Matrix / Multidimensional array using this syntax:
var matrix: number[][] =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
//OR
var matrix: Array<number>[] =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
The equivalent in JavaScript would be:
var matrix =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
The JavaScript syntax is also valid in TypeScript, since the types are optional, but the TypeScript syntax is not valid in JavaScript.
To get different lengths you would use the same syntax in JS and TS:
var matrixLength = matrix.length; // There are two dimensions, so the length is 2. This is also the column size.
var firstDimensionLength = matrix[0].length; // The first dimension row has 6 elements, so the length is 6
var secondDimensionLength = matrix[1].length; // The second dimension row has 6 elements so the length is 6

Related

Return coordinates (x,y) from an array of numbers in Javascript

I am trying to make a collision map in a 2d top down view game in Javascript. I am using Tiled to build the maps. Tiled generates a json / javascript file with an array of each element in my map. I can set a boolean for each tile, so those with the true setting will come out in the array as 1 and those with the false value will return 0.
Now I want output those data as x,y coordenates. I mean if i have the array [0,0,0,0] I want that those output like (x,y) (0,0), (1,0), (2,0), (3,0) based in the width and height of the tilemap array. Something like this:
"data":[0,0,0,0,
1,1,1,1,
0,0,0,0,
0,0,0,0]
"height":4,
"width":4,
"x":0,
"y":0
My problem is I don't know how to say it to my loop that there will be four columns and four rows and the index should change from (0,0), (0,1), (0,2), (0,3) to (1,0), (1,1),(1,2),(1,3) after end the first row continue until the last column.
Any idea?
You could use two for-loops for the current row and col respectively:
const tiledOutputJson = {
"data": [
0, 0, 0, 0,
1, 1, 1, 1,
0, 0, 0, 0,
0, 0, 0, 0
],
"height": 4,
"width": 4,
"x": 0,
"y": 0
};
const { data, height, width, x, y } = tiledOutputJson;
for (let row = 0; row < height; row++) {
for (let col = 0; col < width; col++) {
console.log(`(${row}, ${col}) = ${data[row * height + col]}`);
}
console.log();
}
In general I would recommend to make it an array for x which contains the arrays for y
[
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
]
You can do the mapping like so
const data = {
"data": [0, 0, 0, 0,
1, 1, 1, 1,
0, 0, 0, 0,
0, 0, 0, 0
],
"height": 4,
"width": 4,
"x": 0,
"y": 0
}
for (let x = 0; x < data.height * data.width; x = x + data.width) {
for (let y = x; y < data.width + x; y++) {
console.log({
x: x / data.height,
y: y % data.width,
v: data.data[y]
})
}
}

Javascript Multidimensional Array complete column getting set

I am trying to make a game in Javascript. The game board is intialized to a zero-filled 2-D array. However, when I am setting the value of a single point, the complete column is getting set with that value. I think this is some issue with the way I am initializing the Array.
Method 1
# initialization
gameState = Array(6).fill(Array(7).fill(0))
# later in the game
gameState[2][4] = 1
# results in complete 4th index column to be assigned the value 1, like so -
0: (7) [0, 0, 0, 0, 1, 0, 0]
1: (7) [0, 0, 0, 0, 1, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 1, 0, 0]
4: (7) [0, 0, 0, 0, 1, 0, 0]
5: (7) [0, 0, 0, 0, 1, 0, 0]
Method 2
# initialization
let gameState = [];
for (let i=0; i<MAX_ROWS; i++) {
let row = []
for (let j=0; j<MAX_COLUMNS; j++) {
row.push(0)
}
gameState.push(row);
}
# again similar assignment
gameState[2][4] = 1
# results in correct state of the array
0: (7) [0, 0, 0, 0, 0, 0, 0]
1: (7) [0, 0, 0, 0, 0, 0, 0]
2: (7) [0, 0, 0, 0, 1, 0, 0]
3: (7) [0, 0, 0, 0, 0, 0, 0]
4: (7) [0, 0, 0, 0, 0, 0, 0]
5: (7) [0, 0, 0, 0, 0, 0, 0]
Can someone please explain what I am doing wrong here?
Your problem is pretty simple.
Array(6).fill(Array(7).fill(0))
Let's explain what this does.
Array(6)
creates a holey array with space for 6 items.
.fill(...)
will fill up these 6 holes with what ever you put in as argument.
Now comes the issue..
In Javascript, the arguments are evaluated before the execution of the function is run.
This means (in this exact case where .fill(...) is only ran once) your code is exactly the same as:
const innerArray = [0,0,0,0,0,0,0];
gameState = Array(6).fill(innerArray);
This means it fills the outer array with exactly the same array instance 6 times.
What you want is to create separate arrays each time. Just do this instead:
gameState = [...Array(6)].map(() => [...Array(7)].map(() => 0))

Issues with displaying a map in p5.js

I am currently attempting to display a map in processing using a 2d array.
Currently I have this down:
var start_map = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0],
[1, 1, 1, 1, 1]
];
function drawMap(map) {
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
if (map[x][y] == 0) {
fill(51, 153, 51);
rect((10 + 50*x), (10 + 50*y), 50, 50);
}
else if (map[x][y] == 1) {
fill(0, 102, 0);
rect((10 + 50*x), (10 + 50*y), 50, 50);
}
}
}
}
But, while I do get a map displayed, it appears to be rotated 90 degrees clockwise. What is causing this and how can I fix this?
Think about how the indexes of a 2D array work. Let's look at a simpler example:
var map = [
[1, 2],
[3, 4]
];
Where is map[0][1]? Where is map[1][0]?
A 2D array is an array of arrays. The first index selects the subarray at that index, and the second index selects the element in that subarray.
So in the simple example above, map[0] selects the subarray at index 0, which is [1, 2]. Then map[0][1] selects the element in that subarray at index 1, which is 2.
This might seem a bit surprising if you were treating the indexes as an x, y pair. In that case, you'd expect 0, 1 to give you 3, right? But it's not an x, y pair. It's an index into the outer array, then an index into the subarray.
In other words, it's actually a y, x pair. So to fix your problem, you can actually just swap the order of your indexes:
`map[y][x]`
Now you use the y value to select which subarray you want (which row you want), and the x value to select which element in that subarray you want (which column you want).

Get index on click with jquery

I am trying to develop a 2 player checkers game, for my college, but I am stuck at getting the index of the 2D array when I click on the piece.
I divided my HTML code in:
table - the game board
row - each row is the height of the array
cell - each cell is a piece and the width of the array
Then I setted a default array to start the game:
var board = [
[0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[2, 0, 2, 0, 2, 0, 2, 0],
[0, 2, 0, 2, 0, 2, 0, 2],
[2, 0, 2, 0, 2, 0, 2, 0],
];
Where the:
- 0 - empty cell
- 1 - Player 1 pieces
- 2 - Player 2 pieces
To get the position I am using this code
function getPosition() {
$('.row').on('click', function() {
console.log( $('.row').index(this) );
});
$('.cell').on('click', function() {
console.log( $('.cell').index(this) );
});
}
Get the height array position which should be between 0 and 7 are ok, but the cell from the row should be between 0 and 7 too, but using this I am getting from 0 to 63, using this parameters I have no idea how to start the next comparisons of the game.
Here is the code from codepen
http://codepen.io/michaelthompson/pen/jVdrav
In each instance you can simply use $(this).index() which will return the index within the element's siblings
But since clicking on a row always means clicking a cell you could combine them and do
$('.cell').on('click', function() {
var $cell = $(this),
columnIndex = $cell.index(),
rowIndex = $cell.parent().index();
});
What $('.cell').index(this) is doing is taking the whole collection of the class within the page and that's why you are getting 0-63

How to draw walls in ThreeJS from path or 2d array?

I need to draw a 3d house model (walls only) from a 2d path or array (explained later) I receive from FabricJS editor I've built. The type of data sent from 2d to 3d views doesn't matter.
My first (and only quite close to what I want to get) attempt was to create the array of 1s and zeros based on the room I want to draw, and then render it in ThreeJS as one cuboid per 'grid'. I based this approach on this ThreeJS game demo. So if the array look like this:
var map = [ //1 2 3 4 5 6 7 8
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1,],
[1, 1, 0, 0, 0, 0, 0, 1, 1, 1,], // 1
[1, 1, 0, 0, 1, 0, 0, 0, 0, 1,], // 2
[1, 0, 0, 0, 1, 1, 0, 0, 0, 1,], // 3
[1, 0, 0, 1, 1, 1, 1, 0, 0, 1,], // 4
[1, 0, 0, 0, 1, 1, 0, 0, 1, 1,], // 5
[1, 1, 1, 0, 0, 0, 0, 1, 1, 1,], // 6
[1, 1, 1, 0, 0, 1, 0, 0, 1, 1,], // 7
[1, 1, 1, 1, 1, 1, 0, 0, 1, 1,], // 8
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1,],
];
I iterate through the array and render one block for every 1, and calculate it's position from indexes from the 2d 'map' (my array).
var UNITSIZE = 250, units = mapW;
for (var i = 0; i < mapW; i++) {
for (var j = 0, m = map[i].length; j < m; j++) {
if (map[i][j]) {
var wall = new t.Mesh(cube, material);
wall.position.x = (i - units/2) * UNITSIZE;
wall.position.y = WALLHEIGHT/2;
wall.position.z = (j - units/2) * UNITSIZE;
scene.add(wall);
}
}
}
It worked great till I wanted to place other models (.obj, but it doesn't matter. Let's call them furniture) near the walls. Each piece of furniture has it's (x=0, y=0, z=0) point in the center of the model, and since walls are cubes (with the same coord system, with 0 point in the center), furniture are rendered in the center of the wall (when we place it in the corner, only 1/4 of the model is visible). This is more/less how it looks like:
(black - how the walls should look like, blue - each cuboid of the wall, red - piece of furniture)
Thats why I would like to render walls as planes, probably from a 2d closed patch (I can export it from Fabric without a problem). I don't need walls to be thick nor to be visible "from behind", when camera moves through the wall. Any clues on how to achieve something like this?
"Help me StackOverflow, your my only hope."
You can manually populate the vertex and face arrays of a THREE.js mesh, so if you can export the closed path you need for example as an array of coordinates, you can iterate over it, and push needed information to your wall object.
Something like this
var coordArray = [...]; //Array of corner points of a closed shape from your source. Here assumed to be THREE.Vector2() for simplicity.
var walls = new THREE.Geometry();
for(var i = 0; i < coordArray.length(); i++){ //iterate over the coordinate array, pushing vertices to the geometry
var coordinates = coordArray[i];
walls.vertices.push(new THREE.Vector3(coordinates.x, coordinates.y, 0)); //vertex at floor level
walls.vertices.push(new THREE.Vector3(coordinates.x, coordinates.y, 10)); //vertex at the top part of the wall, directly above the last
}
var previousVertexIndex = walls.vertices.length - 2; // index of the vertex at the bottom of the wall, in the segment we are creating faces for
for(var i = 0; i < walls.vertices.length; i += 2){
walls.faces.push(new THREE.Face3(i, i + 1, previousVertexIndex));
walls.faces.push(new THREE.Face3(i + 1, previousVertexIndex + 1, previousVertexIndex));
previousVertexIndex = i;
}
walls.computeVertexNormals();
walls.computeFaceNormals();
scene.add(new THREE.Mesh(walls, new THREE.MeshLambertMaterial());

Categories

Resources