Get this Troll Program working - javascript

Scenario :
Attempted to create this troll 'guessing game program'.
It prompts the user to guess a number between 1-10, and the user will
get it wrong each time until they guess all numbers, frustrated, I
tell them to guess one last time, upon this attempt, it says your
answer was right!
Code - I am new at JS so I have not really gone into DOM manipulation and the code for some reason does not work.
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<script type="text/javascript">
var numset = 0;
var guess = numset + 1;
var max = numset >= 11;
while (guess !== max) {
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
} else {
alert("You Won! Number of guesses: 11")
}
</script>
</body>
</html>
Todo :
Please correct this
or Suggest any better approach, i am open to options.
Thank You.

One option would be to use a Set of numbers between 1 and 10, prompt for a number and remove it from the set until the set is empty, and then display the total number of guesses.
Note that because the program uses prompt, it will block the user's browser - consider using something less user-unfriendly, like an input and a button / enter listener, if at all possible.
// Set of numbers from 1 to 10:
const numSet = new Set(Array.from(
{ length: 10 },
(_, i) => i + 1
));
let guesses = 1; // to account for the final guess at the end
while(numSet.size > 0) {
const guessed = prompt("I am guessing a number between 1-10, let's see if you can guess it!");
numSet.delete(Number(guessed));
guesses++;
}
prompt("I am guessing a number between 1-10, let's see if you can guess it!");
alert("You Won! Number of guesses: " + guesses)

Related

Making a high score (best time) localStorage in JavaScript

