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

左心房为你撑大大i 提交于 2019-12-13 07:57:07

问题


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



来源:https://stackoverflow.com/questions/20505211/how-to-put-dice-rolls-in-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!