JS: store selected values in array

Asked

Viewed 358 times

0

Good night. I am building a Javascript Bingo and want to store the numbers already drawn in an array to then consult it and avoid repetitions, but I don’t know how to do this. Can someone help, please?

The code is like this:

<script>
sorteados = [99]
function getBingo() {
    var bola = Math.floor(Math.random() * (75 - 1 + 1)) + 1;
    sorteados.push(bola);

    if (bola < 16) {
    letra = "B";
    }
    else {
        if (bola < 31) {
        letra = "I";
        }
        else {
            if (bola < 46) {
            letra = "N";
            }
            else {
                if (bola < 61) {
                letra = "G";
                }
                else {
                    if (bola < 76) {
                    letra = "O";
                    }
                }
            }
        }
    }

    document.getElementById("bolinha").innerHTML = "<span style='color:yellow'>" +letra +"</span>&nbsp;"+ bola;
    document.getElementById(bola).innerHTML = "<span style='color:red; background-color:white; border-radius:20px; padding:2px;'>" + bola + "</span><audio src='"+bola+".mp3' autoplay></audio>";
}
</script>

<script>document.write ("Números já sorteados: "+sorteados.join(", ")); </script>    

The game is running on https://monono.com.br/bingo

I accept suggestions for improvements.

Thank you

3 answers

0

Good night to you, Roberto. Just after you draw a number check if there is any identical number in the "drawn" array, if it exists, you run the getBingo() function again (this is called recursiveness, when you call the function within itself) and get another number, and do the same check, if it does not exist in the array, Voce adds it with the . push and continue with the rest of the function. Another tip: instead of using an if inside an Else, just use "Else if(condition){}". I really liked the layout of your application, congratulations. :)

function getBingo() {
  var bola = Math.floor(Math.random() * (75 - 1 + 1)) + 1;
  let indice;
  for (indice = 0; indice < 99; indice++) {
    if(sorteados[indice] == bola) {
      getBingo();
    }
  }
  sorteados.push(bola);
  console.log(...sorteados)
  if (bola < 16) {
    letra = "B";
  }
    else if (bola < 31){ 
      letra = "I";
    }
      else if (bola < 46) {
        letra = "N";
      }
        else if (bola < 61) {
          letra = "G";
        }
          else if (bola < 76) {
            letra = "O";
          }
}
  • This looks like an infinite loop. Have you tried running this function? Run it twice.

  • Yes, I made a mistake using that Isis within the for. Thank you! : D

  • Thanks, João, but what I can’t do is feed the array with the drawn balls.

0

The method find javascript seems to suit better for what you want.

//...
let sorteados = [99];

function getBingo() {

  let bola = Math.floor(Math.random() * (75 - 1 + 1)) + 1;

  /*
   O método find () retorna o valor do primeiro elemento na 
   matriz (Array) que satisfaz a função de teste fornecida. Caso contrário, 
   undefined é retornado
   */

  let existeBola = sorteados.find(item => item === bola);

  if (existeBola) { 
    getBingo(); // Tenta novamente
    return;
  }

  sorteados.push(bola);

  if (bola < 16) {
    letra = "B";
  } else {
    if (bola < 31) {
      letra = "I";
    } else {
      if (bola < 46) {
        letra = "N";
      } else {
        if (bola < 61) {
          letra = "G";
        } else {
          if (bola < 76) {
            letra = "O";
          }
        }
      }
    }
  }

  //...

}

By the way I strongly advise you to consider a withdrawal condition (stop repeating) if he does not find any drawn ball.

EX:

//...
let sorteados = [99];
let max_tentativas = 10; // Numero maximo aceitavel de tentativas;
let tentativas = 0;

function getBingo() {

  let bola = Math.floor(Math.random() * (75 - 1 + 1)) + 1;
  let existeBola = sorteados.find(item => item === bola);

  if (existeBola) {

    if (tentativas < max_tentativas) { // 

      getBingo(); // Tenta novamente

    } else {

      alert('Atingiu o numero maximo de tentativas');
      // ...
    }

    tentativas++;

    return; // Para tudo aqui
  }

  sorteados.push(bola);
  tentativas = 0; // Zera o numero de tentativas ja feitas

  if (bola < 16) {
    letra = "B";
  } else {
    if (bola < 31) {
      letra = "I";
    } else {
      if (bola < 46) {
        letra = "N";
      } else {
        if (bola < 61) {
          letra = "G";
        } else {
          if (bola < 76) {
            letra = "O";
          }
        }
      }
    }
  }

  //...

}
  • Thank you, Cristiano, I’ll test your suggestions.

0

It is better than seeing if you have drawn repeated and draw again is using a different algorithm, like the Fisher-Yates that randomizes the array, and then you just take elements from the beginning, with the guarantee that they are unique.

Example:

//função para baralhar os elementos do array
function shuffle(array) {
  let tamanho = array.length, temp, i;
  while (tamanho) {
    i = Math.floor(Math.random() * tamanho--);
    temp = array[tamanho];
    array[tamanho] = array[i];
    array[i] = temp;
  }
  return array;
}

const QTD_BOLAS = 75, LETRAS = "BINGO";
let bolas = []; //criar o array para as bolas
for (let i = 1;i <= QTD_BOLAS; ++i){
  bolas.push(i); //inserir as bolas disponiveis
}
shuffle(bolas);

document.getElementById("sortear").addEventListener("click", function(){
  let bolaSorteada = bolas.shift(); //retirar a primeira bola do array
  let bolasPorLetra = QTD_BOLAS / LETRAS.length; 
  let letra = LETRAS[Math.floor((bolaSorteada - 1) / bolasPorLetra)]; //obter a letra escolhida
  console.log("Sorteada - " + letra + bolaSorteada);
});
<button id="sortear">Sortear</button>

Note that replaces the ifs I had to find the words by a different logic. In this code, he assumes that there are X balls for each letter, dividing the amount of balls that exist by the amount of letters, which in this case will give 15 letters per ball. Which means that if you split the drawn ball by 15, give it the position of the letter to show, which makes the code more direct and less repetitive.

Example:

  • If the 10 ball comes out, dividing by 15 results in 0 giving you the first letter of the word "BINGO" the "B".
  • If the 20 ball comes out, dividing by 15 results in 1 which gives you the second letter of the word "BINGO" the "I".

If you want you can also prevent the user to draw balls if they have all left by checking the size of the array bolas before drawing, something like if (bolas.length > 0).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.