-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.
Cmte Cardinal... Friend, so simple to resolve and I did not think about it! Thank you so much for your help!
– Yne-Dev