Random Number Guessing Game - Limit the Number of guesses - javascript

I'm trying to make a program that generates a random number which the user guesses. It also limits the number of guesses the user can make (or is supposed to.)
var highLimit = 5;
var randNum = Math.floor((Math.random() * highLimit) + 1);
var allowedGuesses = 2;
var numGuesses = 0;
function guessingGame() {
if (numGuesses <= allowedGuesses) {
do {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
} while(numGuesses < allowedGuesses && inputNum != randNum);
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
numGuesses = 0;
function newGame() {
randNum = Math.floor((Math.random() * highLimit) + 1);
guessingGame();
return false;
}
And the HTML:
<form name = "numForm">
<fieldset>
<label for = "randNum">Enter a number between 1 and 5: </label>
<input type = "text" name = "number" value = "" id = "randNum" size = "1" maxlength = "1" />
</fieldset>
<input class = "button" type = "button" name = "submit" onclick = "guessingGame()" value = "Submit Number" />
<input class = "button" type = "reset" name = "newGame" onclick = "newGame()" value = "New Game" />
<fieldset>
<textarea name = "gameResults" onclick = "" readonly = "true" value = "" rows = "5" cols = "40" ></textarea>
</fieldset>
</form>
Right now, the program is stuck in a infinite loop since highLimit is set at 5. But if I set it at ten, the program works. How can I fix it so it works at any value? I would also appreciate other suggestions for improvement.
Thanks in advance!

I think you don't need a loop in this one. You can simple say:
function guessingGame() {
if (numGuesses < 0){numGuesses=0;}
if ((numGuesses < allowedGuesses) && (inputNum != randNum)) {
inputNum = document.numForm.number.value;
inputNum = parseInt(inputNum);
if (inputNum < randNum && inputNum > 1) {
document.numForm.gameResults.value = "Sorry, your guess was too low.";
numGuesses++;
}
else if (inputNum > randNum && inputNum < highLimit) {
document.numForm.gameResults.value = "Sorry, your guess was too high.";
numGuesses++;
}
else if (inputNum == randNum) {
document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
numGuesses++;
}
else {
document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
numGuesses--;
}
}
else {
document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
}
return false;
}
the if (numGuesses < 0){numGuesses=0;} will help also. for negative cases.

This is an update for:
Ran the Snippet and answeared in "0 tries"
This is how I did it: But you're going to have to replace the 'prompts' and 'alerts' with your specified inputs and outputs, if you still need it after 4 years:
let maximum = parseInt(prompt('Enter the maximum number!') );
while(!maximum) {
maximum = parseInt (prompt('Please enter a valid number') )
}
const targetNum = Math.floor(Math.random()*maximum)+1;
let attempts =0;
let maxAttempts = Math.ceil(maximum/2);
// ==== Uncomment the line below to cheat --> ======
// console.log(targetNum)
let guess = parseInt(prompt(`Enter your first guess!, you have ${maxAttempts} attempts (press 'q' anytime to escape from this hellish nightmare)`));
while(parseInt(guess) !==targetNum && attempts < maxAttempts-1) {
if (typeof(guess) === 'string' && guess.toLowerCase() ==='q') {break;}
attempts++;
if(guess>targetNum) {
guess = (prompt(`Too High! Enter new guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}else {
guess= (prompt(`Too low! Entere a new Guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
}
}
if(typeof(guess) === 'string' && guess.toLowerCase() ==='q') {
alert(`You gave up after ${attempts} attempts`);
}
else if(attempts >= maxAttempts-1) {alert(`Oops, your ${maxAttempts} attempts ran out, the number was ${targetNum}: Verification : ${targetNum==guess}`);}
else {
alert(`Good job, you got it ${attempts+1} attempts!, the number was ${targetNum}: Verification : ${targetNum==guess}`) ;
}

Related

sea battle game / prevent typing the same thing twice

such a problem is that if I enter the same number 3 times and it counts for me as a win, but I need to prohibit it so that I cannot enter the same number a second time, can you tell me how to do this?
let randomLocation = Math.floor(Math.random() * 6)
let location1 = randomLocation
let location2 = location1 + 1
let location3 = location2 + 1
let guess
let hits = 0
let guesses = 0
let isSunk = false
while (isSunk == false) {
guess = prompt('Enter the coordonation: ')
let secondTime = guess
if (guess < 0 || guess > 6) {
alert('Your number is incorrect')
} else {
guesses++
if (guess == location1 || guess == location2 || guess == location3) {
alert('SHOT')
hits++
if (hits == 3) {
isSunk = true
alert('The ship was wrecked')
}
} else {
alert('you missed')
}
}
}
let stats = 'You wrecked from ' + guesses + ' attempts ' + ' which means you have statistics ' + (3 / guesses)
console.log(stats)
Here's one way to check to see if the user has entered the same thing before. Use a Set.
let answers = new Set();
while(true) {
let input = prompt('Enter something')
if (input == null) break;
if (answers.has(input)) {
alert('You already entered that.');
} else {
alert('That is new!')
answers.add(input); // Remember this input for later.
}
}

How to check whether i submit blank input in javascript? i have written a program but it is not working

I have written a javascript code in an HTML file using a script tag,
where I want to know whether my input is greater than or less than 10
or equals to 10 or any blank input. I use the if-else method to solve
this problem, but my last else if condition which is "Your input is
blank" not outputting in any way.
//f1 function will run when some hit the submit button
function f1() {
//here we are taking the value of the input field using id "myinput" in the variable called myinputvar
var myinputvar = document.getElementById("myinput").value;
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
} else if (myinputvar = " ") {
document.getElementById("txt").innerHTML = "Your input is blank";
}
}
<!-- this is the input tag to take inputs from user -->
Enter a integer number between 0 to anynumber = <input type="text" id="myinput"><br><br>
<!-- this is the button to submit the value -->
<button onclick="f1()">submit</button>
<!-- this is the heading tag to print the output -->
<h1 id="txt"></h1>
Wrap in a form and make it required
Also cast to number
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
//here we are taking the value of the input field using id "myinput" in the variable called myinputvar
var myinputvar = +document.getElementById("myinput").value; // make it a number
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
} else if (myinputvar = " ") {
document.getElementById("txt").innerHTML = "Your input is blank";
}
})
<form id="myForm">
Enter a integer number between 0 to anynumber =
<input type="text" required id="myinput"><br><br>
<button>submit</button>
</form>
<h1 id="txt"></h1>
A general way to check for only whitespace input uses the regex pattern ^\s*$. Sample code:
if (/^\s*$/.test(inputvar)) {
document.getElementById("txt").innerHTML = "Your input is blank";
}
pay attention not to use the shortcut:
if (inputvar) {
// this won't catch "0"!
}
but the more proper
if (inputvar === "") {
// is empty
}
and of course you should check for this condition first, if you want to handle numbers as input.
You can use ASCII code to check for that
else if(myinputvar.carCodeAt(0) === 13) {
document.getElementById("txt").innerHTML = "Your input is blank";
}
13 is ASCII code of enter key
https://www.asciitable.com/
> This method is also working, the logic is i should have use a nested
> if like this
function f1() {
var myinputvar = document.getElementById("myinput").value;
if (myinputvar == "") {
document.getElementById("txt").innerHTML = "Your input is blank";
} else {
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
}
}
}
As Tim Biegeleisen mentioned, it worked in this way:
var myinputvar = document.getElementById("myinput").value;
if (/^\s*$/.test(myinputvar)) {
document.getElementById("txt").innerHTML = "Your input is blank";
} else {
if (myinputvar > 10) {
document.getElementById("txt").innerHTML = "Your input number is greater than 10";
} else if (myinputvar < 10) {
document.getElementById("txt").innerHTML = "Your input number is less than 10";
} else if (myinputvar = 10) {
document.getElementById("txt").innerHTML = "Your input number is 10";
}
}
Check if the given input value is a valid number or not
function isNumber(n){ return /^-?[\d.]+(?:e-?\d+)?$/.test(n); }

