JavaScript在循环问题中选择自己的冒险游戏随机数函数

时间:2019-02-25 21:17:26

标签: javascript loops random

我正在编写一个自己选择的冒险程序,其中,如果选择了一个特定选项(例如要等待的示例),则用户会得到一个介于1到10之间的随机数来做俯卧撑(俯卧撑就是用户点击提示“确定”按钮,但是很多时候随机数等于),到目前为止,这是我的代码,但我不断遇到错误。我是一个完全菜鸟,所以请放轻松。

 var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
  alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
    alert("Nice! Lets see you crank out " + pushUp + "!");
    setsOf10 = true;
  }
for (var i=0; i<count; i++){
  pushUps();
}
  else {
    alert("Really, thats it? Try again");
  }

while ( setsOf10 == false);
}

玩了更多之后,我可以说我已经接近了,但仍然没有。再说一次,我不是要您为我解决这个问题,因为我做错了或遗漏了什么。这就是我所拥有的,它给了我我的随机数,我只需要它就可以让我单击“确定”按钮,无论该随机数分配给我多少次。

    var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
  alert(pushUpSets);
  if (pushUpSets < 3){
    var weak = "Thats it? Weak sauce!";
    alert(weak);
  }
  else{
    alert("Sweet lets get some reps in!");
  }
  for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}

1 个答案:

答案 0 :(得分:1)

在这里,“做出选择”按钮只是一个虚拟按钮,使我们可以进行俯卧撑。每次点击都会减少我们的计数。

// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code. 
document.addEventListener('DOMContentLoaded', () => {
  document.querySelector('#choice').addEventListener('click', makeChoice);
});

function makeChoice() {
  // Call a method to set random pushups and setup the click event
  setUpPushUp();
  // Here we change the display style of the push up section so that it shows to the player.
  document.querySelector('.activity').style.display = 'block';
}

// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;

function setUpPushUp() {
  // Create a random number of pushups, in sets of 10.
  // We add an extra 1 so we can call the doPushUp method to initialize.
  pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;

  // Add a click event to the push up button and call our doPushUp method on each click.
  document.querySelector('#push').addEventListener('click', doPushUp);
  
  // This is just an init call, it will use the extra 1 we added and place test in our P tag.
  doPushUp();
}


function doPushUp() {
  // Get a reference to our output element, we will put text to player here.
  let result = document.querySelector('p');
  // They have clicked, so remove a push up. 
  pushUps--;
  
  // See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
  if (pushUps > 0) {
    result.innerText = `You need to crank out ${pushUps} pushUps`;
  } else {
    result.innerText = 'Nice work!';
  }

}
.activity {
  display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
  <p></p>
  <button id="push">Push</button>
</div>