Increment number of attempts and decrement number of guesses remaining - javascript

I am new to JS, I want to the code to display number of attempts made, number of guesses remaining in this simple game. I have gotten lost in the code and I don't know what I am not doing right. The const remainingAttempts returns undefined yet I want to subtract number of attempts made from maxNumberOfAttempts.
const guessInput = document.getElementById("guess");
const submitButton = document.getElementById("submit");
const resetButton = document.getElementById("reset");
const messages = document.getElementsByClassName("message");
const tooHighMessage = document.getElementById("too-high");
const tooLowMessage = document.getElementById("too-low");
const maxGuessesMessage = document.getElementById("max-guesses");
const numberOfGuessesMessage = document.getElementById("number-of-guesses");
const correctMessage = document.getElementById("correct");
let targetNumber;
let attempts = 0;
let maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = "";
} else {
tooHighMessage.style.display = ""; //replaced else condition statement
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts === maxNumberOfAttempts) {
maxGuessesMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = "";
resetButton.style.display = "";
}
function hideAllMessages() {
/*replaced elementIndex <= messages.length to elementIndex < messages.length*/
for (let elementIndex = 0; elementIndex < messages.length; elementIndex++) {
messages[elementIndex].style.display = "none"; //removed [elementIndex]
}
// for (let message in messages.value) {
// //used for..in to iterate through the HTML collection
// message.style.display = "none";
// }
}
function setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabled = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = "none";
}
submitButton.addEventListener("click", checkGuess);
resetButton.addEventListener("click", setup);
setup();
main {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin: auto;
}
#guess {
width: 5em;
}
#reset {
margin: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="guess.css" rel="stylesheet" />
<title>Number Guesser</title>
</head>
<body>
<main>
<h1>Guessing Game</h1>
<p>
I'm thinking of a number from 1 to 99! Can you guess it in 5 tries or
less?
</p>
<div>
<input type="number" id="guess" min="1" max="99" />
<button id="submit">Submit Guess</button>
</div>
<div>
<p class="message" id="number-of-guesses"></p>
<p class="message" id="too-high">You guessed too high. Try again.</p>
<p class="message" id="too-low">You guessed too low. Try again.</p>
<p class="message" id="max-guesses">
You reached the max number of guesses
</p>
<p class="message" id="correct">
Congratulations, You guessed correctly! <br />
Would you like to play again?
</p>
</div>
<button id="reset">Reset</button>
</main>
<script src="guess.js"></script>
</body>
</html

just increment attempts as attempts++; below const remainingAttempts = maxNumberOfAttempts - attempts;. this should solve the no. of attempts part.

In setup(), when you reset the number of attempts, you should be setting it to 5: maxNumberOfAttempts = 5;
Additionally, in checkGuess(), you should:
Make sure to decrease the number of attempts with each guess. Add maxNumberOfAttempts-- at the top of the function.
At the bottom of if (guess !== targetNumber), you can replace the variable in the message from ${remainingAttempts} to ${maxNumberOfAttempts}
, since maxNumberOfAttempts is now keeping track of the amount of attempts remaining.
Lastly, the next if statement can check if the user is out of attempts with if (maxNumberOfAttempts === 0) {...}
This eliminates the need to use 3 different 'attempt' variables since you're resetting back to '5' at each instance of setup() anyway.

Related

Javascript Score Counter not increasing

