How to generate a random number only once? (Javascript)

Asked

Viewed 37 times

-1

Hello! I’m trying to create a "little game" where I get a random number between 1 and 100 and the user has to try to hit, if he kicks up, print an msg for him to try a lower number and vice versa. The problem is that each time the user tries to hit the number (by clicking on the button) the system generates a new random number! So the generated number does not remain the same until the user gets it right. I’d like to know how to generate a random number only once. Follow the Cód:

(JS)

const playGame = () =>{
    //1º. Pegar as classes do html.
    const form = document.querySelector('.forms');
    const inputNumber = document.querySelector('.input-number');
    const button = document.querySelector('.btn');
    const result = document.querySelector('.print-results')
    const msgSistem = document.querySelector('.msg-sistem');

    //2º. Parar o evento de submit do button.
    const stopEventSubmit = (e) =>{
        e.preventDefault();

        //3º. Gerar um num aleatório entre 1 e 100.
        const number = Math.floor(Math.random() * 100) + 1;
        console.log(`Sistema: ${number}`);

        //4º. Pegar o valor do input.
        const valueImput = Number(inputNumber.value);
        console.log(valueImput);

        //5º. Criar um <p> e imprimir o núm escolhido pelo usuário.
        const p = document.createElement('p');
        result.appendChild(p);
        p.innerText += `Nº escolhido: ${valueImput}`;

        if(valueImput === number){
            msgSistem.classList.add('green');
            msgSistem.classList.remove('red');
            msgSistem.innerText = 'Parabéns, você acertou!'
        }
        if(valueImput > number){
            msgSistem.classList.add('red');
            msgSistem.classList.add('remove');
            msgSistem.innerText = 'Tente um número mais baixo'
        }
        if(valueImput < number){
            msgSistem.classList.add('red');
            msgSistem.classList.add('remove');
            msgSistem.innerText = 'Tente um número mais alto'
        }
    }
    form.addEventListener('submit', stopEventSubmit);
}
playGame();

(HTML)

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Aprendendo JS</title>
    <style>
        .red{
            background-color: red;
        }
        .green{
            background-color: chartreuse;
        }
    </style>
</head>
<body>
    
<h1>Testes</h1>
    <form action="" class="forms">
        <label>
            Digite um número de 0 a 100:
            <input class="input-number" type="number" placeholder="Ex: 28">
        </label>
        <button class="btn">ENVIAR</button>
    </form>

    <div class="print-results"></div>
    <h4 class="msg-sistem"></h4>

    <script src="/script.js" defer></script>
</body>

NOTE: I am a beginner.

1 answer

0

This is a question of where the code is located. When you submit the form, it executes everything inside stopEventSubmit, then every time you click on the button, a new random number will be generated. You can sort simply by placing const number = Math.floor(Math.random() * 100) + 1; out of function stopEventSubmit.

Would look like this:

const playGame = () =>{
    //1º. Pegar as classes do html.
    const form = document.querySelector('.forms');
    const inputNumber = document.querySelector('.input-number');
    const button = document.querySelector('.btn');
    const result = document.querySelector('.print-results')
    const msgSistem = document.querySelector('.msg-sistem');

    //3º. Gerar um num aleatório entre 1 e 100 apenas uma vez.
    const number = Math.floor(Math.random() * 100) + 1;
    console.log(`Sistema: ${number}`);

    //2º. Parar o evento de submit do button.
    const stopEventSubmit = (e) =>{
        e.preventDefault();

        //4º. Pegar o valor do input.
        const valueImput = Number(inputNumber.value);
        console.log(valueImput);

        //5º. Criar um <p> e imprimir o núm escolhido pelo usuário.
        const p = document.createElement('p');
        result.appendChild(p);
        p.innerText += `Nº escolhido: ${valueImput}`;

        if(valueImput === number){
            msgSistem.classList.add('green');
            msgSistem.classList.remove('red');
            msgSistem.innerText = 'Parabéns, você acertou!'
        }
        if(valueImput > number){
            msgSistem.classList.add('red');
            msgSistem.classList.add('remove');
            msgSistem.innerText = 'Tente um número mais baixo'
        }
        if(valueImput < number){
            msgSistem.classList.add('red');
            msgSistem.classList.add('remove');
            msgSistem.innerText = 'Tente um número mais alto'
        }
    }
    form.addEventListener('submit', stopEventSubmit);
}
playGame();
<h1>Testes</h1>
<form action="" class="forms">
    <label>
        Digite um número de 0 a 100:
        <input class="input-number" type="number" placeholder="Ex: 28">
    </label>
    <button class="btn">ENVIAR</button>
</form>

<div class="print-results"></div>
<h4 class="msg-sistem"></h4>

Now the random number will be generated only once.

  • Cmte Cardinal... Friend, so simple to resolve and I did not think about it! Thank you so much for your help!

Browser other questions tagged

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