Random math game in JavaScript - 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

Related

Evaluate if statements in javascript

So I'm following the modern JavaScript from the beginning by brad traversy, and in the guess number project the app ignores all the conditions in the first if statement and continue. I checked the code in the project file and it's the same, I tried switch statement, I put each condition in a separate if statement, and still doesn't work
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Your if statement is absolutely fine, the reason you never see the message "Please enter a Number between ${min} and ${max}" is because you let the code continue, and almost immediately that message is overwritten by a different one. Simply adding a return statement within your if block will solve this problem.
Note I also fixed this line guessInput = ''; which should be guessInput.value = '';
let min = 1,
max = 10,
winningGuess = 2,
guessesNum = 3;
// Grab on UI Elements
const game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');
// Assign UI to min and Max
minNum.textContent = min;
maxNum.textContent = max;
// Add an EventListener
guessBtn.addEventListener('click', function() {
let guess = parseInt(guessInput.value);
if (isNaN(guess) || guess < min || guess > max) {
setMessage(`Please enter a Number between ${min} and ${max}`);
return; // here
}
if (guess === winningGuess) {
gameOver(true, `Great Job ${winningGuess} is the Correct guess, You Won!`)
} else {
guessesNum -= 1;
if (guessesNum === 0) {
gameOver(false, `Sorry you lost, The correct guess was ${winningGuess}`)
} else {
guessInput.style.borderColor = 'red';
setMessage(`${guess} is not the correct number, You have ${guessesNum} guesses left. Please try again`, 'red');
guessInput.value = '';
}
}
});
function gameOver(won, msg) {
let color;
won === true ? color = 'green' : color = 'red';
guessInput.disabled = true;
guessInput.style.borderColor = color;
message.style.color = color;
setMessage(msg);
}
function setMessage(msg, color) {
message.textContent = msg;
message.style.color = color;
};
<div class="container">
<h1>The Number Guesser Game</h1>
<div id="game">
<p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
<input type="number" id="guess-input" placeholder="Enter Your Guess">
<input type="submit" value="Submit" id="guess-btn">
<p class="message"></p>
</div>
</div>
Try changing the const to let. You're editing all these later in your code:
let game = document.querySelector('#game'),
minNum = document.querySelector('.min-num'),
maxNum = document.querySelector('.max-num'),
guessInput = document.querySelector('#guess-input'),
guessBtn = document.querySelector('#guess-btn'),
message = document.querySelector('.message');

JS get random value from array and update array

I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>
Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working
Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

Displaying hidden html buttons using JavaScript

Am trying to create a quiz but after the start page am un sure how to make the answer choices display. I have created the buttons for the choices in html and started them off as hidden, and have allocated for them in javascript. I have the questions and answers in an array but am stuck on displaying the choice buttons under the question. After the initial start page.
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.querySelector("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
var buttonEl = document.querySelector("start-game");
should be
var buttonEl = document.getElementById("start-game");
var timerEl = document.getElementById("timer");
var start = document.getElementById("start-button");
var questionEl = document.getElementById("header");
var option0 = document.getElementById("option0");
var option1 = document.getElementById("option1");
var option2 = document.getElementById("option2");
var option3 = document.getElementById("option3");
var intials = document.getElementById("user-initials");
var buttonEl = document.getElementById("start-game");
var totalTime = 75;
var elapsedTime = 0;
var questionNum = 0;
var questions =["The condition in an if/else statement is enclosed with in _______",
"Arrays in JavaScript can be used to store ______",
"Commonly used data types do not include ______",
"String values must be enclosed within _____ when being assigned to variables"];
var answers =[question1= ["Quotes","Curly brackets","Parentheses","Square brackets"],
question2= ["Numbers and strings","Other arrays","Booleans","All of the above"],
question3= ["Strings","Booleans","Alerts","Numbers"],
question4= ["Commas","Curly brackets","quotes","parentheses"]
];
var correctAnswers = [2,3,2,2];
start.addEventListener("click", function(){
timer();
displayQuestion();
start.style.visibility = "hidden";
buttonEl.style.visibility = "visible";
});
function timer(){
var timerInterval = setInterval(function(){
totalTime--;
timerEl.textContent = totalTime;
if(totalTime === 0){
function stopTimer(){
clearInterval(timerInterval);
endQuiz();
return;
}
}
}, 1000)
}
function newQuiz(){
questionEl.textContent = (questions[0]);
};
function decreaseTimer (){
timerEl.text(totalTime);
while(elapsedTime < 75){
elapesedTime += 1;
}
endQuiz();
totalTime = totalTime - elapsedTime;
timerEl.textContent = totalTime;
}
function displayQuestion(){
for( var i = 0; i < questions.length ; i++){
questionEl.textContent=(questions[i]);
option0.textContent=(answers[i][0]);
option1.textContent=(answers[i][1]);
option2.textContent=(answers[i][2]);
option3.textContent=(answers[i][3]);
}
}
<div class="wrapper text-center">
<header>
<h1>Coding Quiz</h1>
</header>
<div class="card">
</div>
<div class="card-body">
<p id="header"> You have 75 seconds to complete this asessment. Every
incorrect answer will cost you time.
<br>
</p>
<button id="start-button" class="btn">Start</button>
<div id="start-game" style="visibility: hidden">
<button id="option0" data-index="0"></button><br>
<button id="option1" data-index="1"></button><br>
<button id="option2" data-index="2"></button><br>
<button id="option3" data-index="3"></button><br>
</div>
</div>
</div>
<div id="timer"></div>

Can't change text in 'on click' javascript

I am doing a 'if,else' statement in javaScript. I want to change the "h2" text. I think I'm missing some code
<div id="game">
<p id="howMany">How many fingers am I holding up?</p>
<p id="theGame"> <input type="guess" id="guess" placeholder="0 to 5">
<button id="check-guess"> Guess! </button>
</p>
<div id="theAnswer">
<h2 id="h2">Your Reward</h2>
</div>
</div>
document.getElementById("check-guess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
document.getElementsById("h2").innerHTML = "You got it!";
} else {
document.getElementsById("h2").innerHTML = "Nope! Try Again. The number is " + randomNumber ;
}
}
Your function getElementsById doesn't exist, it could be getElementById. The value you pass needs to be an id, not a tagname.
document.getElementById("check-guess").onclick = function() {
var randomNumber = Math.random();
randomNumber = randomNumber * 6;
randomNumber = Math.floor(randomNumber);
if (document.getElementById("guess").value == randomNumber) {
document.getElementById("h2").innerHTML = "You got it!";
} else {
document.getElementById("h2").innerHTML = "Nope! Try Again. The number is " + randomNumber;
}
}
<input id="guess">
<button id="check-guess">Check</button>
<h2 id="h2">Test</h2>

