How to make a random button that a number is 'a prize' and another 'an earthquake' without both values ever matching

0

Hi, I'm good at this, I do not fall into how to make a button of a prize, another a disaster (earthquake), and it would be from 1 to 5 randomly, it is for a game, both can not be repeated, Let randomly the two buttons never give the same value. Thanks

let buttons = document.getElementsByTagName('button');
let price = Math.floor(Math.random() * buttons.length) + 1;
let earthquake = price;

while(price == earthquake){
  earthquake = Math.floor(Math.random() * buttons.length) + 1;
}

let premioBoton = document.getElementsByTagName('button')[price - 1];
let earthquakeBoton = document.getElementsByTagName('button')[earthquake - 1];

premioBoton.onclick = function(){
  alert('Ha ganado un premio de $ 10.000');
};

earthquakeBoton.onclick = function(){
  alert('Ha habido un terremoto')
};
let buttons = document.getElementsByTagName('button');
let price = Math.floor(Math.random() * buttons.length) + 1;
let earthquake = price;

// if (opener === null) {
//   alert('Pasa primero por el panel generl')
//   location.assign("../index.html");
// }

while(price == earthquake){
  earthquake = Math.floor(Math.random() * buttons.length) + 1;
}
console.log('earthquake is in ' + earthquake);
console.log('price is in ' + price);
    
asked by francisco dwq 21.01.2018 в 19:10
source

1 answer

0

I could validate after obtaining the prize that is not repeated with earthquake using a structure while

let buttons = document.querySelectorAll('button');
let price = Math.floor(Math.random() * buttons.length) + 1;
let earthquake = price; // Igualamos
// Mientras sea igual ejecutamos nuevamente el random
while(earthquake=== price){
    earthquake = Math.floor(Math.random() * buttons.length) + 1;

}

console.log(' price is in ' + price);
console.log(' earthquake is in ' + earthquake);

//Iteramos sobre los botones
buttons.forEach(function(el) {
    // agregamos el listener, para el evento click
    el.addEventListener('click',function(e){
        // si es el valor generado price igual al atributo de
        // data-num del botón es premiado
        if(this.getAttribute('data-num') == price){
            alert("Premiado");
        }
        // si es el valor generado earthquake igual al atributo de
        // data-num del botón es terremoto
        if(this.getAttribute('data-num') == earthquake){
            alert("Terremoto");
        }
    });
});
<h1>¡Bienvenido!</h1>

<p>Realiza un sorteo cada hora y podrás ganar 10.000$... ¡o un terrible terremoto!</p>

<h2>¿A qué número apuestas?</h2>

<button data-num="1">1</button>
<button data-num="2">2</button>
<button data-num="3">3</button>
<button data-num="4">4</button>
<button data-num="5">5</button>


<div id="alerta"></div>
    
answered by 21.01.2018 в 19:20