this is my first question on stack overflow, I have only been coding for a few months and I know I am probably just missing something simple here. I am trying to create a simple program for learning purposes, computer auto picks number between 1-100, user then picks number and is alerted if their choice is hot or cold in relation to the computer number.
I am trying to pass the users answer from a form field into a JavaScript variable, then run the function to test their answer when a button is clicked. I am using jQuery for both of these.
Here is the application live: http://keithlamar.github.io/HotOrCold/
Here is my HTML:
<form>
Your Number <input id="guess" type="number" name="yournumber"><br>
</form>
<p id="pick">Click Here</p>
Here is my JavaScript:
var userNum = $('#guess').val();
var comNum = Math.floor(Math.random()*101);
var difference = function (a,b) {return Math.abs(a - b)};
var askNumber = function(){
if(userNum == comNum){
alert("You got it! You Win!")
}
else if(difference(userNum,comNum) < 5){
alert("Very Hot!");
}
else if(difference(userNum,comNum) < 10){
alert("Hot!");
}
else if(difference(userNum,comNum) < 20){
alert("Warm!");
}
else if(difference(userNum,comNum) > 20){
alert("Very Cold!")
}
else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function(){
$('#pick').click(function(){
askNumber();
});
});
It seems like the var userNum is not getting a value from the input. I think it may have something to do with nesting of functions within functions, but I am not entirely sure!
Thanks for any input!!
You need to read the values inside the function - in your code you are reading the input field during the page load(before the click happens)
function difference(a, b) {
return Math.abs(a - b)
};
function askNumber() {
//read the user input in the click handler
var userNum = parseInt($('#guess').val(), 10);
var comNum = Math.floor(Math.random() * 101);
//calculate the difference only once then reuse it
var diff = difference(userNum, comNum);
if (diff == 0) {
alert("You got it! You Win!")
} else if (diff < 5) {
alert("Very Hot!");
} else if (diff < 10) {
alert("Hot!");
} else if (diff < 20) {
alert("Warm!");
} else if (diff > 20) {
alert("Very Cold!")
} else {
alert("Sorry, you need to choose a number.")
}
};
$(document).ready(function () {
$('#pick').click(function () {
askNumber();
});
});
Demo: Fiddle
Related
So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();
I make a condition with Else-If to print a line like [You got A+, You got D]. Now I want to store one valid output line in a variable outside the condition.
var gradeMark = Math.round(totalNumber / 6);
//Generate grade mark
if (gradeMark >= 80) {
console.log("You got A+");
} else if (gradeMark >= 70) {
console.log("You got A");
}....
.....
else if (gradeMark >= 0) {
console.log("You got F");
} else {
console.log("It's not valid mark");
}
//Getting grading mark
var validGradeMark =
You can use defining variable instead of console log and it is out of condition now.
let gradeMark = Math.round(totalNumber / 6);
let validGradeMark;
// Generate grade mark
if (gradeMark >= 80) {
validGradeMark = "You got A+";
} else if (gradeMark >= 70) {
validGradeMark = "You got A";
}....
.....
else if (gradeMark >= 0) {
validGradeMark = "You got F";
} else {
validGradeMark = "It's not valid mark";
}
// Getting grading mark
console.log(validGradeMark);
So my alternative version of this code is in Java, the logic is fairly similar although in JavaScript the userinput is repeated infinitely rather than carrying until the user loses. This is my working Java code for reference:
int stop =0;
Scanner scan = new Scanner(System.in);
Random rand = new Random();
do {
int card;
int upcommingcard;
String userinput;
card= rand.nextInt(13)+1;
System.out.println("Card is "+card);
System.out.println("Higher or Lower?");
userinput = scan.next();
upcommingcard = rand.nextInt(13)+1;
if(!userinput.equalsIgnoreCase("H")&&(!userinput.equalsIgnoreCase("L"))){
System.out.println("Invalid Input ");
}
else if((userinput.equalsIgnoreCase("H")) && (upcommingcard > card)){
System.out.println("Correct!");
}
else if(userinput.equalsIgnoreCase("L") && upcommingcard < card){
System.out.println("Correct!l ");
}
else {
System.out.println("You lost it was " + upcommingcard);
stop=1;
}
}while (stop != 1);
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
JavaScript - Not working
var max=13;
var min=1;
var stop=0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is "+card+"... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do{
if((userinput !="H")&&(userinput !="L")){
console.log("Invalid input");
}
else if((userinput ="H")&&(upcommingcard > card)){
console.log("Correct!");
}
else if((userinput ="L")&&(upcommingcard < card)){
console.log("Correct!");
}
else{
console.log("You lost, it was "+ upcommingcard);
stop=1;
}
}
while(stop !=1);
Just to mention also that it registers that the user's input is correct although it fails to continue and just keeps on spitting out the same output until the browser crashes.
EDIT: Thanks for the responses! the loop works perfectly now, my only issue is that the logic is a bit flawed since sometimes I Input 'L' for 8 and upcoming int is 10.. Dispite this I get the Incorrect response.
It's not that your console isn't updating, it's that you never exit your loop if the input is incorrect, and you never offer them the option to try again.
Thus if they are incorrect, the loop will never end, the console won't be updated, and they can't retry.
I would recommend changing the code to the following, to alert the user to try again.
var max = 13;
var min = 1;
var stop = 0;
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
do {
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input!");
userinput = prompt("Card is " + card + "... Higher or lower?");
} else if ((userinput == "H") && (upcommingcard > card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
stop = 1;
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
There are some points I want to make on this:
Your Java and Javascript code logic differs. You had the variables and input reads inside do while in Java but outside in Javascript.
As your prompt right now is outside the loop, it will keep having the same input value everytime and not asking for another one, and will carry on until it's a wrong guess, or forever if it's an invalid input. And the next point worsens your problem:
Your if comparison operators are invalid. What you did, as mentioned in the comments, is a data assignment to userinput and will always return correct
That being said, I corrected it below while adding alert popups instead of console.log only:
var stop = 0;
do {
var card = Math.floor((Math.random() * (13 - 1) + 1));
var userinput = prompt("Card is " + card + "... Higher or lower?");
var upcommingcard = Math.floor((Math.random() * (13 - 1) + 1));
if ((userinput != "H") && (userinput != "L")) {
console.log("Invalid input");
alert("Invalid input");
stop = 1; //Currently stopping if having invalid input, you can remove this later
} else if ((userinput == "H") && (upcommingcard > card)) {
//Note the '==' above, and also the next one for comparing equal values
console.log("Correct!");
alert("Correct");
} else if ((userinput == "L") && (upcommingcard < card)) {
console.log("Correct!");
alert("Correct!");
} else {
console.log("You lost, it was " + upcommingcard);
alert("You lost, it was " + upcommingcard);
stop = 1;
}
}
while (stop != 1);
Now, do compare the JS snippet above with your working Java code you've posted. If you compare again with your JS code, you should be able see what I meant by having different logic.
I am writing a simple n-back game, and at the end of a session I have an alert message popping up to tell the user their n-back level is being increased if they score 75% or better. For some reason though, after the user clicks OK or hits enter, the setInterval function seems to be running through one more time. On the grid I have created, one more square lights up, even though the session is supposed to be over. I will post the relevant game code below:
$('#start').click(function()
{
let counter = 0;
message_switch = true;
$('#start').blur();
$('#score-output').text(0);
$('#percentage').text('%');
var intervalID = setInterval(function()
{
counter++;
show_card(get_cardID(cardIDs));
if (counter === 30)
{
window.clearInterval(intervalID);
message_switch = false;
var score = Math.round((playerMatches.length / matches.length) * 100);
score = score - (error_count * 3);
update_score(score);
if (score < 50)
{
if (n_back < 2)
{
n_back = 1;
} else {
n_back = n_back - 1;
}
} else if (score < 75 && score >= 50)
{
n_back = n_back;
} else if (score >= 75) {
n_back = n_back + 1;
};
$('#nback').text(n_back);
reset_game_values();
if (score >= 75) //here there is some issue
{
window.alert("Congratulations, you will move up to " + n_back + " back.");
score = 0;
return;
} else {
score = 0;
}
}
}, 3500);
})
I know this is a lot of code and there is also a lot of code I haven't provided, mainly just in an attempt to be brief. Does anyone see anything obvious that I am not seeing? If you feel you need to see more of the program I can provide it. Thanks.
I am trying to make a simple JavaScript guessing game, and my for loop keeps getting skipped! Here is the part of my code that is getting skipped:
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
and here is the full code:
//declaring variables
var numberToGuess;
var tries;
var i;
var isSkipped = true;
var confirmPlay = confirm("Are you ready to play lobuo's guessing game? The number for you to guess will be a number ranging from 1 to 25."); //does the user want to play?
if (confirmPlay === true) {
console.log("User wants to play");
} else {
window.location = "http://lobuo.github.io/pages/experiments.html";
} //if user wants to play, let them play, else go to website homepage
numberToGuess = Math.floor((Math.random() * 25) + 1); //sets computer-generated number
tries = prompt("How many tries would you like?"); //gets amount of tries
tries = Math.floor(tries); //converts amount of tries to integer from string
for (i = 0; i === tries; i += 1) {
isSkipped = false;
var guessedNumber = prompt("Guess your number now.");
console.log("User guessed number " + guessedNumber);
//check if number is correct
if (guessedNumber === numberToGuess) {
confirm("Hooray, you have guessed the number!");
break;
} else if (guessedNumber > numberToGuess) {
confirm("A little too high...");
} else {
confirm("A little too low...");
}
}
if (isSkipped === true) {
console.log("Oh no! The for loop has been skipped!");
}
If you need any further details, just ask.
Shouldn't the for be like this?:
for (i = 0; i < tries; i += 1) {
When you write:
for (i = 0; i === tries; i += 0) {
the loop repeats as long as the condition i === tries is true. If tries is 3, for instance, this condition is not true on the first iteration, and the loop ends immediately.
You should write:
for (i = 0; i < tries; i++) {
Also you need to use parseInt() function on user's input.
var guessedNumber = parseInt(prompt("Guess your number now."), 10);
instead of
var guessedNumber = prompt("Guess your number now.");