Javascript Random Guess Game - javascript

https://jsfiddle.net/andrew_jsfiddle/eyLyqajz/1/
Assignment 1 - Using your JSFiddle account you are going to create a guessing game, only it will be the computer doing the guessing. Here is how it works - the computer will ask you for a number between 1 and 1000, it will check first to make sure your input is within the bounds.
Once you enter the number it will guess the number and do a comparison with the number you entered. It will output the results of the guess and continue to do this until it gets the correct answer. This is what the output of the program will look like (if I enter 329)
For this attempt I did:
var guessnum= new Guessnum(1000);
document.getElementById("click").onclick= function() {
guesslist()};
function guesslist() {
document.getElementById('guessnum').innerHTML= InsertGuess();
}
function InsertGuess() {
for (var a= 0; a < guessnum.length; a++){
guessnum[a] = Math.floor((Math.random() * 1000) + 1);
}
var show_guess="";
for (i=0; i < guessnum.length; i++){
show_array += "You guess" + guessnum[i] + "of " + i + "<br>";
}
return document.getElementById('guess').innerHTML=show_array;
}

Use a listener on the input with a global variable that contains the random number
var myRandomNumber;
input.addEventListener('input', function(){
}
)
You'll need to click first on the button though.
Fiddle

My friend, I think you are really confused. It wouldn't help to just create it for you. Break down the requirements to actionable steps and start from scratch. You want to create a guess game that you set a number. Think it as simply as possible:
Action 1 - Set a number -->
Create the field
Action 2 - Check if number is valid(1-1000) -->
Get the value entered and make the necessary checks
Action 3 - Computer tries to guess by selecting a num up to 1000 -->
Generate random num from 1-1000
Action 4 - Compare number with the one you set before -->
Simple comparison of generated number and the selected one
Action 5 - Proceed as needed -->
If it's the exact number it won and it will stop!
If it's higher then the next guesses should have this number as highest limit.
If it's lower then the next guesses should have this number as lowest limit.
Action 6 - Show guess and result of comparison --> Simply show the results of the previous actions
Action 7 - If not successful guess --> repeat until the number is guessed
Try to apply this kind of logic to all these problems.

Related

In school and trying to create the classic guess a number game. What did I do wrong?

