Problem with simple guessing game in JavaScript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
Improve this question
I'm trying to make a simple guessing game in JavaScript, but when I click submit button - nothing happens. This is a code from a book, so I think it should work. Do you have any idea what is wrong with it?
Below is the HTML and JS code. I have this two files in one folder.
I would be greatful for any ideas.
var randomNumber = Math.floor(Math.random() * 100) + 1;
const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const guessSubmit = document.querySelector('guessSubmit');
const guessField = document.querySelector('guessField');
let guessCount = 1;
let resetButton;
function checkGuess() {
var userGuess = Number(guessField.value);
if (guessCount === 1) {
guesses.textContent = 'Poprzednio wprowadzone liczby: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Gratulacje! Zgadłeś!';
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = '';
setGameOver();
} else if (guessCount === 10) {
lastResult.textContent = 'Koniec gry!';
setGameOver();
} else {
lastResult.textContent = 'Żle!';
lastResult.style.backgroundColor = 'red';
if (userGuess < randomNumber) {
lowOrHi.textContent = 'Zbyt mała liczba!';
} else if (userGuess > randomNumber) {
lowOrHi.textContent = 'Zbyt duża liczba!';
}
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Rozpocznij nową grę!';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas p');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
guessField.focus();
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
}
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Zgadnij liczbę</title>
</head>
<body>
<h1>Zgadnij liczbę</h1>
<p>Program wybrał liczbę od 1 do 100. Sprawdź, czy uda Ci się ją odgadnąć w mniej niż 10 prób. Otrzymasz odpowiedzi, czy zgadywana przez Ciebie wartość jest zbyt duża lub zbyt mała.</p>
<div class="form">
<label for="guessField">Wprowadź liczbę: </label>
<input type="text" id="guessField" class="guessField">
<input type="submit" value="Wyślij odpowiedź" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
<<script src="zgadywanie.js"></script>
</body>
</html>

You are trying to get elements by type selector, but in HTML you haven't these types. Instead, try class selector.
const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');

Related

How to make value become 0 in textbox?