I'm creating a simple card game that when a player wins the score should increase per win. But whenever I run this code it keeps resetting the score back to 0.
How can I make it so the scores keep increasing +1 if the corresponding player wins?
I've tried the below and it's unfortunately not working with what I have
$(document).ready(function(){
//storing our images, separating them out by suit. Orderimg from lowest to highest cards.
arrClubs=['2_of_clubs.png','3_of_clubs.png', '4_of_clubs.png', '5_of_clubs.png', '6_of_clubs.png', '7_of_clubs.png', '8_of_clubs.png', '9_of_clubs.png', '10_of_clubs.png', 'jack_of_clubs.png','queen_of_clubs.png', 'king_of_clubs.png', 'ace_of_clubs.png']
arrDiamonds=['2_of_diamonds.png','3_of_diamonds.png', '4_of_diamonds.png', '5_of_diamonds.png', '6_of_diamonds.png', '7_of_diamonds.png', '8_of_diamonds.png', '9_of_diamonds.png', '10_of_diamonds.png', 'jack_of_diamonds.png','queen_of_diamonds.png', 'king_of_diamonds.png', 'ace_of_diamonds.png']
arrHearts=['2_of_hearts.png','3_of_hearts.png', '4_of_hearts.png', '5_of_hearts.png', '6_of_hearts.png', '7_of_hearts.png', '8_of_hearts.png', '9_of_hearts.png', '10_of_hearts.png', 'jack_of_hearts.png','queen_of_hearts.png', 'king_of_hearts.png', 'ace_of_hearts.png']
arrSpades=['2_of_spades.png','3_of_spades.png', '4_of_spades.png', '5_of_spades.png', '6_of_spades.png', '7_of_spades.png', '8_of_spades.png', '9_of_spades.png', '10_of_spades.png', 'jack_of_spades.png','queen_of_spades.png', 'king_of_spades.png', 'ace_of_spades.png']
//console.log(arrClubs);
var player1Score = 0;
var player2Score = 0;
//get random suit. 1 = Clubs, 2 = Diamonds, 3 = Hearts, 4 = Spades.
var suitType = Math.ceil(Math.random() * 4)
var card = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
console.log(arrClubs[card])
selectedCard = arrClubs[card]
} else if(suitType == "2"){
console.log(arrDiamonds[card])
selectedCard = arrDiamonds[card]
} else if (suitType == "3"){
console.log(arrHearts[card])
selectedCard = arrHearts[card]
} else {
console.log(arrSpades[card])
selectedCard = arrSpades[card]
}
document.getElementById('p1Card').src = "./images/cards/" + selectedCard
//Player 2 Randomly Selected Card:
var suitType = Math.ceil(Math.random() * 4)
var card2 = Math.floor(Math.random() * 12)
var selectedCard //storing selected card
console.log(suitType)
if (suitType == "1"){
// console.log(arrClubs[card2])
selectedCard = arrClubs[card2]
} else if(suitType == "2"){
// console.log(arrDiamonds[card2])
selectedCard = arrDiamonds[card2]
} else if (suitType == "3"){
//console.log(arrHearts[card2])
selectedCard = arrHearts[card2]
} else {
//console.log(arrSpades[card2])
selectedCard = arrSpades[card2]
}
document.getElementById('p2Card').src = "./images/cards/" + selectedCard;
if (card < card2){
player2Score++;
document.getElementById('player2Results').value = player2Score;
// alert("Player 2 Wins")
} else if (card > card2){
player1Score++;
document.getElementById('player1Results').value = player1Score;
// alert("Player 1 wins")
} else {
// alert("TIE!")
console.log('Tie!');
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>War</title>
</head>
<body>
<div> Game</div>
<img src="./images/cards/black_joker.png" id="p1Card">
<img src="./images/cards/red_joker.png" id="p2Card">
<input type="text" readonly id="player1Results"/>
<input type="text" readonly id="player2Results"/>
<button id="play">Play</button>
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="./js/index.js"></script>
</body>
</html>
Most likely you are setting player1Score and player2Score back to 0 each time you run it. Here's a working example:
const runGame = (() => {
var player1Score = 0;
var player2Score = 0;
return () => {
const card = Math.random();
const card2 = Math.random();
if (card < card2){
player2Score++;
console.log('Player 2 Wins! Score: ' + player2Score);
document.getElementById('p2').value = player2Score;
} else if (card > card2){
player1Score++;
console.log('Player 1 Wins! Score: ' + player1Score);
document.getElementById('p1').value = player1Score;
} else {
console.log('Tie!');
}
}
})();
document.getElementById('play').addEventListener('click', runGame);
<div id="player1Results"></div>
<div id="player2Results"></div>
<input type="text" readonly id="p1"/>
<input type="text" readonly id="p2"/>
<button id="play">Play</button>

I am trying to push a value onto an array with .push(), but it stops pushing values once the array length reaches two

I'm trying to create a javascript calculator for The Odin Project. I finally felt like I was making a bit of progress, after headbutting my keyboard for hours, and then this weird bug arose.
In the function where I add event listeners to the operator buttons, I am trying to push the current operator (the last one which was clicked) on to an array which keeps track of the operator buttons which have been clicked ('newOperators.push(e.target.innerText)').
If I spam the operator button, it pushes on to the array just fine. But when I am trying to chain together a series of operations, the newOperators.push() method seems to quit after the array length reaches two.
To test, I added another dummy array and pushed letters onto it on using another push() method, which I put on the line above newOperators.push(), and that seems to work just fine. I've tried switching newOperators.push() to newOperators.unshift() and that has the same issue.
Losing my mind here, any help would be much appreciated!
Javascript:
let display = document.querySelector('.display');
let title = document.querySelector('.title');
let plus = document.querySelector('.plus');
let minus = document.querySelector('.minus');
let times = document.querySelector('.multiply');
let divide = document.querySelector('.divide');
let equal = document.querySelector('.equal');
let period = document.querySelector('.period');
let one = document.querySelector('.one');
let two = document.querySelector('.two');
let three = document.querySelector('.three');
let four = document.querySelector('.four');
let five = document.querySelector('.five');
let six = document.querySelector('.six');
let seven = document.querySelector('.seven');
let eight = document.querySelector('.eight');
let nine = document.querySelector('.nine');
let nought = document.querySelector('.nought');
let buttons = document.querySelectorAll('button');
let operators = document.querySelectorAll('.operator');
let numbers = document.querySelectorAll('.number');
let currentCalc = [];
let currentOp = '';
let firstNumber = 0;
let secondNumber = 0;
let thirdNumber = 0;
let firstStash = 0;
let secondStash = 0;
let total = 0;
let calculated = false;
let newOperators = [];
const add = function(a,b) {
return a + b;
};
const subtract = function(a,b) {
return a - b;
};
const multiply = function(a,b) {
return a * b
};
const division = function(a,b) {
return a / b
};
function operate(fnum,snum, op) {
if(op === '+') {
let sum = add(fnum,snum);
return sum;
} else if(op === '-') {
let sum = subtract(fnum,snum);
return sum;
} else if(op === 'x') {
let sum = multiply(fnum,snum);
return sum;
} else if(op === '/') {
let sum = division(fnum,snum);
return sum;
}
}
let fNumArr = [];
let sNumArr = [];
let tNumArr = [];
numbers.forEach((e) => {
e.addEventListener('click', (e) => {
console.log('numberFunc', newOperators)
if(newOperators.length < 1) {
fNumArr.push(e.target.innerText)
firstNumber = parseInt(fNumArr.join(''));
console.log('first',firstNumber);
display.textContent = firstNumber;
} else if( newOperators.length = 1) {
sNumArr.push(e.target.innerText);
secondNumber = parseInt(sNumArr.join(''));
console.log('second',secondNumber);
display.textContent = secondNumber;
} else if(newOperators.length > 1) {
tNumArr.push(e.target.innerText);
thirdNumber = parseInt(tNumArr.join(''));
console.log('third',thirdNumber);
display.textContent = thirdNumber;
}
})
})
operators.forEach((e) => {
e.addEventListener('click', (e) => {
console.log(currentOp)
newOperators.push(e.target.innerText);
console.log('topOfOp',newOperators)
display.innerText = '';
if(newOperators.length === 1) {
} else if(newOperators.length === 2) {
console.log(operate(firstNumber,secondNumber,newOperators[1]));
total = operate(firstNumber,secondNumber,newOperators[1]);
display.innerText = total;
firstNumber = total;
secondNumber = 0;
fNumArr = [];
fNumArr.push(total)
sNumArr = [];
}
})
})
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Caculator</title>
<link rel="stylesheet" href="styles.css">
<script src="./app.js" defer></script>
</head>
<body>
<h1 class="title">Calculator</h1>
<div class="container">
<div class="calculator">
<div class="display">This will print result</div>
<button class="clear">Clear</button>
<button class="plus operator">+</button>
<button class="minus operator">-</button>
<button class="multiply operator">x</button>
<button class="divide operator">/</button>
<button class="equal ">=</button>
<button class="one number">1</button>
<button class="two number">2</button>
<button class="three number">3</button>
<button class="four number">4</button>
<button class="five number">5</button>
<button class="six number">6</button>
<button class="seven number">7</button>
<button class="eight number">8</button>
<button class="nine number">9</button>
<button class="nought number">0</button>
<button class="period number">.</button>
</div>
</div>
</body>
</html>
In your numbers.forEach loop you made the mistake of:
if( newOperators.length = 1)
You should fix that.
Also, a little advice as you are starting out (I am also starting out WebDev):
You should name your variables clearly even of they are too long.
Refractor your code into functions and files for example make it so you pass in a callback to your event listeners and get rid of repetitive code. Remember keep it DRY (Don't Repeat Your code)

JS: Always get empty array?

I am trying to loop between two numbers and to return all prime numbers between them. In the first function isNumberPrime, I check if the number is prime and return 0 if it is not and 1 if it is prime. In the second function I am trying to loop between two numbers and to check if the flag is = 1, I push the number in the array. But, I can not see where the problem is?
function isNumberPrime(flag) {
let number;
let divider;
if ((number != 2 || number%2 === 0) || number === 1){
flag = 0; //not prime number 0
}
else {
divider = 3;
while(divider <= number/2){
if (number%divider === 0){
falg = 0;
break;
}
divider = divider + 2;
}
if(divider > number/2){
flag = 1;
}
}
return flag;
}
function looping(lowerNumber, higherNumber) {
let allPrimes = [];
for (let i = lowerNumber; i <= higherNumber; i++) {
isNumberPrime(i);
if (isNumberPrime(i) == 1){
allPrimes.push[i];
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = input2.value;
let output = document.getElementById("output");
output.innerText = 'All primes between ' + lowerNumber +' and ' + higherNumber + ' are: [' + looping(lowerNumber, higherNumber) + ']';
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<div>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</div>
<script src="primeNumber.js"></script>
</body>
</html>
I have identified and fixed below issues with your code.
Issues
In isNumberPrime function, you expect flag as a function prameter. Thats wrong. The parameter should be the number
There is a typo error flag was misspelled as falg inside isNumberPrime
The condition number != 2 will assume all the numbers other than 2 as not prime. So removed that.
Also the syntax for Array.push is wrong. it should be allPrimes.push(i) and not allPrimes.push[i]
I have made the lower boundary and upper boundary as the max value between input value and 0 to avoid negative numbers.
Also I have used Math.ceil() in the starting number to take number greater than or equal to input and Math.floor() in ending number to take number less than or equal to input in case of decimals.
I have updated looping function call as looping(+lowerNumber, +higherNumber), to make the parameter number. The value fetched from an input will be string by default.
If you want the element to be inside the form, you can wrap the elements inide a form. But a button inside a form will be treated as a submit button. So you have to explicitly make the button type="button" or you have to preventDefault on form submit. I went for the second approach in the updated fiddle.
Working Fiddle
function isNumberPrime(number) {
let flag;
let divider;
// Wrong: number != 2 will assume all the numbers other than 2 as not prime
if (number % 2 === 0 || number === 1) {
flag = 0; //not prime number 0
}
else {
divider = 3;
while (divider <= number / 2) {
if (number % divider === 0) {
flag = 0; // Typo error fix
break;
}
divider = divider + 2;
}
if (divider > number / 2) {
flag = 1;
}
}
return flag;
}
function looping(lowerNumber, higherNumber) {
let allPrimes = [];
const lowerBoundary = Math.ceil(Math.max(lowerNumber, 0));
const higherBoundary = Math.floor(Math.max(higherNumber, 0));
for (let i = lowerBoundary; i <= higherBoundary; i++) {
const isPrime = isNumberPrime(i);
if (isPrime == 1) {
// Wrong syntax of `Array.push` fixed
allPrimes.push(i);
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = +input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = +input2.value;
let output = document.getElementById("output");
if (higherNumber > lowerNumber) {
output.innerText = 'All primes between ' + lowerNumber + ' and ' + higherNumber + ' are: [' + looping(lowerNumber, higherNumber) + ']';
} else {
output.innerText = 'Lower boundary should be smaller than the higher';
}
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers);
function submitForm(event) {
event.preventDefault();
}
const form = document.querySelector('form');
form.addEventListener('submit', submitForm);
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<form>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</form>
You have some problems as follows:
First push methods are used in wrong way and the right way is
allPrimes.push(i)
Second you are using number while you didn't initialize the variable,
so initialize it let number = flag;
Third you need to check number === 2 instead of number != 2.
lowerNumber and higherNumber is string, so convert it to number by + operation
Here is working sample:
function isNumberPrime(flag) {
let number = flag;
let divider;
if ((number === 2 || number%2 === 0) || number === 1){
flag = 0; //not prime number 0
}
else {
divider = 3;
while(divider <= number/2){
if (number%divider === 0){
falg = 0;
break;
}
divider = divider + 2;
}
if(divider > number/2){
flag = 1;
}
}
return flag;
}
function looping(lowerNumber, higherNumber) {
let allPrimes = [];
debugger
for (let i = +lowerNumber; i <= +higherNumber; i++) {
if (isNumberPrime(i) == 1){
allPrimes.push(i);
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = input2.value;
let output = document.getElementById("output");
output.innerText = 'All primes between ' + lowerNumber +' and ' + higherNumber + ' are: [' + looping(lowerNumber, higherNumber) + ']';
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<div>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</div>
<script src="primeNumber.js"></script>
</body>
</html>
isNumberPrime() algorithm was incorrect, also you had it take a flag instead of number argument.
looing() used push[i] used instead of push(i).
enterNumbers() passed two strings to looping() instead of integers; aggressive type checks in logging().
function isNumberPrime(number) {
if(number < 2) return false;
for(let i = 2; i <= number / 2; i++) {
if(!(number % i)) return false;
}
return true;
}
function looping(lowerNumber, higherNumber) {
if(lowerNumber == "" || !Number.isInteger(lowerNumber) || lowerNumber < 0 || higherNumber == "" || !Number.isInteger(higherNumber) || higherNumber < 0) {
console.error("looping is called with invalid arguments");
return [];
}
let allPrimes = [];
for(let i = lowerNumber; i <= higherNumber; i++) {
if(isNumberPrime(i)) {
allPrimes.push(i);
}
}
return allPrimes;
}
function enterNumbers() {
let input1 = document.getElementById("firstNumber");
let lowerNumber = input1.value;
let input2 = document.getElementById("secondNumber");
let higherNumber = input2.value;
let output = document.getElementById("output");
output.innerText = 'All primes between ' + lowerNumber +' and ' + higherNumber + ' are: [' + looping(Number(lowerNumber), Number(higherNumber)) + ']';
}
const button = document.querySelector('button');
button.addEventListener('click', enterNumbers)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Prime numbers</h1>
<p>Type first number and second number:</p>
<div>
<input id="firstNumber" type="number" size="24" />
<input id="secondNumber" type="number" size="24" />
<button>Show primes</button> <br />
<span id="output"></span>
</div>
<script src="primeNumber.js"></script>
</body>
</html>
You have a few issues here:
In your isNumberPrime function:
You are returning flag while it is also the input param of the function. and you are checking number while it was only declared but never assigned any value.
There is an issue with the condition which is why every number you will input will result in flag being equals to 0. So instead of using and OR operator you should use AND.
You have a typo in the else statement falg instead of flag.
So it should look like this:
function isNumberPrime(number) {
//switched between the flag and number
let flag;
let divider;
if (
(number != 2 && number % 2 === 0) || //changed || to &&
number === 1
) {
flag = 0;
} else {
divider = 3;
while (divider <= number / 2) {
if (number % divider === 0) {
flag = 0; //falg to flag
break;
}
divider = divider + 2;
}
if (divider > number / 2) {
flag = 1;
}
}
return flag;
}
In the looping function:
You used square brackets push[i] when pushing the values into the array. You need to use round brackets push(i)

Javascript textcontent is not displaying anything

I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.

How to keep track of attempts in a JavaScript guess-the-number game

My goal is to keep track of the attempts made in the game. This is my code so far.
I have edited this post to understand difference between count = 0 and count = 1.
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.getElementById("attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let count = 1
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value;
if (guessValue < randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too low";
count++
} else if (guessValue > randomNumber) {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "Your guess is too high";
count++
} else {
attempt.innerHTML = "Attempt n: " + count
result.innerHTML = "You guessed correctly in " + count++ + "
attempts";
}
}
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Guess the number</title>
</head>
<body>
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
<script src="script.js"></script>
</body>
I can't understand why attempt.innerHTML won't work. It doesn't show up on the page like "result" does.
You are declaring a global attempt variable outside the function which holds the html element and then you are declaring a local attempt variable in your function which will always be 1.
Declare a counter outside the function and then increment it everytime your function is called.
Also in your answer you are only incrementing the count and updating the attempt.innerHTML inside your if else block under specific conditions. You want to move this code outside of the if else block so it updates on every guess.
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
let attempt = document.querySelector(".attempt")
let attemptCounter = 0
button.addEventListener("click", checkGuess)
function checkGuess() {
let guessValue = document.getElementById("guess").value
// Increment Attempts by 1
attemptCounter++
attempt.innerHTML = "Attempt n: " + attemptCounter
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
}
<h1>GUESS A NUMBER:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess">
<input type="submit" value="SUBMIT" id="button">
<div>
<p class="attempt"></p>
<p class="result"></p>
</div>
This is a simplified function version of setting up multiple number guessing games on a single page. All game related data is kept in dataset attributes num and try of the associated input field.
function guess(id){
let el = document.getElementById(id);
el.dataset.try=0;
el.dataset.num = Math.floor(Math.random() * 30) + 1;
el.onchange=()=>el.nextElementSibling.innerHTML =
"Attempt "+(++el.dataset.try)+":<br>Your guess is "
+["too low.","correct!","too high."]
[Math.sign(el.value-el.dataset.num)+1]
}
guess('guess1');guess('guess2');
<h1>GUESS SOME NUMBERS:</h1>
<p>Enter a guess:</p>
<input type="number" id="guess1">
<div></div>
<p>Enter another guess:</p>
<input type="number" id="guess2">
<div></div>
You're redefining the attempt variable in a local scope as an integer which is overriding the reference to the document element. When you use "innerHTML" your using it on the localized attempt (an integer not the document element)
Try this:
let randomNumber = Math.floor(Math.random() * 30) + 1
let result = document.querySelector(".result")
let attempt = document.querySelector(".attempt")
let button = document.getElementById("button")
let guess = document.getElementById("guess")
button.addEventListener("click", checkGuess)
let attemptCount = 1 // Renamed this from attempt and moved to global scope
function checkGuess() {
let guessValue = document.getElementById("guess").value
attempt.innerHTML = "Attempt n: " + attemptCount
if (guessValue < randomNumber) {
result.innerHTML = "Your guess is too low";
} else if (guessValue > randomNumber) {
result.innerHTML = "Your guess is too high";
} else {
result.innerHTML = "You guessed correctly";
}
attemptCount++;
}

Categories