Creating a Number Guessing Game in Javascript - Need Help on Loop - javascript

So far I have created a basic number guessing game,the number is currently set to 50 for testing purposes. I would like to know how to add a loop so the user can guess again. I would also like to see the previous guesses on the screen. So it would should something like:
Number Guessing Game!
Guess #1 : 49 was LOW
Guess #2 : 51 was HIGH
Guess #3 : 50 was CORRECT
For the loop i know i need to use something like "while( !guessed )" but not sure how to implement it at all, i'm pretty new to this, any help would be fantastic!
var canvas;
canvas = openGraphics();
var max;
max = 100;
var numberToGuess;
numberToGuess = 50; // will become Math.floor( Math.random() * max ) + 1; later //
canvas.setFont("comic sans ms", "15px", Font.Bold);
canvas.drawString("Number Guessing Game!");
var guess;
guess = prompt( "Please input your first guess" );
if(guess > numberToGuess){
var message1;
message1 = " was HIGH";
var messageanswer;
messageanswer = "Guess #1 : " + guess + message1;
canvas.drawString(messageanswer, 20,20);
}
if (guess < numberToGuess){
var message2;
message2 = " was LOW";
var messageanswer2;
messageanswer2 = "Guess #1 : " + guess + message2;
canvas.drawString(messageanswer2, 20,20);
}
if (guess == numberToGuess){
var message3;
message3 = " was CORRECT";
var messageanswer3;
messageanswer3 = "Guess #1 : " + guess + message3;
canvas.drawString(messageanswer3, 20,20);
}
canvas.paint();

You're correct, you need to use a type of while loop to continuously allow input until the number is guessed.
Remember, you'll want to use a dowhile loop, because you want the condition to be checked after the code runs, not before.
Something like this would work:
var guess;
var numberToGuess = 50;
do {
// check previous guess and alert low/high message
if ( guess ) {
if ( guess > numberToGuess ) {
alert( "Your guess was too high." );
}
else {
alert( "Your guess was too low." );
}
}
guess = prompt( "Please input your guess" );
} while ( guess != numberToGuess );
alert( "You guessed correctly!" );
Obviously you can add your own counter and message if you'd like, but this should get you on the right track.

I think the best way in context of this is to wrap your code like this
function guess()
{
if(guess > numberToGuess)
{ }
if (guess < numberToGuess)
{ }
if (guess == numberToGuess)
{
...
return;
}
else guess();
}

There is a problem with loops in JavaScript: The UI is dead while they run. So you need to start thinking in "events" and "event handlers".
The idea is that you update the UI or the DOM to display the current state of the game. Part of the UI is a text entry field where the user can enter the next guess. Next should be a button "Am I right?". These two elements replace the prompt.
You can now add an event / click handler to the button. In the handler, you read the input and check it. If it's wrong, you update the UI.
If it's correct, you hide the text field and the button. Instead you display some kind of "You won!" screen plus a button to restart the game.
Again, the code should end with that. The click handler for the win button should reset the UI to the original state.

Related

JavaScript Choose your own adventure game random number function in loop problem