can not display the dialog when load both file .js or .html?

I am having trouble with this problem. When I coded this very simple javascript code from head first javasript book, they said to me that I must saved it as the name battle.js and run it, but after that, they said to me that I must run it as the name battle.html. Here is the code
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = promt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3/guesses);
alert(stats);
As they described, it must appear a dialog and we can enter something into that, but when I ran it, nothing appeared.
I just a newbie with javascript, could you please give me some ideas ? Thank you very much.
Your code has typing mistake. replace promt to prompt
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3 / guesses);
alert(stats);

Javascript won't display message

I'm trying to create a simple program where a user needs to pick a maximum number, then try to guess a number between 1 and that maximum number. When they enter their guess, I need to validate the input, and offer a choice of feedback: different messages if it's (1) not a number, (2) a number not within the range, (3) the correct guess, (4) too high, but within range, and (5) too low, but within range.
function do_guess(prompt) {
let valid_input = false;
let guess = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
while (!valid_input) {
input = window.prompt(prompt);
guess = Number(input);
if (isNaN(guess)) {
message.innerHTML = "That is not a number!";
} else if (guess < 1 || guess > val) {
// val = max_num - "I wasn't sure how to code this."
message.innerHTML = "That number is not in the range, try again.";
} else if (guess == num) {
valid_input = true;
message.innerHTML = "You got it!";
} else if (guess > num) {
message.innerHTML = "No, try a lower number.";
} else {
message.innerHTML = "No, try a higher number.";
}
}
}
do_guess("Number from 1 to 10")
Guess <input id="guess" value="" />
<div id="message"></div>
Based on your requirements, I'm loading the max_val from the input box and calling the do_guess function with a new button.
function do_guess(prompt) {
let valid_input = false;
let max_val = Number(document.getElementById("guess").value);
let message = document.getElementById("message");
let output = '';
let num = Math.floor((Math.random() * max_val) + 1);
prompt = prompt + max_val;
while (!valid_input) {
input = window.prompt(prompt + output);
let guess = Number(input);
if (isNaN(guess)) {
output = " That is not a number!";
} else if (guess < 1|| guess > max_val) {
output = " That number is not in the range, try again.";
} else if (guess == num) {
valid_input = true;
message.innerHTML = "You got it!";
} else if (guess > num) {
output = " No, try a lower number.";
} else {
output = " No, try a higher number.";
}
}
}
Max Guess <input id="guess" value="" />
<div id="message"></div>
<button onClick="javascript:do_guess('Number from 1 to ')">
Guess
</button>