I'm having a little bit of trouble wrapping my head around using a localStorage for a high score. I have saved the variable for the high score but now getting it to refresh with a new high score has become the issue.
So I have reverted back to the start and I have just these lines:
localStorage.setItem('score', timeDiff.toFixed(3));
parseFloat(document.getElementById("best_score").innerHTML = "My best time is " + localStorage.getItem('score') + " s");
My plan is then, if that user scores a better time than all their other attempts, this is saved as their best time.
I realise I need to do an "if" statement. So, the best I can come up with at the moment is human speak not JavaScript.
If score is nothing, then just print the new score.
If the score is better than the current printed score, then print that one instead.
If the score isn't as good as the current score, then don't do anything at all.
And that is it!
Be grateful for anyone to push me in the right direction of how to write those if statements.
There's no reason for the parseFloat in your example, but you will probably want parseFloat as part of this solution.
The update would look something like this:
// Get the previous high score if any, or `NaN` if none
// `localStorage.score` will be `undefined` if you've never stored a high score
// at all (or a string otherwise). `parseFloat` will return `NaN` if you pass it
// `undefined`, so we check that later.
const lastHighScore = parseFloat(localStorage.score);
// Get the string version of this score
const scoreString = timeDiff.toFixed(3);
let message;
if (isNaN(lastHighScore) || timeDiff > lastHighScore) { // ** Perhaps < ? Hard to tell from the question
// New high score
message = "Your new best time is " + scoreString;
// Store the new score
localStorage.score = scoreString;
} else {
// Not a new high score
message = "Your time was " + scoreString + "; your best time was " + localStorage.score;
}
document.getElementById("best_score").textContent = message;
Given the starting point seems to have a value in timeDiff, I couldn't see how a score could be "nothing."
(If you want to use getItem() and setItem() instead, note that getItem() will return null [not undefined] if the item doesn't exist. But parseFloat(null) also gives you NaN, so...)
Okay, based on what you wrote in the comment, your problem is not actually the if statements, but how to structure it so it gets updated properly.
The answer to this is creating a function that does all of this for you.
Let's call it updateHighscore.
This function will take a new score, then see if it's a high score and if it is, update everything accordingly.
Whenever a game is finished now, you just call this method.
E.g. See the following:
function updateHighscore(newScore) {
// get current highscore
const oldHighscore = parseFloat(localStorage.getItem('score'))
if (oldHighscore == null // if it doesn't exist yet
|| oldHighscore < newScore) { // or if it's smaller than the new score (I assume bigger means better here)
// current highscore needs to be updated
localStorage.setItem('score', newScore)
// html needs to be updated
document.getElementById("best_score").innerHTML = "My best time is " + localStorage.getItem('score') + " s"
}
}
Now, whenever the game is finished and you have a new score, just call this method with the score and it should update everything accordingly.
You have to write it like this when user gets a new highscore:
localStorage.setItem('score', timeDiff.toFixed(3));
document.getElementById("best_score").innerHTML = "My best time is " + parseFloat(localStorage.getItem('score')) + " s";
to check the highscore, do like this:
var highScore = parseFloat(localStorage.getItem('score'));
highScore = highScore > currentScore ? highScore : currentScore;
localStorage.setItem('score', highScore);

Score counter doesn't count scores properly

First off, I have to say that I am very new to Javascript and programming in general so it's possible that the issue is related to my (current) lack of knowledge.
I've tried to make a simple game where a computer thinks of a random number between 0 and 10 and the user tries to guess that number by typing his guess in the text field. If the number is correct, the user gets the message that they guessed the number correctly and otherwise, they get the message that the numbers are not correct.
The first part works as intended. The problem is the score counter.
So this is the part of the HTML code that I wrote for the counter:
<p id="points">Number of points: </p><span id="points-number">0</span>
And this is the code that I wrote in JS:
<script type="text/javascript">
document.getElementById("instructions").onclick = function() {
alert("You need to guess the number that your computer imagined. Viable numbers are between 0 and 10. Every time you guess the number, score increases by 1 and every time you miss, you will lose a point")
}
document.getElementById("guess-number").onclick = function() {
var ourNumber;
var randomNumber;
var pointsNumber = 0;
randomNumber = Math.floor(Math.random() * 10);
ourNumber = document.getElementById("input").value;
if (ourNumber == randomNumber) {
alert("The numbers are equal!");
pointsNumber+=1;
var result = document.getElementById("points-number");
result.innerHTML = pointsNumber;
} else {
alert("The numbers are not equal! The number that your computer imagined is:" + randomNumber + ", and our number is: " + ourNumber);
pointsNumber-=1;
var result = document.getElementById("points-number");
result.innerHTML = pointsNumber;
}
}
</script>
Now here's the problem...whenever the user misses the number, the number of points goes to -1. But if he misses the second time, it stays at -1, it doesn't decrease further. After the user guesses the number, the value changes from -1 to 1. But, if he guesses again, it doesn't increase to 2, it stays at 1. Then when he misses, it jumps back to -1 and vice versa.
So, I believe I am missing something here, what should I do to make the counter work as intended? In other words, to make the score increase by 1 every time the user guesses the random number and make it decrease by 1 every time he doesn't get it right?
Thanks in advance.
basically, you are always starting with
var pointsNumber = 0;
instead, you should use:
var pointsNumber = + document.getElementById("points-number").innerHTML;
bonus:
and yes instead of:
randomNumber = Math.floor(Math.random() * 10);
use:
randomNumber = Math.floor(Math.random() * 11);
because, Math.random() lies between 0 (inclusive) and 1 (EXCLUSIVE), so could never reach 10.
see more about Math.random() at: https://www.w3schools.com/js/js_random.asp
You need to declare pointsNumber outside of the function:
var pointsNumber = 0;
document.getElementById("guess-number").onclick = function() {
var ourNumber;
var randomNumber;
Otherwise, each time the onclick function is called, you declare pointsNumber and set it to 0. Then it gets +1 or -1 depending on the if/else, which explains the behavior you are observing.

How to write and call functions in javascript with for loops?

I am working on writing code for a course and need to figure out why the code output is not executing properly. I am very new to coding, this is a beginner assignment so all help and explanations are greatly appreciated.
The output should look like this:
Output:
How many times to repeat? 2
Stats Solver execution 1 ====================
give a number 10.10203
give a number 20
give a number 30
give a number 40
give a number 50
sum: 150.10203
average: 30.020406
max: 50
min: 10.10203
ratio: 4.94
Stats Solver execution 2 ====================
give a number 3.21
give a number 2.1
give a number 1
give a number 5.4321
give a number 4.321
sum: 16.0631
average: 3.21262
max: 5.4321
min: 1
ratio: 5.43
done ====================
Here is the code:
"use strict";
function myMain() {
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
}
function wall(){
var num1 = Number(prompt("provide a number"));
var num2 = Number(prompt("provide a second number"));
var num3 = Number(prompt("provide a third number"));
var num4 = Number(prompt("provide a fourth number"));
var num5 = Number(prompt("provide a fifth number"));
var sum = (num1+num2+num3+num4+num5);
alert("sum: " + sum);
var avg = (sum/5);
alert("average: " + avg);
var max = (Math.max(num1,num2,num3,num4,num5));
alert("max: " + max);
var min = (Math.min(num1,num2,num3,num4,num5));
alert("min: " + min);
var ratio = (max/min);
alert("ratio: " + Math.floor(ratio*100)/100);
}
myMain();
Well you really aren't very far off at all. Actually your solution has all the code you need just some of it is in the wrong place. I would have posted this as a comment but as this is a new work account I can't actually post comments so here is a full solution with the explanations.
Your wall function, while annoying with all the alerts is actually correct and doesn't need any adjustments. With that said you might want to play with parseInt and parseFloat to make sure you are getting valid numbers but I am assuming that is outside of the scope of the assignment.
Now on to your main function.
var num = Number(prompt("give a number of times to repeat, must be 0 or greater"));
This is ok and will prompt the user for a number, once again you might want to test that you got a valid number using the aforementioned links.
var count = num;
for (var a=0; a<=num; a++) {count++;}
alert("Stats Solver execution " + num + " ===================");
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This is where things start to fall apart a bit and where i think you are having problems. So I will break this down line for line and explain what each line is doing and you can compare that to what you think its doing.
var count = num;
Nothing crazy here, you are just creating another variable to hold the value in the num variable. Slightly redundant but not really a big deal.
for (var a=0; a<=num; a++) {count++;}
This is the line that appears to have given you the most confusion. This is the actual loop but inside the body of the loop { .... } nothing is being done except 1 is being added to count (count++). If I am understanding the assignment correctly, inside this loop is where you need to call your wall function after alerting the 'Stats Solver execution .....' stuff. All you need to do is move your function call inside this loop.
if (num===0){alert("done ==================="); return;}
wall()
alert("done ===================");
This part is clearly you a little lost and just trying things to get it to work, don't worry even after 12+ years of development i still write code like this ;). You really don't need this as the actual call to wall() will work fine for you.
I am bored and am waiting on work so for the sake of being a complete answer here is an example of how your code should look. Please don't just hand this in rather try and actually understand the difference between what i wrote and what you did because these are some very basic concepts that if you gloss over will make your life much harder down the road. Always feel free to ask, thats how people learn.
function myMain(){
// get the number of repetitions from the user and cast as a number
var num = Number(prompt('Please enter the number of times to repeat'));
// loop from 0 to the number the user provided - 1 hence the <
for (var i = 0; i < num; i++){
// alert the iteration of the loop, you will notice i add 1 to num when we alert it; this is because it starts at 0 so the first time it displays it would show 'Stats Solver execution 0 ======' instead of 'Stats Solver execution 1 ======'
alert('Stats Solver execution ' + (num + 1) + ' ===============');
// call your wall function
wall();
// go back to the top of the loop
}
// alert that we are done.
alert('done===============')
}
// your wall function goes here
// call your myMain function to kick everything off
myMain();
Just for fun you might want to look at console.log instead of alert to not make it such an annoying process with all the popups.
If i missed anything or you are confused about anything don't hesitate to ask and i'll do my best to answer.

Writing a Number Guessing program in JavaScript

Here is the question im trying to address and here is what I have. I am not sure what i've done wrong but it will not run in WebStorm:
alert("This is question 1");
var rndmNum = Math.rndmNum();
rndmNum = rndmNum * 100 + 1;
var i = 0;
do {
var rndmNum = prompt;
function guessNum(guess) {
if (guess < rndmNum);
}
alert("Your guess is too low");
} else if (guess > rndmNum) {
alert("Your guess is too high");
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Question 1</title>
</head>
<body>
<h1>Question 1</h1>
<p>
This is a page used to run/execute some JavaScript.
</p>
<p>
Next question.
</p>
<p>
Return home.
</p>
</body>
</html>
does anyone see any problems in what I have done or have any recommendations? Feedback is appreciated thanks
There's a syntax error:
function guessNum(guess) {
if (guess<rndmNum);
}
alert ("Your guess is too low");
}
else if (guess>rndmNum) {
alert("Your guess is too high");
}
Should be:
function guessNum(guess) {
if (guess<rndmNum) {
alert ("Your guess is too low");
}
else if (guess>rndmNum) {
alert("Your guess is too high");
}
}
You have an else if when your if statement was separated by an alert.
Also
Your brackets {} do not properly close.
The do is not syntactically correct or needed.
Math.rndmNum() is not a real method, think you want Math.random()
I only briefly looked at it. I don't really approve of giving answers for homework questions, but I will pose a question for you.
What if someone puts in something besides a number? You check if the answer is lower or higher, but you never make sure that it's actually a number.
You might want to consider either validating that the answer being checked is a number before checking it, or checking only for the answer you're looking for.
Also, var i = 0. I'll assume that you're going to use that later in your code, but i is pretty much a universal JavaScript variable.
What you're doing there is setting the global variable i to = 0, and most likely you're going to change that somewhere else in your code. Then you might run a for loop that rewrites i, or you might have an extension that rewrites it.
Consider naming your variables more uniquely, or keep the scope of the variables that aren't unique to functions or loops.
first of all. if you want to generate random number use:
Math.random() because Math.rndmNum is undefined
prompt is function and to use it you should write:
var rndmNum = prompt('geuss a number');
to convert random number from float to integer:
rndmNum = Math.floor(rndmNum * 100 +1);
and do-while loop should be:
do {
var rndmNum = prompt('geuss a number');;
function guessNum(guess) {
if (guess<rndmNum){
alert ("Your guess is too low");
}else if (guess>rndmNum) {
alert("Your guess is too high");
}
}
i++;
}while(i<10) // number of guesses

Trouble with Loop and Functions in Javascript

So i have an assignment and ive been doing it now for a few hours and am very stuck on a few parts of it. So the parts im stuck on is having to use a loop to validate information put into a prompt, and using information from an array to coincide with with a variable in another function and finally displaying all of it.
So I have everything set up but have no idea what exactly im getting wrong here if someone would mind helping point me in the right direction? Oh I should probably mention Im trying to get the second function to go with the array so when the user enters a number (1 through 4) it matches with the prices in the array.
function numSeats() {
//var amountSeat=document.getElementById("price");
var amountSeat=prompt("Enter the amount of seats you would like");
amountSeat=parseInt(amountSeat);
for (i=7; i<amountSeat; i++){
if (amountSeat<1 || amountSeat>6) {
alert("Check the value of " + amountSeat);
location.reload(true);
}else{
alert("Thank You");}
}
return amountSeat;}
function seatingChoice() {
//var seatChoice=document.getElementById("table").innerHTML;
var seatChoice=prompt("Enter the seat location you want.");
seatChoice=parseInt(seatChoice);
for (i=7; i<seatChoice; i++){
if (seatChoice<1 || seatChoice>4) {
alert("Check what you entered for " + seatChoice);
location.reload(true);
}else{
alert("Thank You")}
}
return seatChoice;}
var price=new Array(60, 50, 40, 30);
var name=prompt("Please enter your name.");
if (name==null || name=="")
{
alert("You did not enter a name, try again");
location.reload(true);
}
else
{
alert("Thank You");
}
document.write(name + " ordered " + numSeats() + " for a total dollar amount of " + seatingChoice(
) );
It looks to me like you repeat the same error in both numSeats and seatingChoice;
Let's look at what you're doing with your loop
var amountSeat = prompt("Enter the amount of seats you would like");
for (i=7; i<amountSeat.length; i++) {/* amountSeat[i] */}
prompt asks the client for a String, so amountSeat is a String.
amountSeat.length is thus the number of characters in the String.
You start your loop at i = 7, thus amountSeat[i] starts from the 7th character in the amountSeat (assuming there are at least 7 characters in amountSeat)
It looks to me more like you want to get a number from the prompt;
// string
var amountSeat = prompt("Enter the amount of seats you would like");
// to number
amountSeat = parseInt(amountSeat, 10); // radix of 10 for base-10 input
Next, consider your if
if (amountSeat[i]<1 && amountSeat[i]>6) {
This is saying if less than 1 AND more than 6. No number can be both of these states at the same time, so it will always be false. It looks like you wanted to use an OR, ||
// do your check
if (amountSeat < 1 || amountSeat > 6) { /* .. */ }
Finally, it looks like you want to calculate the price by some logic, which you haven't included. However, I'm sure it will be based upon numSeats and seatingChoice so you will need to keep a reference to these choices.

Categories

Resources