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

问题描述 投票:0回答:1

我正在编写一个选择你自己的冒险计划,如果选择了一个特定的选项(例如等待),用户会得到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);
}
}
javascript loops random
1个回答
1
投票

在这里,make a choice按钮只是假的,允许我们去做俯卧撑。每次点击都会减少我们的计数。

// 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>
© www.soinside.com 2019 - 2024. All rights reserved.