I'm trying to create a basic match the numbers game. I'm trying to make the value of remaining tries increase upon and wrong guess until it reaches 10 and then console.log('Game over').
I'm trying to use the ternary operator and arrow functions to do this. As it stands the value of my remaningTries let will not increase. Could anyone explain why? Thanks in advance.
let randomNum = Math.random()
let remainingTries = 0
randomNum = Math.floor(randomNum * 100)
console.log(randomNum)
gameOver = function() {
}
dragon = function() {
document.querySelector('.gF').addEventListener('submit', function(e) {
e.preventDefault()
let number = e.target.elements.guess.value
rt = (go) => go++
if (number == randomNum) {
let text = document.createElement('p')
text.textContent = `You won, congrats. The number was ${number}`
document.querySelector('.text').appendChild(text)
document.querySelector('.fish').setAttribute('disabled', true, '.disabled', true)
let again = document.createElement('button')
again.textContent = 'Another round?'
again.value = "refreshPage"
again.onclick = () => location.reload()
document.querySelector('.text').appendChild(again)
}
else if (number > randomNum) {
let lower = document.createElement('p')
lower.textContent = `The number is too high. (${number})`
document.querySelector('.text').appendChild(lower)
remainingTries < 10 ? rt(remainingTries) : console.log('Game over :(')
console.log(remainingTries)
} else if (number < randomNum) {
let higher = document.createElement('p')
higher.textContent = `The number is too low. (${number})`
document.querySelector('.text').appendChild(higher)
remainingTries <= 10 ? rt(remainingTries) : console.log('Game over :(')
console.log(remainingTries)
} else {
let other = document.createElement('p')
other.textContent = `Please enter a number. You entered ${number}.`
document.querySelector('.text').appendChild(other)
remainingTries <= 10 ? rt(remainingTries) : console.log('Game over :(')
}
})
}
dragon()
dumbass
27.2k4 gold badges43 silver badges77 bronze badges
asked Jul 12, 2018 at 12:32
Benjamin-Michael-Newton
73 bronze badges
1 Answer 1
You're setting remainingTries to 0 inside the submit handler, so it resets each time. Move let remainingTries = 0 outside the dragon function.
answered Jul 12, 2018 at 12:35
Alan Friedman
1,61010 silver badges7 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Benjamin-Michael-Newton
Thanks for the help. I've tried moving the let outside of the function but am still having the same issue. I've updated the code to reflect that. Is there something more which needs to be moved outside of the function also?
lang-js