This code is supposed to be a guess the number game. The object is to get JS to display an alert box that asks the user to guess a number. When they guess a number, the code is supposed to return the values of what they have guessed until they get it correct.
When I run the play key, an alert box does pop up, and says:
"Enter a guess between 1 and 100"
After that, even if I enter all 100 numbers, the box re-loads forever.
Here's what I have:
const game = {
title: 'Guess the Number!',
biggestNum: 100,
smallestNum: 1,
playerChoice: null,
secretNum: null,
//1. Add a prevGuesses property to the game object initialized to an empty array.
prevGuesses: [],
//2. Add a getGuess method to game that prompts the player to enter a guess with a message formatted as: Enter a guess between [smallestNum] and [biggestNum]: Hint- Use a template literal for the prompt message.
//3. Ensure that the getGuess method returns a value that is:
//-is a number, not a string
// -is between smallestNum and biggestNum, inclusive
// -Hints: This is a great use case for a while loop. parseInt returns NaN if the string cannot be parsed into a number
getGuess: function() {
while (this.playerChoice !== this.secretNum) {
var playerChoice = prompt(`Enter a guess between ${this.smallestNum} and ${this.biggestNum}: `);
var wholeNumber = parseInt(this.playerChoice);
if (this.wholeNumber > this.biggestNum) {
var wholeNumber = 100;
}
if (this.wholeNumber < this.smallestNum) {
var wholeNumber = 1;
}
if (typeof this.wholeNumber !== "number")) {
var wholeNumber = Math.floor(Math.random() * 100)
}
}
},
//4. From within the play method, invoke the getGuess method and add the new guess to the prevGuesses array
play: function() {
this.secretNum = Math.floor(Math.random() *
(this.biggestNum - this.smallestNum + 1)) + this.smallestNum;
game.getGuess();
this.prevGuesses.push(this.wholeNumber);
//6 the play method should end(return) when the guess matches the secretNum
if (typeof(this.wholeNumber) === "number" && this.wholeNumber !== this.secretNum) {
game.render();
}
},
// 5. Add a render method to game that play will call after a guess has been made that alerts:
// -if the secret has been guessed: "Congrats! you guessed the number in [x] guesses!"
// otherwise
// -"Your guess is too [high|low]"
// "Previous guesses: x, x, x, x"
// Hints: render wont be able to access any of play's local variables, e.g., guess, so be sure to pass render any arguments as needed. Template literals not only have interpolation, they honor whitespace - including line breaks! The list of previous guesses can be generated using the array join method.
render: function() {
if (this.wholeNumber === secretNum) {
alert(`Congrats! You guessed the number in ${game.prevGuesses.length} guesses!
Previous guesses: ${prevGuesses}`);
} else if (this.wholeNumber > this.secretNum) {
alert(`Your guess is too high!
Previous guesses: ${this.prevGuesses}`);
game.guess();
} else if (this.wholeNumber < this.secretNum) {
alert(`Your guess is too low!
Previous guesses: ${this.prevGuesses}`);
game.guess();
}
}
};
game.play();
/*
Allow the player to continually be prompted to enter their guess of what the secret number is until they guess correctly
If the player has an incorrect guess, display an alert message that informs the player:
Whether their guess is too high, or too low, and...
A list of all the previously guessed numbers (without showing the square brackets of an array)
If the player has guessed the secret number:
Display an alert message that congrats the player and informs them of how many guesses they took
End the game play*/
/*
Bonus: when play is run, immediately prompt the player to enter the smallest and biggest numbers instead of having them pre-set*/
The research that I've done: I've googled as many pages as I could find and youtube tutorials on functions, play object, loops within arrays, anything that I could think of that's related to the types of objects in this code.
the comment text is from the assignment. While I was working on it, I put the comments next to the code that I was working on.
I really am only a few weeks into coding and appreciate any feedback.
This is the original code that I was provided:
const game = {
title: 'Guess the Number!',
biggestNum: 100,
smallestNum: 1,
secretNum: null,
play: function() {
this.secretNum = Math.floor(Math.random() *
(this.biggestNum - this.smallestNum + 1)) + this.smallestNum;
}
};
There are several issues with your code:
this.wholeNumber never receives a value, so that will not work. Also, it does not seem the purpose of this exercise to have such a property. You should not have to store the user's guess in a new property this.wholeNumber. See next point:
The goal of getGuess is to return a number, but there is no return statement. You seem to want to store the number in a property, but that is not the assignment.
Related to this: in play you should get the guessed number as a return value from the call to getGuess
The goal of getGuess is not to wait for the user to guess right, only for the user to make a valid guess (within range and not NaN). So the condition of your while loop is not correct.
getGuess does not verify that parseInt returned NaN. Note that the type of NaN is "number", so the last if's condition will never be true. You should use the isNaN function, or better Number.isNaN.
play should always call render, not only when the guess is right.
render should be called by passing it an argument (the guessed number), and thus the render method should define a parameter for it.
The render method should not call game.guess(). That is not its job.
The play method should not put a new value in secret, otherwise the user will be playing against a moving target :) The secret should be set once in the main program
The main program -- where you currently just have game.play() -- should have the looping logic, which you had tried to implement elsewhere. Here is where you should repeat calling game.play() until the guess is right. It is also here where you should display alert messages about guesses that are too low, too high, ...etc.
There is no clear instruction where the main program should get the latest guess from. It can get it from game.prevGuesses, but I would suggest that the play method also returns the latest guess, just like getGuess should do.
Take note of the other instructions that are given in comments for the main program. For instance, when the user has guessed right you should alert after how many attempts they got it right. Think of which property can help you to know this number of attempts. Hint: length.
I will not provide the corrected code here, as I think with the above points you have enough material to bring this exercise to a good end. Happy coding.
Use parentheses to invoke the play function.
game.play();

