guessing game in javascript using while loop and unlimited guesses - javascript

var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = true;
while (userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!');
userIsGuessing++;
if (guess < x && (x - guess) < 15) hint += ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint += ' Way too small!';
else if (guess > x && (x - guess) < 15) hint += ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint += ' Way too big!';
else(guess === x); {
document.writeln("You win! It took you" + userIsGuessing + " times to
guess the number.
");
}
}
I am trying to get this code to ask the user to guess a number between 1 and 100. Each time the user guesses, they get one of four hints. Then at the end, when they guess correctly, they will be told how many guesses it took them. I'm really stuck, please help.

How to begin..
userIsGuessing is a boolean, you should never use ++ on it.
You are writing in the document that the user win, you should alert it, like the prompt but ok.
Do not increment your hint, the ergonomics is terrible.
Check the comment
var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = false; // Boolean, begin at false
var count = 0; // Will count the try of the users
while (!userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!'); count++; // We increment count
if(guess == x) { // CHECK IF RIGHT FIRST. EVER FOR THIS KIND OF STUFF.
userIsGuessing = true; // If right, then the Boolean come true and our loop will end.
alert("You win! It took you" + count + " times to guess the number.");
}
if (guess < x && (x - guess) < 15) hint = ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint = ' Way too small!';
else if (guess > x && (x - guess) < 15) hint = ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint = ' Way too big!';
}

Related

making a point counter for a dice game in javascript

I am trying to make a dice game point counter where you are awarded points based on how close your guess of what you thought the number was going to be to what the number rolled is. My current code looks like this
function continueL(e){
if (e.keyCode == Keyboard.letter('L')){
add(copter);
var evorod = readInt("What number do you think it's going to be? You are guessing ");
println("Please click the die to roll a number");
mouseClickMethod(contin);
}
}
function contin(e){
var num = Randomizer.nextInt(1,12);
println("The number rolled is.... " + num);
var numText = new Text("The number rolled is...." + num, "20pt Arial");
numText.setPosition(50, 200);
numText.setColor(Color.red);
add(numText);
if (num == evorod){
println("Congrats! You Win! Here is 100 points");
} else {
if(num == evorod - 1 || num == evorod + 1){
println("So close! Here is 80 points!");
} else {
if(num == evorod - 2 || num == evorod + 2){
println("Almost got it. Take 60 points!");
} else {
if(num == evorod - 3 || num == evorod + 3){
println("Nice try. Take 40 points!");
} else {
if(num == evorod - 4 || num == evorod + 4){
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
}
}
}
}
remove(copter);
}
But it only displays the final else no matter what your guess was vs the number rolled.
edit: evorod is a global variable
evorod needs global scope, right now it only exists inside the continueL() function so will be undefined when you try to use it in contin(). Fix that by declaring it outside the function.
Meanwhile your if statements could be simplified to this, instead of a bunch of separate nested conditionals:
if (num == evorod) {
println("Congrats! You Win! Here is 100 points"); // there is no println in javascript, I'll assume you've coded your own equivalent
} else if (num == evorod - 1 || num == evorod + 1) {
println("So close! Here is 80 points!");
} else if (num == evorod - 2 || num == evorod + 2) {
println("Almost got it. Take 60 points!");
} else if (num == evorod - 3 || num == evorod + 3) {
println("Nice try. Take 40 points!");
} else if (num == evorod - 4 || num == evorod + 4) {
println("Whoops... maybe next time? Take 20 points");
} else {
println("Better luck next time.");
}
Try a switch statement instead. There are 6 possible outcomes per throw. If you guessed less or more than the actual outcome you lose 20 points per digit away from the true outcome.
First of all, let's find how off your prediction was from the roll. We do that by subtracting (excuse my shabby math).
int outcome = ...
int guess = ...
int difference;
if(outcome > guess)
difference = outcome - guess;
else if(outcome < guess)
difference = guess - outcome;
switch(difference)
{
case 0:
{
System.out.println("100 Wondred points!");
break;
}
case 1:
{
System.out.println("You get 80 hamsters!");
break;
}
}
And so on it goes, with a difference of 5 being the lowest score because it means you were 5 numbers away from the outcome.

how to have the return answer as a whole number

I'm a beginner in javascript and I just made this program as an exercise that can basically guess your number in 7 tries or less, but the problem is that i keep getting the (Answer Variable) as a decimal number and I want it to be only a whole number. How do I do that ?
console.log('I will guess the number you\'re thinking of in 7 guesses maximum\n\t\tThink of a number between 1 and 100')
console.log('\n\n')
let low = 0;
let high = 100;
let answer = (high + low) / 2
let guess = Number(prompt("Pick a number"))
for(let a = 1; a < 7; a++){
console.log(`Is your number ${answer} ?`)
let ud = Number(prompt(`Press : 1-Larger, 2-Smaller, 3-Current Number`))
if(ud == 1){
low=answer
answer=(high + low) / 2
} else if (ud == 2){
high=answer
answer=(high + low) / 2
} else if (ud == "c"){
break;
}
}
console.log(`This is magic`); ````
That is because if you devide an odd number by 2 it will always give a decimal number. You can use Math.floor
console.log('I will guess the number you\'re thinking of in 7 guesses maximum\n\t\tThink of a number between 1 and 100')
console.log('\n\n')
let low = 0;
let high = 100;
let answer = (high + low) / 2
let guess = Number(prompt("Pick a number"))
for (let a = 1; a < 7; a++) {
console.log(`Is your number ${answer} ?`)
let ud = Number(prompt(`Press : 1-Larger, 2-Smaller, 3-Current Number`))
if (ud == 1) {
low = answer
answer = Math.floor((high + low) / 2)
} else if (ud == 2) {
high = answer
answer = Math.floor((high + low) / 2)
} else if (ud == "c") {
break;
}
}
console.log(`This is magic`);

checkPrime function returns incorrect values

numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num in numbers) {
if (num % i === 0) return num + ' is not prime';
else {
return num + ' is prime';
}
return num !== 1;
} else {
return num + ' is not in range';
}
}
}
console.log(checkPrime(27));
Hi.
In the above code, I tried to create a function which returns information about whether a number is prime or not.
However, it fails in some cases. Like eg. in the case of 27 or 145, it returns the values are prime, which obviously is false. How can I amend this program to make it work?
Also, what is the smartest way of merging the case for number 2 and the rest prime numbers?
Thanks in advance and sorry if this is too basic, I could not find the right answer anywhere else.
You are putting the 'else' clause that states the number is prime before having finished to check all numbers until itself -1.
To be optimal, you don't need to loop until the number ( < num). Just until the square root of the number. (even better than looping until num/2) For example : 167 can be seen that is prime when the loop has reached 13. 13*13 = 169 > 167 so you can stop and safely afirm that 167 is prime.
For number 2 it is correct to have a sepparate case.
Below is the code for checking a single value if it is prime:
function checkPrime(num) {
if (num == 1 || num === 0) {
return 'It is a separate case'
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < Math.sqrt(num); i++) {
if (num % i === 0) return num + ' is not prime';
}
return num + ' is prime';
}
alert(checkPrime(27));
I have rewritten the code to provide the right answer
numbers = [];
for (x = 1; x <= 1e4; x++) {
numbers.push(x)
}
//console.log(numbers)
function checkPrime(num) {
if (num == 1 || num == 0) {
return 'It is a separate case'
}
// check this condition outside the loop
if (!(num in numbers)) {
return num + ' is not in range';
}
if (num == 2) {
return num + ' is prime'
}
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return num + ' is not prime';
}
}
return num + ' is prime';
}
console.log(checkPrime(27));
I've rewritten your code and made a couple of changes.
The reason you were having your problem is that you were returning in the for loop meaning all odd numbers would declare themselves as prime numbers.
I've fixed this but also I've I rearranged things a little, to be as efficient as possible it's good to bail as soon as possible so I do a couple of checks to bail initially I check if the number is in range, if not bail.
I've commented the code so it makes sense but if you don't understand why I've done something feel free to ask.
// make an array of all numbers between 0 and 10000
numbers = [];
for (x = 0; x <= 1e4; x++) {
numbers.push(x)
}
function checkPrime(num) {
// return if input number is not in numbers array
if (numbers.indexOf(num) == -1) return num + ' is not in range'
// return if number is 0 or 1
if (num <= 1) return 'It is a separate case'
// check all numbers between 2 and input number
// return if any number devides neatly
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
// if you get this far it's prime
return num + ' is prime';
}
console.log(checkPrime(27));
Personally, for the range, I wouldn't have an array of all the values but I've left this in just in case there was some other reasoning we don't know about.
EDIT:
As you've said the initial array is not important I've remade the code to work without it, I've not included comments this time (to save space) but that code does the same thing and is mostly unchanged.
function checkPrime(num) {
if (num < 0 || num > 1e4) return num + ' is not in range'
if (num <= 1) return 'It is a separate case'
for (var i = 2; i < num; i++)
if (num % i === 0) return num + ' is not prime';
return num + ' is prime';
}
console.log(checkPrime(27));
Anyway, I hope you find this helpful 🙂