I'm writing a choose your own adventure program where If a specific option is chosen (example to wait) the user gets a random number between 1-10 to do push ups(the push-ups would be the user clicking on the prompt "ok" button however many times the random number is equal to) here's my code so far but I keep getting errors. I'm a complete noob so go easy on me.
var count = Math.floor((Math.random() * 10) + 1);
var setsOf10 = false;
function pushUps() {
alert("Nice! Lets see you crank out " + pushUps + "!");
}
if (setsOf10 == pushUp) {
alert("Nice! Lets see you crank out " + pushUp + "!");
setsOf10 = true;
}
for (var i=0; i<count; i++){
pushUps();
}
else {
alert("Really, thats it? Try again");
}
while ( setsOf10 == false);
}
After playing with this some more I can tell i'm close but still don't have it. and again, I'M NOT ASKING YOU TO SOLVE THIS FOR ME JUST NEED POINTERS AS TO WHAT IM DOING WRONG OR MISSING. Here's what I have, Its giving me my random number I just need it to allow me to click the "ok" button however many times the random number has assigned me.
var pushUpSets = Math.floor((Math.random() * 10) + 1);
function pushUps(){
alert(pushUpSets);
if (pushUpSets < 3){
var weak = "Thats it? Weak sauce!";
alert(weak);
}
else{
alert("Sweet lets get some reps in!");
}
for (i=0; i>3; i++){
pushUps(pushUpSets);
}
}
Here, the make a choice button is just dummy to allow us to go to do push ups. Each click decrements our count.
// This is important, we use this event to wait and let the HTML (DOM) load
// before we go ahead and code.
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#choice').addEventListener('click', makeChoice);
});
function makeChoice() {
// Call a method to set random pushups and setup the click event
setUpPushUp();
// Here we change the display style of the push up section so that it shows to the player.
document.querySelector('.activity').style.display = 'block';
}
// The pushups variable is declared at the document level
// This way our setUpPushUp and doPushUp functions have easy access.
let pushUps = 0;
function setUpPushUp() {
// Create a random number of pushups, in sets of 10.
// We add an extra 1 so we can call the doPushUp method to initialize.
pushUps = (Math.floor((Math.random() * 10)+1)*10)+1 ;
// Add a click event to the push up button and call our doPushUp method on each click.
document.querySelector('#push').addEventListener('click', doPushUp);
// This is just an init call, it will use the extra 1 we added and place test in our P tag.
doPushUp();
}
function doPushUp() {
// Get a reference to our output element, we will put text to player here.
let result = document.querySelector('p');
// They have clicked, so remove a push up.
pushUps--;
// See if the player has done all the required push ups (i.e. pushUps is 0 or less.)
if (pushUps > 0) {
result.innerText = `You need to crank out ${pushUps} pushUps`;
} else {
result.innerText = 'Nice work!';
}
}
.activity {
display: none;
}
<button id="choice">Make a choice !</button>
<div class="activity">
<p></p>
<button id="push">Push</button>
</div>

how to add up the current score, jquery, javascript