How to check if a variable has increased (JavaScript)

I want my code to check if a variable has increased. For example, I have a function that looks for the letter A in a text box, which runs every time a key is pressed. Then it counts the number of A's it has found. Then I want to alert me everytime a new A is written. I thought I could do this easily by just checking if the var numberOfA has increased in an if statement, and if it has to alert me, but I can't figure it out. I have tried using ++ and =/== in my if statement, but it alerts me every single time a letter is typed, instead of only everytime an A has been typed. All help is appreciated, I'm pretty new at this.
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
var numberOfA = sentence.length;
if (numberOfA = numberOfA +1) {
alert(" The letter A has been typed ");
}
}
Several problems.
When you write numberOfA = numberOfA + 1, you actually assign a value to numberOfA. Use a === b if you want to test equality.
Also, if you decide to use numberOfA to store the previous count, then you need to compare that with the current sentence.length value.
As a side note: if you are new, then invest time in learning how to use the debugger (e.g. in the browser dev tools). It will save you a lot of time and help you really understand what is happening.
You can not check numberOfA = numberOfA + 1 in your if statement. You can try this -
var numberOfA = 0;
function checkForA(){
var sentence = document.getElementById("userText").value.match(/a/g);
if (sentence.length > numberOfA) {
numberOfA = sentence.length;
alert("The letter A has been typed. In your sentence A has found "+numberOfA+" times.");
}
}

Understand Javascript error

This is my very first program in javascript! I've been trying to go through tutorials and I kind of get it. But my code doesn't work! I want to find out why??? An explanation of the error would help me understand.
document.write("Random # (1-5) = ", Math.floor((Math.random() * 5) + 1), "<br />");
if(Random = 2){
alert("Your names Bob");
}else {
alert("Your names Superman");
}
This program writes to the page a random number between 1 and 5, (works fine...) then, say, if the random number is 2, I want to alert the user that their name is Bob, and if the number isn't 2, alert them that their name is Superman...
Complete noob/beginner here, sorry if this frustrates you, but I appreciate your understanding! The only way to learn!!! Cheers :)
your code is wrong, the first thing is that you should use "==" for comparison into if() (or "===" if you also want to check the type).
The second thing that I see is that you are checking the value of a variable called Random but the first line wrote some text on the page (document.write()) but it doesn't set the value of the Random variable, try replacing the first line with:
var Random = Math.floor((Math.random() * 5) + 1)
and this should work

Javascript coding

