How does this repeat() function work? Help me understand - javascript

I'm learning Javascript and found this solution on how to make a 16X16 grid. so far i've used example.repeat(number) with a an integer value. I somewhat get the flow of the code but I cant grasp how repeat works here exactly, kindly help.
Result on codepen: https://codepen.io/shogunhermit15/pen/mdxyqMN?editors=1010
function buildGrid(x, y, cellSize, gridElement) {
gridElement.style.display = "grid";
gridElement.style.gridTemplateColumns = `repeat(${x}, ${cellSize}px)`;
gridElement.style.gridTemplateRows = `repeat(${y}, ${cellSize}px)`;
let squares = new DocumentFragment();
for (let i = 0; i < x * y; i++) {
let square = document.createElement('div');
square.className = 'square';
squares.appendChild(square);
}
gridElement.appendChild(squares);
}
buildGrid(16, 16, 25, document.querySelector(".grid"));

I think your question is not related to javascript.
It is related to the CSS repeat function.
The repeat() CSS function represents a repeated fragment of the track list, allowing a large number of columns or rows that exhibit a recurring pattern to be written in a more compact form.
Here is Mdn refrence where You can learn more:
https://developer.mozilla.org/en-US/docs/Web/CSS/repeat

You will find here your code with each line commented, hoping that it helps you to understand your code correctly.
function buildGrid(x, y, cellSize, gridElement) { // declaration of the buildGrid function which takes as parameters the location of the grid, the size of the cell, and the element of the grid
gridElement.style.display = "grid"; // grid display is set to grid
gridElement.style.gridTemplateColumns = `repeat(${x}, ${cellSize}px)`; // set grid size based on cell size
gridElement.style.gridTemplateRows = `repeat(${y}, ${cellSize}px)`; // set grid size based on cell size
let squares = new DocumentFragment(); // creating the squares object which contains the grid elements
for (let i = 0; i < x * y; i++) { // loop that creates grid cells
let square = document.createElement('div'); // creating a div element
square.className = 'square'; // adding square class to cell
squares.appendChild(square); // adding the cell to the grid
}
gridElement.appendChild(squares); // adding grid to page element
}
buildGrid(16, 16, 25, document.querySelector(".grid")); // call buildGrid function with defined parameters

Related

How can I get the particular point in a THREE.Points object to change his position?