I am trying to get a current score to add up every time an answer is correct, what is happening is that I have the questions in a pagination set up and when this answer is correct it give me the score but then when it goes to the next page it refresh the score and if I got that one right it just give me the score for that one again but it doesn't add up.
JS code:
$(function() {
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
var score = 0;
if (correct){
alert('Good job ' + arr2,);
score += 2;
alert (score);
currentScore = score++;
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
});
});
Here is another option - local storage.
Here is a reference W3School Web storage
It's not the most ideal solution, but it can meet your criteria.
let score = localStorage.getItem('score')
score++;
localStorage.setItem('score', score);
Your pages will be able to access the localStorage so you can get the value of score and re-set it.
Hopefully the reference can answer further questions, else leave a comment!
Con: It may not be supported by all browsers.
EDIT:
Here is an example with your code.
$(function() {
let currentScore = localStorage.getItem('score'); // get score
if (currentScore === null){ // if score doesnt exist yet
localStorage.setItem('score', 0); // set score
currentScore = 0; // make currentScore 0
}
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
if (correct){
alert('Good job ' + arr2);
currentScore += 2; //increment current score by 2
alert (currentScore);
localStorage.setItem('score', currentScore); // set the item again with new value
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
});
});
Edit 2:
let currentScore = localStorage.getItem('score'); // get score
currentScore = parseInt(currentScore);
it give me the score but then when it goes to the next page it refresh the score and if I got that one right it just give me the score for that one again but it doesn't add up.
I think your problem is there.
If I understand correctly, when the answer is good, the page refresh and passes to the next question. Your problem is that the score doesn't add up to the previous one.
The score variable is only stored in the current page, like a temporary one. Without saving the score on the server, via ajax or another method, and getting it on the next page, it will not add up. Indeed, score will have a value of 0 due to the refresh.
A simple schema :
score = 0 -> correct answer -> +50 point -> score = 50 -> next page -> score = 0
As you can see, because the javascript you wrote is not assuring the persistance of your information, the previously stored score is lost.
You need to send the score on the server and then get it back when the new page is loaded or to avoid changing page and make your quizz on one and only page, without refreshing.
Keep in mind that everytime you are refresing a page, the javascript is starting again and therefore everything done before is lost.
I hope this was helpful.
Ps: You should place your code in the $( document ).ready(); block just like this :
$( document ).ready(function() {
console.log( "ready!" );
});
It will make your code start when the html DOM (the structure of the html file) is loaded and ready to be manipulated. It can avoid a lot of errors.
Edit2 : What it will look like in your code :
$( document ).ready(function() {
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
var score = 0;
if (correct){
alert('Good job ' + arr2,);
score += 2;
alert (score);
currentScore = score++;
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
});
});
Or, to make this more readable and to avoird having a lot of things in the document.ready block (when you will have a lot of lines/functions) :
$( document ).ready( myNiceFunction() );
var myNiceFunction = function(){
$('#author').on('change', function(event) {
var opt = this.options[ this.selectedIndex ];
var correct = $(opt).text().match (arr2);
var score = 0;
if (correct){
alert('Good job ' + arr2,);
score += 2;
alert (score);
currentScore = score++;
alert(currentScore);
display(currentScore);
}
else {
alert ('nice try ' + arr2);
}
}
Ps2 : I know this is not the best website to explain it but I think it is simple enough to make you understand the principle of ajax without losing you into a bunch of technical stuff : here and here
Edit : Grammar and second post-scriptum.
Not sure how you're doing pagination but it should be ajaxed, instead of a full postback, so you don't lose the values on your page.

Can I put a variable = another variable in if statements. Or put var = value = another value which it should be equal to?

Hi I'm trying to work on a problem solving webpage that I need for school but so far I'm stuck with the if statement which it will use to calculate.
What I have so far.
<script>
var randomNumberA = Math.round((Math.random() * 50) +1)
var randomNumberB = Math.round((Math.random() * 50) +1)
document.write('He runs at ' + randomNumberA + 'm/s which took him ' + randomNumberB + 's. How far did he run?');
var distance = randomNumberA * randomNumberB
function Submit()
{
var answer = document.getElementById('answer')
if(distance == true){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
</script>
<body>
<input type='text' id='inputAnswer'/>
<input type='button' onClick='Submit()' value='Submit'/>
</body>
It's not really working and if I put only one "=" then it'll alert as true as long as there's a value in the text box. I plan to make a variable for the textbox value and a variable for the formula and just put If(var1=var2)... so on, but it doesn't work. I'd like to know if it's possible, and if it is how?
If it's not possible can I try to place var1 = formula = textbox id. I'm trying to make it so one variable contains the values that need to be equal so when I declare it in the if statement, I'll just test if it's true or false.
All help is appreciated thanks!
You should compare the calculated distance to the given answer. Now you compare distance to true, which doesn't make sense.
Change it to
if(distance == parseFloat(answer.value)){
You need .value, because answer points to the element. You don't want to compare distance to the element, but to the numeric representation of the element's value.
Also note that you have the id wrong. In html it is inputanswer, while in your script you called it answer.
The version with a single = works, because you assign a value to distance. An assignment can also be used as an expession, which returns the value that was assigned. So if you write if (distance = true), you assign true to the variable distance, and also return true from the expression, resulting in the code inside the if always being executed.
I've made the necessary fixes in the code below, which you can just run from here. As you can see, you were almost there. I just needed to make those two small fixes. :)
var randomNumberA = Math.round((Math.random() * 50) +1)
var randomNumberB = Math.round((Math.random() * 50) +1)
document.write('He runs at ' + randomNumberA + 'm/s which took him ' + randomNumberB + 's. How far did he run?');
var distance = randomNumberA * randomNumberB
function Submit()
{
var answer = document.getElementById('inputAnswer')
if(distance == parseFloat(answer.value)){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
<body>
<input type='text' id='inputAnswer'/>
<input type='button' onClick='Submit()' value='Submit'/>
</body>
Not completely sure that I understand your question. But, here's some info that will hopefully help:
if(distance == true){
This will render true if there's a value, unless the value is set to false. It's like saying:
if (distance)
If you want to test to see if the value matches the formula, you would just do something like this:
function Submit()
{
var answer = document.getElementById('inputAnswer').value // not 'answer'
if(distance === answer){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
Hope that helps
you could also get the value via JQuery if your'e using that. It would be the following:
var answer = $('#inputAnswer').val();
Cheers!

syntax issues with js/jquery assignment - Quiz questions in an object

I'm trying to work through an assignment to further my understanding of js but I'm running into some issues that are keeping me from final code. The code executes a short quiz- inputs from radio buttons are taken in and matched to an object containing answers, then outputting a final score.
code at http://jsfiddle.net/8ax9A/3/
issues I'm aware of now :
my $response variable doesn't seem to work.
var $response = $('[name=rad]:checked').val();
counter is listening for clicks through questions. After the last question, I want to report final score. I can't get counter to reach the end of questions + 1, and I cant get an accurate final score listener reported (var finalScore).
if ($response == parseInt(questions[counter].answer, 10)) {
finalScore++;
}
Those are just snippets so check out the fiddle for full code. I'd love some suggestions on how to understand where I'm going wrong.
Here is one way you could do it:
//Initialization
var counter=0;
var score=0;
loadQuestion();
$('#next').on('click',answer);
//functions
function answer(){
// if the user did not answer
if ($('input:radio:checked').length == 0){
alert('You have to answer!');
return;
}
var currentQ=questions[counter];
// if answer is correct
if($('[name=rad]:checked').val()==currentQ.answer){score++;}
counter++;
// if there are no questions left
if(counter >= questions.length) {displayResults(); return;}
loadQuestion();
}
function loadQuestion(){
// clear the radio buttons
$("input:checked").removeAttr("checked");
var currentQ=questions[counter];
// display the question
$('h1').text(currentQ.question);
$('#a1').text(currentQ.choices[0]);
$('#a2').text(currentQ.choices[1]);
$('#a3').text(currentQ.choices[2]);
}
function displayResults(){
$("h1").text("You've finished with a score of " + score + "!");
$('[name=rad], #a1, #a2, #a3, #next').remove();
}
JS Fiddle

Clear Var or Callback in Javascript

Sorry, i am not sure if I am asking the question correctly. When a date is changed by a user the date count down changes on the page. If the date is changed more than once it flashes all date changes. I guess it is storing the previous information somewhere. I have tried clearing the vars.
var deal_yeax = '';
as I would do in php with no luck
$('#deal_end').focusout(function() {
var deal_end = $("#deal_end").val();
var array = deal_end .split('-');
var deal_montx = array[0];
var deal_dax = array[1];
var deal_yeax = array[2];
deal_montx = deal_montx - 1;
$(function(){
ts = new Date(deal_yeax , deal_montx , deal_dax );
$(".h").countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds){
message_days = (days);
var message_hours = (hours);
$(".message_hours").text(message_hours + " Hours");
var message_minutes = (minutes);
$(".message_minutes").text(message_minutes + " Minutes");
var message_seconds = (seconds);
// Creat the display
if ( message_days < 1 && message_hours < 1 ) { $(".message_seconds").text(message_seconds + " Seconds"); }
else if ( message_days < 1 && message_hours > 1 ) { }
else if ( message_days == 1 ) { $(".message_days").text(message_days + " Day"); }
else { $(".message_days").text(message_days + " Days"); }
if ( message_days < 1 && message_hours < 1 && message_minutes < 1 && seconds < 1 ) {
$(".hide_my_buy_button").fadeOut("fast");
}
}
});
});
});
Everytime you "focusout" from #deal_end, you'll attach a countdown event to .h. Without knowing exactly how countdown(...) works (It'll be good if you provide the source so we can provide more help!), one way to fix the issue maybe to use JQuery's unbind(...) function to remove existing listeners on an event before adding a new one to it.
Here's an example on the issue:
<!-- HTML -->
<div>
<input id="text" />
<button id="clicker" />
</div>
<!-- Javascript -->
$('#text').focusout(function() {
var text = this.value;
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
... and here's how to solve the issue (It's just one of the many ways. This way is probably not the most elegant but anyhow.)
$('#text').focusout(function() {
var text = this.value;
$('#clicker').unbind('click');
// Everytime #text is "focused out", a new event is registered with #clicker.
$('#clicker').click(function() {
console.log('Value: ' + text);
});
});
Bottom line: It seems focusout(...) is adding a new countdown everytime it is triggered. That might be the problem you're having.
Not sure if this helps? Lemme know.
P.S. JSFiddle to go with it: http://jsfiddle.net/PE9eW/
The problem seems to be with .countdown function that you are using in your code to flash the date changes. When you assign a new count down object to $(".h") the plugin or the function probably assign some event handler or interval to it, but it doesn't seem to clear the old ones when it is called again and that is why it flashing all the dates for each countdown. So you will have to do it manually. I am not sure if you are using an external plugin or is it your own function but what you need to do is to clear the existing events or intervals that is assigned to your element when you call the function. I can be more helpful if you tell me which plugin you are using or maybe show the code if it is your own function. (referring to .countdown() )

Categories