Логика, если утверждение только достигает 9/10 - PullRequest
0 голосов
/ 31 декабря 2018

Код должен присуждать большинство из 10 сальто в сторону выигравшей монеты.Тем не менее, это всего лишь 9 бросков и награждение большинства из 9.

Я пытался умерить число, но ни один из них не удался.при изменении процента до 110 общее количество сальто переходит только к 7

    //start decleration of variables; self explainitory 
    var placeholder = document.getElementById("placeholder");
    var heads_counter = 0;
    var tails_counter = 0;
    var wins = 10;

    //reset button listener & functionality 
    document.getElementById("reset").addEventListener("click", function(){
        heads_counter = 0;
        tails_counter = 0;
        placeholder.innerText = ("");
        coin_placeholder.innerText = ("");
    });

    //coin img event listener & functionality 
    document.getElementById("coin").addEventListener("click", function(){
        //50% chance of 1 or 2
        var chance = Math.floor(Math.random() * 2); 

        //if chance is 1 "Heads!"" is displayed in place holder and adds to heads_counter
        if (chance == 1){
            placeholder.innerText = ("Heads!");
            heads_counter++;                
        //else statment if chance is 2, "Tails!" is displayed and adds to tails_counter 
        }else  {
            placeholder.innerText = ("Tails!");
            tails_counter++;        
        }
        //if the majority of total flips is heads, "Heads wins!" is displayed
        if(51 <= heads_counter / wins * 100 && tails_counter / wins * 100 <= 49){
            placeholder.innerText = ("Heads Wins!");
            heads_counter = 0;
            tails_counter = 0;
        //if the majority of total flips is tails, "Tails wins!" is displayed
        }else if (51 <= tails_counter / wins * 100  && heads_counter / wins * 100 <= 49){
            placeholder.innerText = ("Tails Wins!");
            heads_counter = 0;
            tails_counter = 0;
        //if flips are tied, "Tie!" is displayed
        }else if(tails_counter / wins * 100 == 50 && heads_counter / wins * 100 == 50){
            placeholder.innerText = ("Tie!")
            heads_counter = 0;
            tails_counter = 0;
        }
        //innerText of coin_placeholder
        coin_placeholder.innerText = ("Heads: " + heads_counter + " Tails: " + tails_counter);
});

1 Ответ

0 голосов
/ 31 декабря 2018

бросок монеты не происходит десять раз.

Ваша логика во втором выражении if эффективно ищет 5 или более бросков на одной стороне, но не проверяет необходимый остаток.Т.е. 6 голов выиграют и завершат игру, даже если есть только 1 хвост.

Это потому, что требования больше и меньше не обязательно составляют в сумме 100%, то есть 6 голов и 3 хвостабудет соответствовать этим требованиям, так как 60% - это головы, а 30% - хвосты (т. е.> 51% голов и <49% хвостов). </p>

Я добавил базовую проверку и вышел из функции перед этой проверкой.если общий лимит не был достигнут.


Демо

//start decleration of variables; self explainitory 
var placeholder = document.getElementById("placeholder");
var coin_placeholder = document.getElementById("coin_placeholder");
var heads_counter = 0;
var tails_counter = 0;
var wins = 10;

//reset button listener & functionality 
document.getElementById("reset").addEventListener("click", function() {
  heads_counter = 0;
  tails_counter = 0;
  placeholder.innerText = ("");
  coin_placeholder.innerText = ("");
});

//coin img event listener & functionality 
document.getElementById("coin").addEventListener("click", function() {
  //50% chance of 1 or 2
  var chance = Math.floor(Math.random() * 2);

  //if chance is 1 "Heads!"" is displayed in place holder and adds to heads_counter
  if (chance == 1) {
    placeholder.innerText = ("Heads!");
    heads_counter++;
    //else statment if chance is 2, "Tails!" is displayed and adds to tails_counter 
  } else {
    placeholder.innerText = ("Tails!");
    tails_counter++;
  }

  //innerText of coin_placeholder
  coin_placeholder.innerText = ("Heads: " + heads_counter + " Tails: " + tails_counter);
  
   // Check if total coin flips matches the required number of wins, exit function if it does not
   if ( heads_counter + tails_counter < wins ) {
      return;
   }

  //if the majority of total flips is heads, "Heads wins!" is displayed
  if (51 <= heads_counter / wins * 100 && tails_counter / wins * 100 <= 49 ) {
    placeholder.innerText = ("Heads Wins!");
    //if the majority of total flips is tails, "Tails wins!" is displayed
  } else if (51 <= tails_counter / wins * 100 && heads_counter / wins * 100 <= 49 ) {
    placeholder.innerText = ("Tails Wins!");
    //if flips are tied, "Tie!" is displayed
  } else if (tails_counter / wins * 100 == 50 && heads_counter / wins * 100 == 50 ) {
    placeholder.innerText = ("Tie!")
  }
  
  // This can come out of the if statement above now\
  // Reset counters
  heads_counter = 0;
  tails_counter = 0;
  
});
<p id="placeholder"></p>
<p id="coin_placeholder"></p>

<button id="reset">Reset</button>
<button id="coin">Coin</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...