I work on a personal project to try out equations to try to simulate the behavior of a galaxy. I have so far managed to place the Points as I wanted, but now I want to take each point individually to change its position.
The goal for now is just to successfully try to apply a Random Vector to each of the points.
I tried:
var direction = new THREE.Vector3(0.00003, 0.000005, 0);
points.position.add(direction);
but this applies to all Points.
Then I tried something like that:
for (let i = 0; i < points.geometry.attributes.position.count; i++) {
points.geometry.attributes.position[i] = Math.random() * 500
}
points.geometry.attributes.position.needsUpdate = true;
But nothing append :( I thing I missed something but I dind't know what
Here the full code on codepen:
Codepen
When you access:
points.geometry.attributes.position[i]
you're not getting the array of the vertex positions. You're getting the BufferAttribute. What you probably want is the array inside the BufferAttribute:
points.geometry.attributes.position.array[i]
However, this is still not the recommended approach. Three.js recommends you use the .getAttribute() method:
// Get the attribute
const posAttribute = points.geometry.getAttribute("position");
// Get the array inside the attribute
const posArray = posAttribute.array;
// Increment by 3 at a time to access XYZ separately
for(let i3 = 0; i3 < posArray.length; i3 += 3) {
posArray[i3 + 0] = xPosition;
posArray[i3 + 1] = yPosition;
posArray[i3 + 2] = zPosition;
}
// Tell the attribute it needs updatin
posAttribute.needsUpdate = true;

PIXI Logic is Skewed from the Actual Visuals

I am pretty new to JavaScript and PIXI. I am making a little game that requires the player to navigate and grab a key (move onto the same space as the key). This takes them to the next level. My problem is that whenever a new level is generated, it somehow uses the x and y coordinates for the key of the previous level to skew the logic. Because of this, the first level works fine, but every level afterwards is messed up.
The levels get skewed up and to the left by the respective values of the previous key. I have a 2d array in the background which holds values of where and where not the player can (holds values for things like walls, turrets, and the key). I randomly generate the key coordinates and for example set grid[9][12] = 3; for the key space. The next level visually looks perfect, with the walls and key generating, and the player being in the top left. However because of the skew, the top left of the visuals is really at [max_X - 9][max_Y - 12] and the player can go off screen to invisibly access the rest of the maze. So I can then phase through walls because the logic has the walls in a different place than the visuals, and the actual key space usually ends up off screen.
Here is my code that generates a new goal (key) object
function createGoal(scene) {
while (true) {
let x = getRandomInt(APP_WIDTH);
let y = getRandomInt(APP_HEIGHT);
//if space is not already occupied, populate
if (grid[x][y] == 0) {
console.log(x);
console.log(y);
goal = null;
goal = new Goal(TILE_WIDTH, x, y);
scene.addChild(goal);
grid[x][y] = 3;
break;
}
}
}
And here is the grid initialization:
const grid = new Array(APP_WIDTH);
for (let i = 0; i < APP_WIDTH; i++) {
grid[i] = new Array(APP_HEIGHT);
for (let j = 0; j < APP_HEIGHT; j++) {
grid[i][j] = 0;
}
}
Any help would be greatly appreciated.

Photoshop scripting with JSX in for loop to change fill color of each layer

So, I am tinkering with changing fill colors of layers in a PSD file using JSX. I ultimately want to loop all layers, turning off visibility for all but one, edit the fill color of that layer, save as PNG, and then repeat for all layers and all colors in JSON file. I'm starting small as this is my first attempt, but if your solution can help preempt my downfalls with other tasks then it would be greatly appreciated. Here is what I have (alert properly prompts, but line 5 receives error 1302: no such element referencing line 5):
var layerNum = app.activeDocument.layers.length
alert(layerNum);
var i;
for (i=0;i<layerNum;i++){
var currentLayer = app.activeDocument.layers.index(i)
var myColor = new SolidColor();
//var RGB = HEXtoRGB(Y);
myColor.rgb.red = RGB[255];
myColor.rgb.green = RGB[0];
myColor.rgb.blue = RGB[0];
currentLayer.fill.color = myColor;
}
Is this because the collection of layers does not start at 0? Should I start with layers.index(layerNum) and use i-- to move down the collection? Any insight would be helpful. Thanks in advance to this always helpful community.
This var currentLayer = app.activeDocument.layers.index(i)
should be this: var currentLayer = app.activeDocument.layers[i]
Layers collections are pretty much the same as arrays, starting from 0, so you did it right
As KienT points out you need to use square brackets for layers.
Also it's useful to create a variable that's the app.activeDocument, so you don't have to type that out each time. Looping over the layers backwards (or up) is easy - just remember to take 1 off the layers length. You can adjust also make it ignore the background by making the loop start at 1 instead of 0. You can also adjust the layers visibility from true to false (on and off) as you go.
// call the source document
var srcDoc = app.activeDocument;
var layerNum = srcDoc.layers.length;
// alert(layerNum);
for (var i = layerNum -1; i >= 0; i--)
{
var currentLayer = srcDoc.layers[i];
var myColor = new SolidColor;
// Select the layers as you go
srcDoc.activeLayer = srcDoc.artLayers[i];
// switch layer visibility to on
srcDoc.visible = true;
myColor.rgb.red = 255;
myColor.rgb.green = 0;
myColor.rgb.blue = 0;
app.activeDocument.selection.fill(myColor, ColorBlendMode.NORMAL, 100, false);
}

Class-wide Event is Malfunctioning [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 4 years ago.
I create a 16x16 grid of divs in JavaScript.
Each div has a mouse enter event (inherited based on common class) that should change its black background to white.
Here's my problem: whereas each div should change color when it's hovered over, all divs (when hovered over) cause the same bottom-right div to change color, rather than themselves.
I believe all of the events reference the final div under the className "squares" (bottom right div). How do I make each event reference its own div?
SNAPSHOT
CODE
//GRID CREATION (30x30)
var container = document.getElementById('container');
var size = 30;
//Row Creation (30)
for(j=0; j < size; j++) {
var row = document.createElement('div');
row.classList.add("row");
//Square Creation (30 per Row)
for(i=0; i<size; i++) {
var square = document.createElement('div')
square.classList.add("square");
//div background-color changes on mouse-enter
square.addEventListener('mouseenter', () => {
this.square.style.background = 'white';
});
row.appendChild(square);
}
container.append(row);
}
It’s strange to find this.square in your event listener when nothing else refers to this.square. Perhaps you originally tried square.style.background, which didn’t work for the reason described in JavaScript closure inside loops – simple practical example, then tried to fix it with this.style.background = 'white';, which didn’t work because it was an arrow function, then tried to make this.square work…?
Anyway, use either a non-arrow function, to get this inside to be the element the event listener was attached to instead of the same as the this outside:
square.addEventListener('mouseenter', function () {
this.style.background = 'white';
});
or better, declare your variables with let – which must be available, since you were using an arrow function – and refer to square:
//GRID CREATION (30x30)
let container = document.getElementById('container');
let size = 30;
//Row Creation (30)
for (let j = 0; j < size; j++) {
let row = document.createElement('div');
row.classList.add("row");
//Square Creation (30 per Row)
for (let i = 0; i < size; i++) {
let square = document.createElement('div');
square.classList.add("square");
//div background-color changes on mouse-enter
square.addEventListener('mouseenter', () => {
square.style.background = 'white';
});
row.appendChild(square);
}
container.append(row);
}
Declarations for j and i were missing, too. You should enable strict mode and never use var to avoid these types of problems.

wants to know about some Javascript function explanation

Hy,this is my first post here
I am following a front end dev. class
Recent task was to create a pixel art page,was my first ever bigger task with javascript,i asked around and solved parts what I didn't know how,but now I do not understand everything,would appreciate if any experienced user could help me.
// Select color input
// Select size input
// When size is submitted by the user, call makeGrid()
//function makeGrid(row,colm) {
function makeGrid() {
let gridRows, cell;
let rows = $("#inputHeight").val();
let cols = $("#inputWidth").val();
let table = $("#pixelCanvas");
table.children().remove();
for (let i = 0; i < rows; i++) {
table.append("<tr></tr>");
}
gridRows = $("tr");
for (let j = 0; j < cols; j++){
gridRows.append("<td></td>");
}
cell = table.find("td");
table.on("click", "td", function() {
var color = $("input[type='color']").val();
$(this).attr("bgcolor", color);
});
}
//when size is submitted call makeGrid()
$("input[type='submit']").click(function(e) {
e.preventDefault();
makeGrid();
});
This is my code,parts which I do not understand:
table.children().remove();-removes tables child element(?what exactly removes,why this needed to be implemented?
cell = table.find("td");-I know that .find is a jquery element which allows us to search trough descendant but I do not understand why I needed this here.
The project is also uploaded on my codepen
https://codepen.io/MelindaB/pen/xWgJqY
Thank you for the help
table.children().remove(); is used to clear the current generated table to make it possible to create a new one.
You can test this by removing the line, generating a 1x1 table, and generate another 1x1 after that. You will see the grid now actually consists of 3 cells instead of the specified 1.
As far as I can see cell = table.find("td"); has no use since cell is not used anywhere and this line can be removed.

Categories