JS: How would I display a decrementing value through an html header? (and more)

Basically, I'm making a simple javascript/html webpage game where you guess a number and you have three chances to guess correctly. I'm having a problem displaying the number of attempts a player has left (It gets stuck at three). The color change that is supposed to occur also doesn't happen.
It also doesn't reset the page's display after a refresh (it takes 5 playthroughs of the game to get it to reset).
Maybe my for loop/if statement is screwy?
Here's my code.
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
The prompt is a blocking event, so you don't see the page update until after the prompts... try the example below, where setTimeout is used to allow a delay...
var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));
function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
document.body.style.backgroundColor = "#CC0000";
var x = "";
x = x + "You have " + guesses + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
setTimeout(function() {
handleGuess(prompt("Try again!"));
},1000);//wait 1 second
} else {
var x = "";
x = x + "You win!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
//return false;
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
//return false;
}
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<br>
Attention. This is a fully workable example, and definitely an "overkill demo" for your "blocking" request.
I've removed the prompt calls with new inputs, and created 2 buttons for the game. One that calls the Start Game, and a second for the "in game try attemps".
I'm assuming you are still learning so this example might be helpful for you,by showing the advantages of separating your code into different elements, based on what they are doing, and also making it easier for you to "upgrade" the features of your game.
I could replace a lot more repeated code to make it look better, but that would not make it so familiar anymore to you.
/*function ChangeDif(Difficulty) {
var i = ""
if (Difficulty == 'easy'){
i = 10;
}
if (Difficulty == 'medium') {
i = 5;
}
if (Difficulty == 'hard') {
i = 3;
}
}
*/
var random = 0;
var start_chances = 3;
var start_attemps = 0;
var x = "";
function startgame() {
document.getElementById("start").hidden = true;
document.getElementById("number").hidden = false;
document.getElementById("again").hidden = false;
document.getElementById("demo").innerHTML = "Pick a number to win the game!";
random = Math.floor((Math.random() * 10) + 1);
//Cheat to see the random number, and make sure the game is working fine
//document.getElementById("cheater").innerHTML= random;
max_chances = start_chances;
step();
}
function lostAchance() {
max_chances--;
if (max_chances > 0) {
step();
} else {
loser();
}
}
function loser() {
//running out of turns
x = "Game Over!" + "<br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#FF0000";
endGame();
}
function step() {
var choice = parseInt(document.getElementById("number").value);
if (choice !== random) {
document.body.style.backgroundColor = "#CC0000";
x = "You have " + max_chances + " chances left" + "<br>";
document.getElementById("demo").innerHTML = x;
document.getElementById("start").hidden = true;
} else {
//win
x = "You win! In " + (start_chances - max_chances) + " attemps <br>";
document.getElementById("demo").innerHTML = x;
document.body.style.backgroundColor = "#009000";
endGame();
}
}
function endGame(){
document.getElementById("start").hidden = false;
document.getElementById("again").hidden = true;
document.getElementById("number").hidden = true;
}
<!DOCTYPE html>
<html>
<body>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'easy')">Easy
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'medium')">Medium
<br>
<input type="radio" name="difficulty" onclick="ChangeDif(this.Difficulty, 'hard')">Hard
<br>
<h1 id="demo">You have 3 chances to guess the correct number.</h1>
<input type="number" id="number" hidden />
<button type="submit" id="start" onclick="startgame()">Let's PLAY</button>
<button type="submit" id="again" hidden onclick="lostAchance()">Try Again</button>
<p id ="cheater"></p>
</body>
</html>

Categories

Resources