more than currency input field

I have this input tag where you put the total of your receipt :
<input type="text" name="currency" id="currency" class="text-input" onBlur="this.value=formatCurrency(this.value);" />
The Javascript is as follows:
<script type="text/javascript">
function formatCurrency(num) {
num = num.toString().replace(/\$|\,/g,'');
if(isNaN(num)) {
num = "0";
}
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num % 100;
num = Math.floor(num/100).toString();
if(cents < 10) {
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) {
num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
}
return (((sign)?'':'-') + '$' + num + '.' + cents);
}
</script>
Users can only enter receipts more than $10.00 bucks, how can I set that on my script? Also they need to know they can not enter currency less than $10.
From what I can gather from your question I think you are looking for something like this. Basically if we have a valid entry such as $100.00 we continue, return true etc, else if we have something that looks like an int or float we can reformat this and recurse the function, else hint user for of vaild entry
var foo = document.getElementById('foo');
foo.addEventListener('blur', function(e) {
var val = e.target.value;
var err = document.getElementById('err');
var errMsg = 'please enter a value $10.00 or greater';
var patt = /^\$\d+\.\d{2}$/;
var amount = parseInt(val.replace(/\$|\./g, ''));
if (val !== '') {
if (patt.test(val)) {
if (amount < 1000) {
err.textContent = errMsg;
} else {
document.getElementById('suc')
.textContent = 'processing request';
}
} else if (typeof amount == 'number' && !/[a-z]/g.test(val)) {
if (/\.\d{2}/.test(val)) {
e.target.value = '$' + (amount / 100);
} else {
e.target.value = '$' + amount + '.00';
}
arguments.callee(e);
} else {
err.textContent = errMsg;
}
}
});
here is a demo
You can apply a validation function when submitting the form to test if the value is below a threshold, such as:
function validate()
{
value = document.getElementById('currency');
if (value <= 10.00)
{
return false
} else
{
return true;
}
}
You could also apply this to the onblur event, but my preference is to present validation errors when the form is submitted.
It looks like you're trying to parse a string, convert it nicely into dollars and cents, and reject it if it's less than 10. There's a much nicer way to do that:
function formatCurrency(num) {
// Remove the dollar sign
num = num.replace("$", "");
// Change the string to a float, and limit to 2 decimal places
num = parseFloat(num);
Math.round(num * 100) / 100;
// If its less than 10, reject it
if(num < 10) {
alert("Too small!");
return false;
}
// Return a nice string
return "$" + num;
}
At the end, are you trying to return -$99.94 if the number is negative?

Categories

Resources