I am going nuts trying to write a JavaScript code, which requests from the user any sequence of numbers until such user enters 'N'.
If this happens, a message should pop up indicating the user that he reached the end of that sequence and then a new message pops up showing 'all' the numbers the user entered PLUS organising them in crescent order.
Any suggestions, please?
I would appreciate any help as I'm going mad right now thinking of anything.
If the array was specified, then I wouldn't have a problem, but since it's a random array, I can not seem to find the right answer.
What you want to do is something like this:
Get the user's numbers and save them, prefably in an array.
Loop through all the numbers and check if the number is N.
If so, alert the user.
Sort the array, alert the user.
Attempt to code:
// All the user's numbers
var UserNumbers = [15, 10, 11, 12, 13];
//The value to search for
var N = 12;
//Loop through the values
for(var i = 0; i < UserNumbers.Length; i++){
if(UserNumbers[i] == N){
//The number matches
alert("You reached the end of the sequence";
}
}
// I am not sure what you mean with cresent order so that you'll have to solve for yourself.
//Sort the UserNumbers here
//Store the message to show the user
var message = "";
//Loop through the values - now in correct order and save them to the message
for(var i = 0; i < UserNumbers.Length; i++){
//Add to the message
message += UserNumbers[i] + " ";
}
//Show the message - all the containing numbers
alert(message);
Although this is an helpful community I am pretty certain that we're not made out of teachers here to teach you how to code. Since this sounds to be an homework rather than a real life scenario, talk with your teacher or classmates. Good luck and next time, try to do some research before posting a question - there are plenty of tutorials for beginners out there.

If Else Statements in Javascript for LiveCycle

I am creating a form on Adobe LiveCycle that adds the numbers in different fields. I need to have the final field (Eligible Assets) add all the previous fields but exclude the sum of three of them and one in specific but only if it is greater than 60000. I've written the script as follows for the first part (to sum all the fields) this is in a field I've titled TotalAssets:
this.rawValue =Cash.rawValue+SavingsAccount.rawValue+ChildrensSavings.rawValue+CheckingAccount.rawValue+ValueHome1.rawValue+ValueHome2.rawValue+ValueVehicle1.rawValue+ValueVehicle2.rawValue+ValueVehicle3.rawValue+BusinessAccount.rawValue+BusinessAssets.rawValue+StocksBonds.rawValue+Retirement.rawValue+CDs.rawValue+OtherInvestments.rawValue+OtherAssets.rawValue;
This has worked fine, but the Retirement value if it is greater than 60000 should not be added into the calculation. This is what I've written (EligibleAssets):
if (Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
} else {
Retirement.rawValue == Retirement.rawValue ;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue+ValueVehicle1.rawValue +Retirement.rawValue);
When I save the form as a PDF the first total of the fields calculates correctly but the second field comes up blank.
If you can spot what I'm missing or doing wrong I would really appreciate any feedback. Thank you!
There are two simple problems that I see here.
First problem is that you are using == when you should be using =.
== - check if the left side is equal to the right side. Example: if(x == 5) {
= - set the left side to the value of the right side. Example: x = 5
In the first example we leave x alone, but in the second example we change x to 5.
So your code should look like:
} else {
Retirement.rawValue = Retirement.rawValue;
}
However, when you think about this, this code doesn't actually do anything. Retirement.rawValue will not change.
This leads us to the second mistake in the code, at least, it looks to me like a mistake.
if(Retirement.rawValue > 60000) {
Retirement.rawValue = 0;
}
This actually changes Retirement.rawValue, which might potentially change what's inside the Retirement field of your form. Worse, its possible that the form would look the same, but act differently when some other field calculates, since you've changed its rawValue. That would be a very tough bug to catch.
The solution is to create a new variable: http://www.w3schools.com/js/js_variables.asp
So now we can create a new variable, set that variable to either the retirement amount or nothing, and then add that variable to the other rawValues at the end:
var retirementOrZero;
if(Retirement.rawValue > 60000) {
retirementOrZero = 0;
} else {
retirementOrZero = Retirement.rawValue;
}
this.rawValue = TotalAssets.rawValue - (ValueHome1.rawValue + ValueVehicle1.rawValue + retirementOrZero);
Now we have a number that we can name anything we want, and we can change it however we want, without affecting any code but our own. So we start by checking if our retirement value is greater than 60000. If it is greater, we set our variable to 0. Otherwise, we set our variable to the retirement value. Then we add that variable we made, to the home and value cost.
As a final question, is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 0;
}
or is it supposed to do
if(Retirement.rawValue > 60000) {
retirementValueOrZero = 60000;
}
Of course, if you are setting it to 60000 instead of setting it to zero, you probably want to name your variable cappedRetirementValue or something like that -- just make sure you rename it everywhere its used!
Hopefully that helps!
Edit: You said you're only adding retirement value if it is greater than 60k, so what you want is this:
if(RetirementValue.rawValue > 60000) {
retirementValueOrZero = RetirementValue.rawValue;
} else {
retirementValueOrZero = 0;
}

Categories

Resources