I am making a dice game where you roll dice. When you roll a number that number adds to your total score. But when you roll a 1 you lose your total score and it switches to the other player. You can also hold to switch player.
As it is right now it become 0 after getting a 1 the first time. My problem is that when you switch back to the original starter player the score that was there before comes back. Like it does not stay the value of 0 but only looks like it.
var swithcing = false;
var current1 = 0;
var total1 = 0;
var current2 = 0;
var total2 = 0;
function roll() {
var randomnumber = Math.floor(Math.random() * 6) + 1;
var player1score = document.querySelector('.player1total');
var player1curent = document.querySelector('.player1');
var player2score = document.querySelector('.player2total')
var player2curent = document.querySelector('.player2')
if (randomnumber == 1) {
swithcing = !swithcing;
player1score.innerHTML = 0;
player1curent.innerHTML = 0;
player2curent.innerHTML = 0;
}
if (randomnumber == 1 && swithcing == false) {
player2score.innerHTML = 0;
}
if (swithcing == true) {
current2 += randomnumber;
player2score.innerHTML = current2;
player2curent.innerHTML = randomnumber;
}
if (swithcing == false) {
current1 += randomnumber;
player1score.innerHTML = current1;
player1curent.innerHTML = randomnumber;
}
}
function hold() {
swithcing = !swithcing;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />
I think your code should look something like this
let switching = false;
let current1 = 0;
let total1 = 0;
let current2 = 0;
let total2 = 0;
let randomnumber = 0
const player1score = document.querySelector('.player1total');
const player1current = document.querySelector('.player1');
const player2score = document.querySelector('.player2total');
const player2current = document.querySelector('.player2');
function roll() {
randomnumber = Math.floor(Math.random() * 6) + 1;
//console.log(randomnumber);
//logic for normal rolls
if(randomnumber > 1){
if(switching==true){
current2=randomnumber;//set to number rolled
total2+=randomnumber;//sum to total score
} else {
current1=randomnumber;//set to number rolled
total1+=randomnumber;//sum to total score
}
}
//logic if player loses
if (randomnumber == 1) {
//switch
switching = !switching;
//if switches to player 2
current1=0;//reset
current2=0;//reset
if(switching==true){
//console.log("Player 2 selected");
total2+=total1//total becomes player 1 previous total
total1=0;//player 1 total resets
} else {
//console.log("Player 1 selected");
total1+=total2//total becomes player 2 previous total
total2=0;//player 2 total resets
}
}
player1score.textContent = total1;
player1current.textContent = current1;
player2current.textContent = current2;
player2score.textContent = total2;
}
function hold() {
switching = !switching;
player1score.textContent = total1;
player1current.textContent = 0;
player2current.textContent = 0;
player2score.textContent = total2;
}
<h1>Player 1</h1>
<h2 class="player1"></h2>
<h3 class="player1total"></h3>
<h1>Player 2</h1>
<h2 class="player2"></h2>
<h3 class="player2total"></h3>
<input type="button" onclick="roll()" value="Roll Dice!" />
<input type="button" onclick="hold()" value="Hold!" />

Random math game in JavaScript

I'm trying to make a math game in JS like this:
Easy level: This level contains 5 questions contains three digits for example 1 + 2;
2 marks are calculated for each question. If the student gets a 7, he is congratulated by a moving animation and music of success, and if he does not get a passing mark, the sound of loss is heard.
and I want to show what's the score he got from correct answers.
like this sample output:
you lose and got 0/5, something like that.
I already do that and I did not get the output as I want, I think I have errors in the if statement.
This is my HTML code
<section>
<h1>Math Addition Quiz Game</h1>
<div class="centerdiv">
<div class="insertBox">
<div class="box1">
<p id="v1"> </p>
<p class="text-center justify-content-center" id="final"></p>
<p class="text-center justify-content-center" id="final1"></p>
</div>
<div class="box1">
<p id="operator">+</p>
</div>
<div class="box1">
<p type="text" id="v2"></p>
</div>
</div>
<div class="middleBox">
<input type="text" id="answ">
</div>
<div class="sentBox">
<button onclick="jsGame()" class="mb-3" id="submit"> Check Answer</button> <br>
<button onclick="Restart()" class="mb-3"id="restart" > Restart </button>
<button onclick="Main()" id="Main"> Back To Main Menu</button>
</div>
</div>
</section>
This is Java Script Code
let n1 = Math.floor(Math.random()*10+1)
let n2 = Math.floor(Math.random() * 10 + 1)
document.getElementById('v1').innerHTML = n1;
document.getElementById('v2').innerHTML = n2;
var count = 0;
var wrong = 0;
var score = 0;
document.getElementById('v1').value = n1;
document.getElementById('v2').value = n2;
document.getElementById('restart').style.visibility = "hidden";
document.getElementById('Main').style.visibility = "hidden";
let ans = n1 + n2;
const jsGame = () => {
var usera = document.getElementById('answ').value;
if (usera == ans) {
audio.play();
wrong = 0; //wrong answers
score++;
count++; //correct answers
GenerateRandom();
}
else {
//sad.play();
wrong = wrong+1;
document.getElementById('answ').value = " ";
alert(`Correct Answer is ${ans} Try Again. `);
}
if (score == 5) {
level.play();
Visible();
var s = 10 - wrong;
if (s >= 5) {
level.play();
document.getElementById("final").innerHTML = `you win and got ${s}/10`
document.getElementsById('submit').style.visibility = "hidden";
document.getElementById('operator').style.visibility = "hidden";
}else{
sad.play();
document.getElementById('answ').value = " ";
document.getElementById("final").innerHTML = `you lose and got ${wrong}/10`
}
}
};
function GenerateRandom() {
document.getElementById('answ').value = " ";
n1 = Math.floor(Math.random() * 10 + 1)
n2 = Math.floor(Math.random() * 10 + 1)
document.getElementById('v1').innerHTML = n1;
document.getElementById('v2').innerHTML = n2;
document.getElementById('v1').value = n1;
document.getElementById('v2').value = n2;
ans = n1 + n2;
}
function Restart() {
window. location. reload();
}
function Main() {
location.href="./game.html";
}
var audio = new Audio('../Congratulations-sound.mp3');
var sad = new Audio('../sad.wav');
var level = new Audio('../level.wav')
function Visible() {
document.getElementById('v1').style.visibility = "hidden";
document.getElementById('v2').style.visibility = "hidden";
document.getElementById('answ').style.visibility = "hidden";
document.getElementById('submit').style.visibility = "hidden";
document.getElementById('operator').style.visibility = "hidden";
document.getElementById('restart').style.visibility = "visible";
document.getElementById('Main').style.visibility = "visible";
}
I hope you can help me, and any modification or better addition to the code please help me. Thank you.
This is a Demo of what I did.
demo in github
repo in Github of all codes

Global variable in number guessing game

I'm trying to make the standard number guessing game that MDN provides in their JS tutorial. I tried tweaking it a bit making different functions for the different scenarios.
It seems the global variable var userGuess = parseInt(guessField.value) is not working as your previous guess always comes up as NaN.
Also when the game resets the showWin() and showLoss() functions work but not the showError() function.
I am very new to JS and coding in general so there is most likely a silly mistake somewhere, if anyone could help me on this problem, that would be greatly appreciated!
var randNum = Math.floor(Math.random() * 100) + 1;
var guessField = document.querySelector('.guessField');
var guessSubmit = document.querySelector('.guessSubmit');
var guesses = document.querySelector('.guesses');
var lastResult = document.querySelector('.lastResult');
var lowOrHi = document.querySelector('.lowOrHi');
var guessCount = 1;
var resetButton;
var userGuess = parseInt(guessField.value);
function checkGuess() {
if(guessCount === 1) {
guesses.textContent = "Previous Guesses: ";
}
guesses.textContent += userGuess + ' ';
if(userGuess === randNum) {
showWin();
} else if(guessCount === 10) {
showLoss();
} else {
showError();
}
guessCount++;
guessField.value = '';
guessField.focus();
}
guessSubmit.addEventListener('click', checkGuess);
function showWin() {
lastResult.textContent = 'You won nice job schmuck';
lastResult.style.backgroundColor = 'green';
gameOver();
}
function showError() {
lastResult.textContent = 'Sorry, wrong guess';
if(userGuess > randNum) {
lowOrHi.textContent = 'Your guess was too high';
} else if(userGuess < randNum) {
lowOrHi.textContent = 'Your guess was too low';
}
}
function showLoss() {
lastResult.textContent = 'You lost, you schmuck';
lastResult.style.backgroundColor = 'red';
gameOver();
}
function gameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'New Game';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
function resetGame() {
guessCount = 1;
var resetParas = document.querySelectorAll('.resultParas');
for(i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
resetButton.parentNode.removeChild(resetButton);
lastResult.style.backgroundColor = 'white';
randNum = Math.floor(Math.random() * 100) + 1;
}
<h1>Guessing Game</h1>
<p>Type in a number between 1 and 100 and I will tell you if it is too high or low.</p>
<form>
<label for="guessField">Enter a guess: </label>
<input type="text" id="guessField" class="guessField"/>
<input type="button" value="Submit Guess" class="guessSubmit"/>
</form>
<div class='resultParas'>
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
In your script, you call
parseInt(guessField.value) // effectively that is parseInt("") when it's empty
Calling parseInt() with an empty string returns NaN;
MDN in their example use:
var userGuess = Number(guessField.value);
Number("") returns a 0 number value.
You would also need to update the value of userGuess every time you call checkGuess(). So the alterations you need are:
// ... code
var userGuess = Number(guessField.value);
// ... the rest of code
function checkGuess() {
userGuess = Number(guessField.value)
// ... rest of code
}
// rest of code
You don't have to use Number() of course, you could also do some other condition checking, but Number() is an elegant way of accepting either numbers or an empty string.
UPDATE
New jsbin here.
For the resetGame() part: you were selecting the .resultParas like:
var resetParas = document.querySelectorAll('.resultParas');
Then you iterated over the results of that and replaced the .textContent of those elements. But those were not simple text nodes, they were parapgraph nodes with text nodes inside them. I changed it to:
var resetParas = document.querySelector('.resultParas').children;
It should be working! I've put some comments in the jsfiddle for more explanation.

what's wrong with this javascript script.?

I am trying to learn javascript by following this exercise from MDN website Learn JavaScript
here is my final code for the game.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Number guessing game</title>
<style>
html {
font-family: sans-serif;
}
body {
width: 50%;
max-width: 800px;
min-width: 480px;
margin: 0 auto;
}
.lastResult {
color: white;
padding: 3px;
}
</style>
</head>
<body>
<h1>Number guessing game</h1>
<p>We have selected a random number between 1 and 100. See if you can guess it in 10 turns or less. We'll tell you if your guess was too high or too low.</p>
<div class="form">
<label for="guessField">Enter a guess:</label>
<input type="text" id="guessField" class="guessField" autofocus>
<input type="submit" value="Submit guess" class="guessSubmit">
</div>
<div class="resultParas">
<p class="guesses"></p>
<p class="lastResult"></p>
<p class="lowOrHi"></p>
</div>
</body>
<script>
// Your JavaScript goes here
var randomNumber = Math.floor(Math.random() * 100) + 1;
var guesses = document.querySelector(".guesses");
var lastResult = document.querySelector(".lastResult");
var lowOrHi = document.querySelector(".lowOrHi");
var guessField = document.querySelector(".guessField");
var guessSubmit = document.querySelector(".guessSubmit");
var test; //used for creating new reset button
var count = 1; // counter for counting user input
function checkGuess() {
//alert('checkGuess is called');
var value = Number(guessField.value);
if (count === 1) {
guesses.textContent = "Previous guesses :"
}
guesses.textContent += value + ' ';
if (value === randomNumber) {
lastResult.textContent = "congratulation u successfully guessed the number";
lastResult.style.backgroundColor = "green";
lowOrHi.textContent = "";
left = 1;
setGameOver();
} else if (count === 10) {
lastResult.textContent = "game over"
lastResult.style.backgroundColor = "red";
left = 1;
setGameOver();
} else {
lastResult.textContent = "WRONG";
lastResult.style.backgroundColor = "red";
if (value < randomNumber) {
lowOrHi.textContent = "too low";
} else {
lowOrHi.textContent = "too high";
}
}
count++;
guessField.value = '';
}
guessSubmit.addEventListener("click", checkGuess);
function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
test = document.createElement('button');
test.textContent = "restart game";
document.body.appendChild(test);
test.addEventListener('click', resetGame);
}
function resetGame() {
count = 1;
var resetParas = document.querySelectorAll('.resultParas');
for (var i = 0; i < resetParas.length; i++) {
resetParas[i].textContent = '';
}
guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = '';
lastResult.style.backgroundColor = 'white';
randomNumber = Math.floor(Math.random() * 100) + 1;
test.parentNode.removeChild(test);
}
</script>
</html>
But when i try to run the game and use the reset game button to restart the game then i am not able to manipulate guesses,lastResult and lowOrHi elements using textContent and backgroundColor properties.
Your blanking out everything inside .resultParas.. And this will include all you <p> tags. IOW: after doing that they have disappeared from the DOM, you can see this say in chrome inspector that .resultPara's after clicking reset game is now blank, and all your p tags have gone.
I think what you really want to do, is blank out the children (the p tags)..
You don't need querySelectorAll either, as in your case there is only the one.
var resetParas = document.querySelector('.resultParas');
for(var i = 0 ; i < resetParas.children.length ; i++) {
resetParas.children[i].textContent = '';
}

JavaScript - Calling a function again is not working

This is kind of hard to explain, but I want to make it so when someone gets the answer right to a question, they get a new question. I have tried calling the function more than once but that doesn't work. I have tried many things like making cookies, but I can't get it to work. Here is my current code:
//Getting elements
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox");
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var quesNum = document.getElementById("quesNum");
//Variables
var num1 = Math.floor((Math.random() * 10) + 1);
var num2 = Math.floor((Math.random() * 10) + 1);
var ans = num1 + num2;
var questionNumber = 1;
quesNum.innerHTML = questionNumber;
//Check if answer is correct or not
function checkAns() {
if(ansBox.value == ans) {
isCorrect.innerHTML = "Good job! Your answer was correct!";
questionNumber++;
quesNum.innerHTML = questionNumber;
ques.innerHTML = " ";
question();
//Call if statement when questionNumber = 10 and disable submitBtn and ansBox
if(questionNumber == 10) {
isCorrect.innerHTML = "Congratulations! You have completed all 10 questions! Refresh the page to do more!";
ansBox.disabled = true;
submitBtn.disabled = true;
}
} else {
isCorrect.innerHTML = "Uh-oh, your answer was incorrect!";
}
}
//Ask question
function question() {
ques.innerHTML = num1 + " + " + num2;
}
//Call question function
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" type="submit" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
<span id="quesNum"></span>
<span>/ 10</span>
</div>
<script src="scripts.js"></script>
</body>
</html>
The code that generates the two random numbers is currently not inside a function, so it runs once when the page first loads. You just need to move those lines inside your question() function, so then each time question() is called you'll get new random values.
You'll want to set the ans value from there too (but leave ans as a global variable so that it can be checked from your other function):
function question() {
var num1 = Math.floor((Math.random() * 10) + 1);
var num2 = Math.floor((Math.random() * 10) + 1);
ans = num1 + num2;
ques.innerHTML = num1 + " + " + num2;
}
In context:
//Getting elements
var ques = document.getElementById("question");
var ansBox = document.getElementById("ansBox");
var submitBtn = document.getElementById("submitBtn");
var isCorrect = document.getElementById("isCorrect");
var quesNum = document.getElementById("quesNum");
//Variables
var ans;
var questionNumber = 1;
quesNum.innerHTML = questionNumber;
//Check if answer is correct or not
function checkAns() {
if(ansBox.value == ans) {
isCorrect.innerHTML = "Good job! Your answer was correct!";
questionNumber++;
quesNum.innerHTML = questionNumber;
ques.innerHTML = " ";
question();
//Call if statement when questionNumber = 10 and disable submitBtn and ansBox
if(questionNumber == 10) {
isCorrect.innerHTML = "Congratulations! You have completed all 10 questions! Refresh the page to do more!";
ansBox.disabled = true;
submitBtn.disabled = true;
}
} else {
isCorrect.innerHTML = "Uh-oh, your answer was incorrect!";
}
}
//Ask question
function question() {
var num1 = Math.floor((Math.random() * 10) + 1);
var num2 = Math.floor((Math.random() * 10) + 1);
ans = num1 + num2;
ques.innerHTML = num1 + " + " + num2;
}
//Call question function
question();
body {
font-family: Arial;
}
div {
padding-top: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div>
<h1>Edu Game One</h1>
<h3 id="question"></h3>
<input type="text" id="ansBox" />
<button id="submitBtn" type="submit" onclick="checkAns()">Submit</button>
<p id="isCorrect"></p>
<span id="quesNum"></span>
<span>/ 10</span>
</div>
<script src="scripts.js"></script>
</body>
</html>
Also, you may want to move the following lines:
questionNumber++;
quesNum.innerHTML = questionNumber;
...to be before the if statement, because at the moment it doesn't count questions attempted, it counts only questions that were answered correctly.

Categories

Resources