mercredi 26 septembre 2018

JavaScript - Generate a random number between 1 and 5, but never the same number twice consecutively

Okay hello everyone. I'm going to try to explain this the best I can....I have some simple code to generate a random number between 1 and 5. Depending on what number is pulled, a certain sound file will play..... HOWEVER.....how could I prevent this simple program from generating the same number twice in a row consequently making the same audio to play twice? For example: a roll of the dice is never the same twice consecutively....meaning you cannot roll a 2 if you just rolled a 2 etc.

I was experimenting with if else statements and kind of backed myself into a corner. I know this may seem like a simple problem but I'm at my wits end on this one. Any advice will be much appreciated! Thanks!

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display a random number between 1 and 5.</p>

<button onclick="myFunction()">ROLL DICE</button>

<p id="demo"></p>

<script>
function myFunction() {
var x = Math.floor((Math.random() * 5) + 1);
document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

Aucun commentaire:

Enregistrer un commentaire