I'm a new programmer learning HTML/CSS/Javascript, and was fiddling around with it until I came across a bug. I was making the computer guess my number (0-5), but then realized if I put in a number higher than 5, the website just crashes. Is there any way I can make it so that if the user puts in a number higher than 5 it will just delete it automatically? Or is that not Javascript. Thanks in advance :)
document.getElementById("guess").onclick=function() {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Try this :
document.getElementById("guess").onclick=function() {
if(document.getElementById("myNumber").value > 5) {
document.getElementById("myNumber").value = "";
alert("Please provide a number that is with in 0 to 5");
} else {
var gotit=false;
var guesses=1;
var x;
while(gotit==false) {
x=Math.random();
x=6*x;
x=Math.floor(x);
if(document.getElementById("myNumber").value==x) {
gotit=true;
} else {
guesses++;
}
}
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
Than define a onchange function to check length:
document.getElementById("myNumber").onchange = function (ev){
try{
var target = document.getElementById("myNumber");
if(parseInt(target.value) > x) { // can throw exception, when given a non number
target.value="";
}
} catch(ex) {
alert('Not a number');
}
};
IMPORTANT:
You have a greater problem here: You are generating a random number, and then comparing it to input( that does not change). This is an infinite loop. Because this is a random operation, and you can hit same number more than once.
You need to generate your number first (before click event on 'guess' button), before clicking on quess button. Like so:
var luckyNumber = x;
var guesses=1;
document.getElementById("start").onclick=function(){ //init counters once
guesses=0;
x=Math.floor(Math.random()*6);
gotit = false;
}
document.getElementById("guess").onclick=function() { // guess as many times as you want
if(document.getElementById("myNumber").value==x) {
gotit=true;
}
guesses++;
if(gotit){
alert("Got it! It was a " + x + ". It only took me " + guesses + " guesses!");
}
}
But if you want to computer to quess your number, than you need to limit number of guesses (add a counter), or it will hang eventualy.
I took this as a little challenge and just went ahead and re-did your little game. Hope this helps.
Demo here
(function (guess, tryy, message) {
var comp = function () {
return Math.floor(Math.random() * 6)
};
var number = comp();
var count = 0;
var test = function () {
var val = guess.value;
if (!Number.isNaN(val) && val >= 0 && val <= 5) {
switch (true) {
case val > number:
message.innerHTML = 'Your guess was too high!';
count++;
break;
case val < number:
message.innerHTML = 'Your guess was too low!';
count++;
break;
case val == number:
count++;
message.innerHTML = 'Congratulations you found the number! It took you ' + count + ' guesses';
//Reseting game here
setTimeout(function(){
count = 0;
number = comp();
guess.value = '';
message.innerHTML = 'Your game has been reset';
}, 2000);
break;
};
}
};
tryy.onclick = test;
guess.onkeyup = function (e) {
if (e.keyCode == 13) {
test();
}
}
})(document.getElementById('guess'), document.getElementById('tryy'), document.getElementById('message'));
Related
This code isn't working: Help! It is only displaying as "no answers left", not anything else and that is displaying that I have only 0 attempts left. I am new to Javascript and need some support, I think the "for" loop isn't working. I can only try out this code once, then the page crashes.
function mathCheck() {
var inputValues1 = document.mathGuesser.mGuesser.value;
var attempts;
for (attempts = 3; attempts >= 0; ) {
if (inputValues1 === 'y = 2x - 3' || inputValues1 === 'y=2x-3') {
document.getElementById("answer").style.color = "Green";
document.getElementById("answer").innerHTML = "<span>" + "Correct" + "</span>";
}
else if (inputValues1 === ' ' || inputValues1 === '') {
document.getElementById("answer").style.color = "Black";
document.getElementById("answer").innerHTML = "<span>" + "Please enter text" + "</span>";
}
else {
document.getElementById("answer").style.color = "Red";
document.getElementById("answer").innerHTML = "<span>" + "Incorrect" + "</span>";
document.getElementById("attempts").innerHTML = attempts;
attempts--;
}
}
document.getElementById("answer").style.color = "Black";
document.getElementById("answer").innerHTML = "No attempts left";
}
In general the algorithm you came up with is working, e.g.:
for (attempts = 3; attempts >= 0; ) {
const answer = prompt("Answer to live?");
if(answer === "42"){
alert("correct!");
} else {
attempts--;
alert(attempts + " attempts left");
}
}
alert("you lost :(");
But that scenario does work because weve got synchronous code. Waiting for the user to enter the right answer is not synchronous but rather asynchronous. So in your case it will check the answer three times before the user is even to able to enter the right answer and in case the right answer was entered the loop runs forever so fast, that it freezes the browser. To solve this you need a state (remaining) and handle the different cases on every click:
var attenpts = 3;
function mathCheck() {
if(attempts <= 0)
return answer("Your tries are up!", "red");
var inputValues1 = document.mathGuesser.mGuesser.value;
if (inputValues1 === 'y = 2x - 3' || inputValues1 === 'y=2x-3') {
answer("Correct", "green");
} else if (inputValues1 === ' ' || inputValues1 === '') {
answer("Please enter your answer!", "black");
} else {
answer("Incorrect!", "red");
document.getElementById("attempts").innerHTML = attempts;
attempts--;
}
}
function answer(text, color){
const el = document.getElementById("answer");
el.innerHTML = "<span>" + text + "</span>";
el.style.color = color;
}
I don't know what you're trying to do, you should specify what the function aims to do in your question, and provide details of the issue, however this is the format of a For loop:
for(var foo = 0; foo < 10; foo++)
So your for loop should look like so:
for (attempts = 3; attempts >= 0; attempts++)
This makes "attempts" increment by exactly one on each iteration of the loop.
Note that the last part is up to you, since your variable starts at 3, and loops while greater than or equal to 0, I'm going to assume you want to decrement, so you could use: attemps--, attempts-=1..
I'm having a problem with my Javascript code that involves putting a timer in a Random guessing game. I must give the user 5 seconds to guess the number. The user can guess multiple times within the span of 5 seconds. If the time runs out, I must prompt the user if he wants to play again or exit. If yes I have to loop back to the game. My timer is not working. I would every much appreciate it if any of you guys can help. Thank you.
<script type="text/javascript">
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0
function timer (upper) {
var timeID = setInterval (getRandomNumber, 5000);
}
function getRandomNumber (upper) {
var number = Math.floor(Math.random()*upper) +1;
return number;
}
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
}else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
}else if(parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
</script>
As prompt freezes the internal timer (in Chrome, Opera and Safari), we can't set a timeout for the user's response. One way is to use html <input> instead of prompt. In this case setTimeout works as desired.
const input = document.getElementById("input");
const getRandomNumber = (upper) => Math.floor(Math.random() * upper) + 1;
const upper = 10;
let guessCounter = 0;
let randomNumber = getRandomNumber(upper);
let timer;
const play = () => {
if (timer) clearTimeout(timer);
input.value = "";
guessCounter++;
timer = setTimeout(() => {
if (confirm("Time is out. Play again?")) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
}
}, 5000);
}
document.getElementById("question").innerHTML = `I am thinking of a number between 1 and ${upper}. What is it?`;
document.getElementById("guess").addEventListener("click", () => {
let userGuess = parseInt(input.value);
if (userGuess > randomNumber) {
alert('Try again! Your number is too high');
play();
} else if (userGuess < randomNumber) {
alert('Try again! Your number is too low ');
play();
} else if (userGuess === randomNumber) {
if (confirm(`You have guessed the number! It took you: ${guessCounter} tries. Play again?`)) {
randomNumber = getRandomNumber(upper);
guessCounter = 0;
play();
} else {
clearTimeout(timer);
}
}
});
play();
<div id="question"></div>
<input id="input" type="input">
<button id="guess">Guess</button>
I recommend moving your game into a function and naming it, e.g. "startGame". Then, when the game finishes it, you can implement your timer to relaunch the game.
function getRandomNumber(upper) {
var number = Math.floor(Math.random()*upper) + 1;
return number;
}
function startGame() {
var randomNumber = getRandomNumber(6);
var userGuess;
var guessCounter = 0;
var playAgain;
while (userGuess != randomNumber){
userGuess = prompt('I am thinking of a number between 1 and 6. \n What is it? ');
guessCounter += 1;
if (parseInt(userGuess) > randomNumber) {
alert('Try again! Your number is too high ' );
} else if (parseInt(userGuess) < randomNumber) {
alert('Try again! Your number is too low ');
} else if (parseInt(userGuess) == randomNumber) {
break;
}
}
alert('You have guessed the number! It took you: \n ' + guessCounter + ' tries. ');
if (confirm('Do you want to play again?')) {
setInterval(startGame, 5000); // Start a new game in 5 seconds
}
}
startGame();
Bouncing my head off the wall here trying to figure out a better way to handle this. I have a large input value which has three checks to check the sum of certain parts of the string in order to validate it. I'm using three try/catch blocks in one function to run the check right now and it seems to be working except for the final validation check which always seems to return true. What I'm wondering is a) is this a good method to use, b) is there a cleaner way to do this with for loop and c) why my final check is not doing anything. Any help is appreciated. I have access to jQuery and Underscore.js if that helps but I have not worked much with underscore. I made a fiddle here:
Sample Fiddle
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
// run the checksum
var valid = false;
try {
var sum = (parseInt(number[0]) * 7) +
(parseInt(number[1]) * 3) +
(parseInt(number[2])) +
(parseInt(number[3]) * 7) +
(parseInt(number[4]) * 3) +
(parseInt(number[5])) +
(parseInt(number[6]) * 7) +
(parseInt(number[7]) * 3) +
(parseInt(number[8]));
alert(((sum % 10).toFixed(0)));
var checkDigit = ((sum % 10).toFixed(0));
if ((number[9]) === ("" + checkDigit)) {
alert('Our Checkdigit is valid', checkDigit);
valid = true;
}
} catch (e) {
alert('Fail for check 1!');
valid = false;
}
try {
var sum2 = (parseInt(number[13]) * 7) +
(parseInt(number[14]) * 3) +
(parseInt(number[15])) +
(parseInt(number[16]) * 7) +
(parseInt(number[17]) * 3) +
(parseInt(number[18]));
alert(((sum2 % 10).toFixed(0)));
var checkDigit2 = ((sum2 % 10).toFixed(0));
if ((number[19]) === ("" + checkDigit2)) {
alert('Our Checkdigit2 is valid', checkDigit2);
valid = true;
}
} catch (e) {
alert('Fail for check 2!');
valid = false;
}
try {
var sum3 = (parseInt(number[21]) * 7) +
(parseInt(number[22]) *3) +
(parseInt(number[23])) +
(parseInt(number[24]) * 7) +
(parseInt(number[25]) * 3) +
(parseInt(number[26]));
alert(((sum3 % 10).toFixed(0)));
var checkDigit3 = ((sum3 % 10).toFixed(0));
if ((number[27]) === ("" + checkDigit3)) {
alert('Our Checkdigit3 is valid',checkDigit3);
valid = true;
}
} catch (e) {
valid = false;
}
alert('All Good DUde!');
return valid;
}
Here is the way to do it.
I have not thrown any error, only error can be if the number is not parseable and so you can throw it if you like else if your sum checks can validate that should be good enough
window.onkeyup = keyup;
var number;
function keyup(e) {
number = e.target.value;
$('#numberValue').text(number);
// must be 10 characters long
if (number.length !== 30) {
return false;
}
number = "" + (number || "");
var valid = false;
//try{
var sum1 = returnSum(number,[0,1,2,3,4,5,6,7,8],[7,3,1,7,3,1,7,3,1]);
var sum2 = returnSum(number,[13,14,15,16,17,18],[7,3,1,7,3,1]);
var sum3 = returnSum(number,[21,22,23,24,25,26],[7,3,1,7,3,1]);
/*
//only if you are throwing err
}catch(e){
valid = false;
}
*/
if (number[9] === sum1 && number[19] === sum2 && number[27] === sum3) {
console.log(sum1 +'|' + sum2 + '|' + sum3);
valid = true;
}
console.log('All Good DUde!');
return valid;
}
function myParse(n){
return (isNaN(parseInt(n,10))) ? -1 : parseInt(n,10);
}
function returnSum(n,ind,mul){
var acc = 0;
var pNum = 0;
for(var i=0; i<ind.length; i++){
pNum = myParse(n[ind[i]]);
if(pNum == -1){
pNum=0;
//throw 'error';//if you really want to throw error on not a number / or your number should fail
}
acc += pNum * mul[i];
}
return (acc%10).toFixed(0)+'';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3> Sample test number to use -- copy and paste should work </p=h3>
<p>487013675311199070109160101300</p>
<input id="searchTxt" placeholder="add numbers together">
<div id='numberValue'>Number goes here</div>
Cheers. joy
From experience, you may want to separate as much math as possible in your try block. JavaScript has a weird way of handling variables and may not be doing what you think it is.
In the code below, when I set the userDoor variable to the prompted user input, the user input attaches to the variable. I know this because the value shows up in the console.log statement just below the variable declaration.
However, the variables revealDoor and offerDoor, which are set based on the userInput variable, act wonky in ways that suggest the variable didn't "catch" the value. (Wonky: easier to demonstrate than explain. please run the code below. UserDoor, revealDoor, and offerDoor should all be different numbers in the range of 1-3. Some of the time, revealDoor === userDoor. This should never happen. ).
Interestingly, the program works fine when I set userDoor directly to an integer--see commented debug line.
Why would the userInput variable show the right value in the console but not seem to catch in the rest of the program?
(This program, by the way, is meant to illustrate the monty hall paradox
alert("There are 3 doors. Behind two of them are DEATH and DOOM. Behind the other is a BIG TASTY SAUSAGE.");
var yWin = 0;
var yLoss = 0;
var nWin = 0;
var nLoss = 0;
while(true){ //noprotect
var userDoor = prompt("choose door: 1, 2, or 3");
//var userDoor = 1 //debug
console.log('UD: ' + userDoor);
var prizeDoor = randomRange(1,3);
console.log('PD: ' + prizeDoor);
var revealDoor = (function(){
var revealDoor = prizeDoor;
if (prizeDoor === userDoor) {
while (revealDoor === prizeDoor) {
revealDoor = randomRange(1,3);
}
return revealDoor;
}
else {
while (revealDoor === prizeDoor || revealDoor === userDoor){
revealDoor = randomRange(1,3);
}
return revealDoor;
}
})();
console.log('RD: ' + revealDoor);
var offerDoor = (function(){
var offerDoor = prizeDoor;
while(offerDoor === revealDoor || offerDoor === userDoor){
offerDoor = randomRange(1,3);
}
return offerDoor;
})();
console.log('OD: ' + offerDoor);
var choice = prompt("You chose door " + userDoor + ". Behind door " + revealDoor + ", I reveal DEATH AND DOOM. I would like to offer you the chance to change your choice to " + offerDoor + ". Do you accept--y/n?");
if(choice === "y"){
userDoor = offerDoor;
}
var result = (function(){
var result;
if(userDoor === prizeDoor){
alert("YOU FOUND THE PRIZE!");
result = 'w';
}
else {
alert("You chose DEATH AND DOOM!");
result = 'l';
}
return result;
})();
//Analytics:
switch(result){
case 'w':
if(choice === 'y'){
yWin++;
}
else {
nWin++;
}
break;
case 'l':
if(choice === 'y'){
yLoss++;
}
else {
nLoss++;
}
break;
}
var done = prompt("Are you Done? y/n");
if(done === "y"){
break;
}
}
function randomRange(min, max) {
return Math.floor(Math.random () * (max - min +1)) + 1;
}
var totalSamples = yWin + nWin + yLoss + nLoss;
var yChoices = yWin + yLoss;
var nChoices = nWin + nLoss;
console.log('With a sample set of ' + totalSamples);
console.log('You chose to change ' + (yChoices/nChoices * 100) + '% of the time.');
console.log('When you\'ve chosen to change, you\'ve won ' + (yWin/yChoices * 100) + '% of the time.');
console.log('When you\'ve chosen to stay, you\'ve won ' + (nWin/nChoices * 100) + '% of the time.');
var userDoor = prompt("choose door: 1,2, or 3")) * 1
Its better 2 use radio button for this
The problem is that prompt() returns a string. Which means any '===' comparisons are returning undefined. I need to convert the returned string to a number using Number().
var userDoor = Number(prompt("choose door: 1,2, or 3"))
Use
var done = confirm("Are you Done? y/n");
if (done) break;
Instead of d prompt confirmation
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.");