Añadidos juegos
This commit is contained in:
55
adivina/script.js
Normal file
55
adivina/script.js
Normal file
@@ -0,0 +1,55 @@
|
||||
let randomNumber;
|
||||
let attemptsLeft = 7;
|
||||
|
||||
const guessInput = document.getElementById('guess-input');
|
||||
const guessBtn = document.getElementById('guess-btn');
|
||||
const restartBtn = document.getElementById('restart-btn');
|
||||
const infoDiv = document.getElementById('info');
|
||||
const attemptsSpan = document.getElementById('attempts-left');
|
||||
|
||||
function startGame() {
|
||||
randomNumber = Math.floor(Math.random() * 100) + 1;
|
||||
attemptsLeft = 7;
|
||||
attemptsSpan.textContent = attemptsLeft;
|
||||
infoDiv.textContent = '';
|
||||
guessInput.value = '';
|
||||
guessInput.disabled = false;
|
||||
guessBtn.disabled = false;
|
||||
restartBtn.classList.add('hidden');
|
||||
}
|
||||
|
||||
function checkGuess() {
|
||||
const guess = Number(guessInput.value);
|
||||
|
||||
if (guess < 1 || guess > 100 || isNaN(guess)) {
|
||||
infoDiv.textContent = "Por favor ingresa un número válido entre 1 y 100.";
|
||||
return;
|
||||
}
|
||||
|
||||
attemptsLeft--;
|
||||
attemptsSpan.textContent = attemptsLeft;
|
||||
|
||||
if (guess === randomNumber) {
|
||||
infoDiv.textContent = "¡Correcto! 🎉 Has adivinado el número.";
|
||||
endGame(true);
|
||||
} else if (attemptsLeft === 0) {
|
||||
infoDiv.textContent = `¡Oh no! Te quedaste sin intentos. El número era ${randomNumber}.`;
|
||||
endGame(false);
|
||||
} else if (guess < randomNumber) {
|
||||
infoDiv.textContent = "Demasiado bajo. Intenta nuevamente.";
|
||||
} else {
|
||||
infoDiv.textContent = "Demasiado alto. Intenta nuevamente.";
|
||||
}
|
||||
}
|
||||
|
||||
function endGame(won) {
|
||||
guessInput.disabled = true;
|
||||
guessBtn.disabled = true;
|
||||
restartBtn.classList.remove('hidden');
|
||||
}
|
||||
|
||||
guessBtn.onclick = checkGuess;
|
||||
restartBtn.onclick = startGame;
|
||||
guessInput.onkeydown = (e) => { if (e.key === "Enter") checkGuess(); };
|
||||
|
||||
startGame();
|
Reference in New Issue
Block a user