Find the sum of a Javascript array and divide by its length

I'm almost embarrassed to ask this.
I'm a beginner programmer, and Javascript is very confusing to me. I managed to put together this much with the help of my instructor, but there are some simple things I can't get right.
I tried search Stack Overflow for a thread that would answer my question, but all of them I've seen contain code that I haven't learned about yet, so they're all just gibberish to me.
What I'm trying to do is add all the values of an Array and divide the sum by the array's length, ergo, find the average. The description of the assignment is find the average of any number of students' grades.
My two problems are
I can't figure out how to get the sum of all numeric values in the Array and,
For some reason, array.length returns one more than the actual length of the Array, even if I add a -1. (ex. if I enter 6 values, the array.length would return 7.)
I know where the problem is but I can't figure out what I need to enter. This assignment is due tomorrow, so anyone's time and effort is appreciated.
Here is my script:
<script type="text/javascript">
var allGrades = new Array();
var g = 0;
var l = 0;
var s = 0;
var t = 0;
do {
allGrades[g] = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "")
g++;
}
while (allGrades[g - 1] != "x")
for (l = 0; l < allGrades.length - 1; l++) {
s += allGrades[l] // Where I think the problem is
}
t == s / g - 1;
g == allGrades.length - 1; //
window.alert(g)
switch (t) {
case (t >= 90):
window.alert("Your average grade is " + (t) + ". " + "This is an A.")
break;
case (t >= 80 && t < 90):
window.alert("Your average grade is " + (t) + ". " + "This is a B.")
break;
case (t >= 70 && t < 80):
window.alert("Your average grade is " + (t) + ". " + "This is a C.")
break;
case (t >= 60 && t < 70):
window.alert("Your average grade is " + (t) + ". " + "This is a D.")
break;
case (t <= 60):
window.alert("Your average grade is " + (t) + ". " + "This is a failing grade.")
break;
}
</script>
I'm sorry if what I'm asking seems dumb. I've only been taking web programming for about two months, so I could really use some help!
Kyle
== is the comparison operator. You need to use the assignment operator (=) here:
t==s/g-1;
And the lines near it.
Also, for your own sake, do not use single-letter variable names unless you have a good reason for doing so.
Here's a cleaner way of writing the script:
var grades = [];
do {
var input = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "");
grades.push(parseFloat(input));
} while (input != 'x');
var sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[l];
}
var average = (sum / grades.length) * 100;
var grade;
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else {
grade = 'failing grade';
}
alert('Your average grade is ' + average + '. ' + 'This is a ' + grade);
t==s/g-1;
g==allGrades.length-1; //
Are both Comparisons, for assignment they should be
t=s/g-1;
g=allGrades.length-1;

Error in JavaScript return code?

Here is the javascript code:
There is an error in code where nightSurcharges is added to total cost even if pickUptime is less than 20.
function TaxiFare() {
var baseFare = 2;
var costPerMile = 0.50;
var nightSurcharge = 0.50; // 8pm to 6am, every night //its flat 0.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime == "") || (pickupTime < 0) || (pickupTime > 23)) {
alert("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
alert("Your taxi fare is $" + cost.toFixed(2));
}
I want nightSurcharge to be added only when pickupTime is >=20, but that's not working right now.
Any help is appreciated. Thanks
This seems obvious to me.
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
This code right here adds nightSurcharge to the cost if pickupTime is greater than or equal to 20, OR less than 6. So of course it's added if it's less than 6.
if (pickupTime >= 20) {
cost += nightSurcharge;
}
Now it will only add to it if it's greater or equal to 20.
your code is:
if (pickupTime >= 20 || pickupTime < 6)
so if pickupTime is less then 6 it'll enter the if as well
http://jsfiddle.net/7rdzC/

Categories

Resources