I'm trying to code a simple Ludo/dice roll game where the dice rolls when the Roll Dice
button is clicked, however the dice only rolls for one player. I think it could be because I'm using the getElementbyId
method, however when change it to class
and use querySelectorAll
instead it results in both of the dice images being static.
// Declare Variables
const images = ['dice1.png',
'dice2.png',
'dice3.png',
'dice4.png',
'dice5.png',
'dice6.png']
// Randomize
function playerRoll() {
ranImage = Math.floor(Math.random() * images.length);
rollDice = images[ranImage];
document.getElementById('display-image').src = `./images/${rollDice}`
}
.dice{
cursor: pointer;
}
<body>
<h1>Ludo Game</h1>
<h2>Player 1</h2>
<div class="dice-image"></div>
<div class="dice">
<img id="display-image" src="/images/dice1.png" height="100px" weight="100px">
</div>
<h2>Player 2</h2>
<div class="dice-image"></div>
<div class="dice">
<img id="display-image" src="/images/dice4.png" height="100px" weight="100px">
</div>
</div>
<button id="roll-button" onclick="playerRoll()">Roll Dice</button>
<script src="index.js"></script>
</body>
</html>