How to put dice rolls in an array? [closed]

2019-09-21 14:39发布

问题:

Dear stackoverflowers,

Could someone help me further with this excercise:

Throw a dice 40 times. The throws has to be put in an array. If a throw is the same as the previous one, it has to be grouped between brackets. It'll cost you 1 point per throw, and if you throw two the same numbers in a row, you get 5 points. Print the info out for the user(like: "Congratz! You earned 5 points") , and how many points the user has left. I dont really know from how many points the user starts but lets just give it 40.

This is my code so far

<html>
<head>
    <script>
function rollDice() {
           var die1 = document.getElementById("die1");
           var status = document.getElementById("status");

           var d1 = Math.floor(Math.random()*6) +1;
           console.log("You rolled "+d1+".");
           if(d1)

  }

  </script>
</head>
<body>
    <div id="die1" class="dice">0</div>

    <button onclick="rollDice()"> Roll the dice </button>
    <h2 id="status" style="clear:left":> </h2>
</body>

Id like to know how to put this into an array and if a throw is the same as the previous one, it logs to the console 5 points. I'm a beginner so please bear with me.

Thanks in advance,

Youssef

回答1:

YOu can declare an array as follows:

var diceRolls = [];

To add something to an array:

diceRolls.push(diceRoll);

To check previous result for equality. Note shoudl also check the previous element exists in the array.

if (diceRolls[diceRolls.length - 1] === diceRoll)
     // do stuff

Hope that gets you started. W3cschools is a great way to get started