randomNum
function returns the different values to diceNum.innerText
and player.style.gridColumnStart
, I want them to be same,How do I do that ?
const randomNum = () => {
return Math.floor(Math.random() * 6) 1;
};
diceBtn.addEventListener("click", () => {
const diceNum = document.getElementById("dice-num");
diceNum.innerText = randomNum();
drawPlayer();
});
function drawPlayer() {
playerBody.forEach((pos) => {
const player = document.createElement("div");
player.style.gridRowStart = pos.x;
player.style.gridColumnStart = randomNum();
player.setAttribute("id", "playerElement");
gameBoard.appendChild(player);
});
}
CodePudding user response:
Set randomNumber as a variable and use that.
class RanNumber {
value = Math.floor(Math.random() * 6) 1;
generateNewNumber() {
this.value = Math.floor(Math.random() * 6) 1;
}
getNumber() {
return this.value
}
}
const RanNum = new RanNumber()
diceBtn.addEventListener("click", () => {
// On click generate new number
RanNum.generateNewNumber()
const diceNum = document.getElementById("dice-num");
diceNum.innerText = RanNum.getNumber();
drawPlayer();
});
function drawPlayer() {
playerBody.forEach((pos) => {
const player = document.createElement("div");
player.style.gridRowStart = pos.x;
player.style.gridColumnStart = RanNum.getNumber();
player.setAttribute("id", "playerElement");
gameBoard.appendChild(player);
});
}
CodePudding user response:
You can pass the random generated number to the drawPlayer function, here's a sample
const randomNum = () => {
return Math.floor(Math.random() * 6) 1;
};
diceBtn.addEventListener( "click", () => {
const diceNum = document.getElementById( "dice-num" );
const rndNum = randomNum();
diceNum.innerText = rndNum;
drawPlayer( rndNum );
});
function drawPlayer( rndNum ) {
document.querySelectorAll( ".playerBody" ).forEach( element => {
element.innerText = rndNum;
});
}
<button id="diceBtn">Roll</button>
<div id="dice-num">#</div>
<div >0</div>
<div >1</div>
<div >2</div>
<div >3</div>
<div >4</div>
<div >5</div>
<div >6</div>