I was watching a YouTube tutorial about coding the 2048 game in Vanilla JavaScript, HTML and CSS. While I was watching the tutorial I thought I could also refactor the code given by the instructor. In a certain point, she calls twice a function to generate two numbered squares (not 0) in random places of the grid. I thought I could write a function (call it randomSquaresGenerator) that given the wanted amount of different positions could generate the respective amount of random numbered squares. Thing is that after some tests (refreshes on my browser) there are times where I can see fewer than the desired squares. I figured out that this is because in certain calls the function might check an already numbered square and passes. I still haven't figured on how to solve this though. Any ideas?
Here is my JavaScript code:
document.addEventListener("DOMContentLoaded", () => {
const gridDisplay = document.querySelector(".grid");
const scoreDisplay = document.querySelector(".score");
const resultDisplay = document.querySelector(".result");
const width = 4;
const squaredWidth = width ** 2;
let squares = [];
function createBoard(width) {
for (let i = 0; i < squaredWidth; i++) {
square = document.createElement("div");
square.innerHTML = 0;
gridDisplay.appendChild(square);
squares.push(square);
}
}
//The function with the unwanted behavior.
function randomSquaresGenerator(positions) {
for (let i = 0; i < positions; i++) {
let randomSquare = Math.floor(Math.random() * squaredWidth);
if (squares[randomSquare].innerHTML == 0) {
squares[randomSquare].innerHTML = 2;
}
}
}
createBoard();
randomSquaresGenerator(2);
});
And my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>2048</title>
<link rel="stylesheet" href="style.css" />
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div class="score-container">
<div class="score-title">SCORE</div>
<span class="score">1000</span>
</div>
<div class="grid"></div>
<div class="result"></div>
</body>
</html>
for(...)with a fixed number of rounds. Use awhileand count how many squares have been "generated". If the number is equal topositionsthen get out of the loop.positionsvalue.