I am trying to code a simple function in JavaScript which generate random values in (0,10) and asks the user to guess these numbers. Since I am new with JavaScript I wrote this code which not working. So I need your help to figure out how can I fix it.
Your last if statement in Guessing checks whether the counter is below 5. Remove that statement and you are good to go. Since counter is defined as a global variable, it is increased in the guessGame function even without you giving it as parameter and once it's =5 your code stops executing.
A tip if you are new to programming in general: If your code stops working at a magic value,(5 in this case), it's always a good idea to search it in your code with ctrl+f.
Edit after comment:
You are thinking readInput as a blocking function, it's not. Your do...while function executes readInput every time, and reads the same value from the input box and processes it as wrong. To fix it, remove your Guessing function, put readInput in your html, and at the end of your readInput add the guessGame function where you do your comparison with the random numbers. Try with 1 number first.
Fun fact: Even guessing supposed to work as you intended, it would generate a new set of random numbers at each click, thus make the game much harder.
With 1 number, your code is like this :
html:
Guess : <input type="text" id="nb"/> <input type="button" value="Check" onclick="readInput()"/>
javascript:
var ranval=generateRandom();
var counter=0;
function readInput(){
var input = parseInt(document.getElementById('nb').value);
if (counter<5){
guessGame(input);
}
counter++;
if (counter==5){
console.log("you lost")
}
}
function generateRandom(){
//the 3 random values to be used later
rand1 = Math.floor(Math.random() * 10) ;
ranval=rand1;
}
function guessGame(input){
if (ranval==input){
console.log("correct")
}
}
Related
I asked this question previously and it got redirected (and treated as answered) to this question - "Adding two numbers concatenates them instead of calculating the sum".
But it did not help me solve it, I did try parseInt, Number(), and putting + in front of my number.
So here is my question again, but before I think I need to specify that I am using +=, not just +.
I used this function to add 5 to a number in a p element:
function add5() {lifeTotal.textContent += 5;}
I have a similar function that subtracts 5 to that same number:
function minus5() {lifeTotal.textContent -= 5;}
Now my problem is that while the subtracting function works as expected, the adding one just puts 5 at the right side of the number. So if the number was 10, it would return 105, as if both numbers were actually strings and not numbers... while the subtracting function works normally and treats numbers as numbers...
It turns me crazy. I just learnt this += thing and I really don't think I used it wrong...
So my solution is to instead use ++ five times, like so:
function add5() {lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++; lifeTotal.textContent ++;}
It works, but it seems to me this is not the shortest way to write this.
The app I am writing is adding or subtracting by calling the corresponding function with an onclick="function()" in html button tags.
What is happening? What is the shortest way to write this?
Thanks!
Thanks to #aerial301 for this answer:
lifeTotal.textContent = +lifeTotal.textContent + 5
It works. I assume that the + in front of my Var lifeTotal is converting the DOM content targeted by the .textContent to a number, which let JS see 2 numbers instead of a string and the number 5.
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();
My Requirement is
I want to display this output when I gave a(0) the output should come 5 and when I gave a(5) the output should come 0.
a(0) = 5
a(5) = 0
like this
Hint:
Using this function
function A(num){}
like this
Please Help me how to do this I'm new in JS
Please give me different kind of solutions its more useful to my career.
function swap (input) {
if( input == 0)
return 5;
return 0;
}
i think there is no description needed
I think I see what you are getting at.
You want to input one variable into a function, and return another variable that is not defined yet. Then you want to define that variable by inputting it into the same function, and get the first input as the output. And so you should end up with 2 outputs.
Now this is technically impossible, because there are undefined variables at play. However, programming is about imagination and I think I have a solution (it's technically a hack but it will work):
var i = 1;
var output1;
var output2;
function swap(input) {
function func1(input) {
output2 = input;
i++;
}
function func2(input) {
output1 = input;
i = 1;
alert(String(output1) + "\n" + String(output2));
}
if (i === 1) {
func1(input);
}
else if (i === 2) {
func2(input);
}
}
while(true) {
swap(prompt("Enter your first input (this will be your second output):"));
swap(prompt("Enter your second input (this will be your first output):"));
}
The swap function goes back and forth between the values 1 and 2 in the variable i. That is how it keeps track of first or second inputs and their exact opposite outputs. The input, or parameter of the swap function is whatever the user types into the prompt boxes. Feel free to make it user-friendly, this is just the dirty code behind it. The reason they are outputted together is because the second input is undefined, and so the machine cannot guess what you were going to input. So first my little program collects all the data and just reverses the order when it is time to output. But to the user who knows nothing about JavaScript and what is going on underneath the hood, this would work perfectly in my opinion.
This should work for any data types inputted, I tested it myself with objects, strings, numbers, and arrays. Hope this helps!!
Shorter alternative to #mtizziani's answer:
let swap = x => !x * 5 // yes this is all
console.log(swap(0));
console.log(swap(5));
We toggle the input, so x is now 1 or 0
We multiple by 5.
Job done.
I am busy learning Javascript programming for college. As I am new to javascript ,I need some clarity on a function a the book has given me to work on please.
The below is a simple calculation in JS to multiply a user input value by 100 and then multiple it on another input value.
function calcStaff() {
"use strict";
var num = document.getElementById("photognum");
var hrs = document.getElementById("photoghrs");
totalCost -= photographerCost;
photographerCost = num.value * 100 * hrs.value;
totalCost += photographerCost;
document.getElementById("estimate").innerHTML = "$" + totalCost;
}
The code works fine and everything run perfect. However I do not understand why we need the following code "totalCost -= photographerCost;"
When I comment this line out it does mess up the calculation , but I dont understand why.
Could someone please explain this Assignment Operator.
Kind Regards
Unless totalCost and photographerCost are set prior to that line within the context that the function is in, it is completely unnecessary. In fact, especially with the "use strict", if there is no other relevant code, then I am surprised that it is not breaking the code.
So actually by that logic those values must be set elsewhere in the code. They're probably set at a global level so that they can be used in other calculations. So that line of code is removing the old photographerCost from the totalCost before calculating and adding in the new photographerCost.
I'll let you see first what i got:
CODE
I decided to experiment and make a script which order numbers in an array in every possible way.
The first way I'm doing is the "Selection mode", where you find the lower value of the array and you put it at the first position. As you can see I printed it into a table to make it funnier, but here comes my question, i want to put a delay at the end of every loop, where i highlight the values that I'm going to exchange, but for some reason it just organize all the table and then render it instead of going step by step.
Now I'm going to proceed to explain a bit my code ^^u:
If you click at "Restart" you'll get a new bunch of random numbers, and if you click at "Selection" the array will become ordered.
Functions:
generate: generate i numbers with a value from 0 to j.
prinTable: print the table.
renderDots: adds styles at the dots which match with the array values.
seleccion: execute the "Selection" way to organize the array.
highlight: adds styles at the dots which will be exchanged at THIS loop, and remove highlight styles of the others points.
I would like to get an affect like this:
You can use the setInterval function instead of a for loop:
function seleccion(table){
var ordenados = 0;
var timer = setInterval(renderOneStep, 300)
function renderOneStep(){
if (ordenados < table.length){
// do all the calculations
ordenados++;
} else {
clearInterval(timer);
}
}
}
The renderOneStep function updates one column. It is called every 300ms.
Please see the updated jsfiddle.