I am trying to learn javascript, I am playing with a game that picks a random number.
I would like to have 2 functions, random and guess. Random generates a new number between 1-10. Guess is where it checks if the number was guessed, if not re-runs the random function and generates a new number to try.
var x;
function random(){
let x = Math.floor((Math.random() * 10) + 1);
guess();
}
function guess(x){
if(x === 3){
alert('you are correct!');
}else{
alert('try again');
random();
}
}
random();
This just alerts try again every time, i'm guessing because it's not generating a new number each time the function is called?
How can you create the random function so it generates a new number each time its called?
***** Correction, it appears to generate a new number but x is undefined within the guess function**
The x in the guess() is the x that gets passed to it as a parameter. I would remove the var x; declaration and pass a value when calling like guess(x)
function random(){
const x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x){
if(x === 3){
alert('you are correct!');
}else{
alert('try again');
random();
}
}
random();
The guess function's signature says that it takes a parameter x, but you're not passing any value to the function when it's called, so it's assigning undefined to x when it runs guess, which will never equal 3. You can take 2 approaches to fix this. First, you could make x a global variable by getting rid of the let where you define x in the random function and removing x from guess's function signature, like so:
var x;
function random() {
x = Math.floor((Math.random() * 10) + 1);
guess();
}
function guess() {
if (x === 3) {
alert(x + '- you are correct!');
}
else {
alert(x + '- try again');
random();
}
}
random();
Or, you could use x as a parameter for the guess function by removing the var x; global declaration and passing x to guess when you call it in the random function, like so:
function random() {
let x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x) {
if (x === 3) {
alert(x + '- you are correct!');
}
else {
alert(x + '- try again');
random();
}
}
random();
I personally wouldn't even have a random function. I'd just define x within guess and call guess from within itself. And, I'd use randojs.com to make the randomness more readable. Here's how I'd do it:
function guess() {
let x = rando(1, 10);
if (x === 3) return alert(x + '- you are correct!');
alert(x + '- try again');
guess();
}
guess();
<script src="https://randojs.com/1.0.0.js"></script>
Note that the return statement would stop the execution of the function right then and there, so it wouldn't progress to the "try again" alert if the number was guessed correctly.
Here's some detailed code that will help you understand how to run such a game in the browser.
See the comments for explanation of how it works (and search for information on MDN to learn more about any particular topic.)
Happy coding!
// Identifies HTML elements
const
guessInput = document.getElementById("guessInput"),
outputParagraph = document.getElementById("outputParagraph");
// Makes a global variable that all functions can access
let globalNum;
// Invokes the main function
playGame();
function playGame(){
// Invokes the randomizer function and stores the result in the global variable
globalNum = getRandomNumber();
//console.log(globalNum);
// Invokes the output function
setOutput("Guess a number from 1 to 10");
// Assigns a function that will be invoked whenever the user changes the input field
guessInput.addEventListener("change", respondToGuess);
// Puts the focus in the input element
guessInput.focus();
}
// Defines a listener function that can automatically see the triggering event
function respondToGuess(event){
// Gets the `target` element of the event and stores it in a local variable
const localReferenceToInputElement = event.target
// The text of an `<input>` element lives in its "value" property
const inputText = localReferenceToInputElement.value;
// Tries to convert the text string to an integer (and store it locally as 'guess')
let guess = parseInt(inputText);
// If the conversion failed, changes the output accordingly
if(!guess){ setOutput("Please enter a valid number"); }
// If the number is out of range, changes the output
else if(guess < 1 || guess > 10){ setOutput("Only numbers from 1 to 10 are allowed"); }
// If the guess doesn't match the stored number, changes the output
else if(guess !== globalNum){ setOutput("Try again..."); }
// If we got this far, the guess was correct, so changes output and ends game
else{
setOutput("You guessed it!");
reset();
}
}
function getRandomNumber(){
// Returns a random number into whatever function called this function
const x = Math.floor((Math.random() * 10) + 1);
return x;
}
function setOutput(outputText){
// The text of a paragraph element lives in its `innerHTML` property
outputParagraph.innerHTML = outputText;
}
function reset(){
// Clears the input and stops listening for changes
guessInput.value = "";
guessInput.removeEventListener("change", respondToGuess);
}
<input id="guessInput" />
<p id="outputParagraph"></p>
I have done some changes to your code.
You have problem with the concept of function calling function.
In real code it will kill your memory.. your function calls function the function not close and call the function again and again... and its fill the memory .
var x;
// flag correct will close the loop when you have right umber
var correct = false;
function random() {
x = Math.floor((Math.random() * 10) + 1);
guess(x);
}
function guess(x) {
if (x === 3) {
alert('you are correct!');
// if number is right flag is up
correct = true;
} else {
alert('the number is ' + x + ' try again');
}
}
// loop until the number is right
while (correct != true) {
random();
}
Related
I made a function that checks if an input number is equal to Math.random(). I want to make another function to check how many times the button was clicked before the user got the correct answer.
function guess() {
var x = document.getElementById('this').value;
var y = Math.floor((Math.random() * 10));
if (x == y) {
alert("Nice");
} //correct answer
else if (x > y) {
alert("Lower");
} else {
alert("Higher");
}
}
<body>
<input type="number" min=1 max=2 id="this">
<button type="button" onclick="guess()">Check</button>
</body>
I expect to see the number of tries the number has done.
Taking into account Nick Parsons comment, I moved the number searched for out of the function. The counter also needs to be defined outside the function and incremented by one on each call. I also altered your code to give the number of attempts when guessed correctly.
var y = Math.floor((Math.random() * 10));
var counter = 0;
function guess() {
var x = document.getElementById('this').value;
counter += 1;
if (x == y) {
alert(`Nice. Took you ${counter} attempts`);
} //correct answer
else if (x > y) {
alert("Lower");
} else {
alert("Higher");
}
}
<body>
<input type="number" min=1 max=10 id="this">
<button type="button" onclick="guess()"> Check </button>
</body>
Also the max on the number-input field was not right.
Create a global variable (say, counter) intialized to zero, then increment it every time the button is clicked:
var counter = 0;
var y = Math.floor((Math.random() * 10));
function guess() {
var x = document.getElementById('this').value;
counter += 1;
if (x == y) {
alert("Nice. You've guessed it in " + counter + " tries.");
counter = 0;
} //correct answer
else if (x > y) {
alert("Lower");
} else {
alert("Higher");
}
}
Although you didn't ask for it, note that I placed the initialization of x and y from outside the event handler function. If you put it inside, every time you click the button, y would be set to a new random number, which makes the hints useless (and I infer you didn't want to do that anyway).
You must first declare a global variable to store click counter and every time that user try incorrect, increase the variable and finally if successful try then alert it.
I have a program that randomly generates two numbers (x and y) and asks the user to multiply them. Once they multiply them, it will tell them if they get it right or wrong. The thing I'm having problems with is that if they get the answer correct, it should then generate a new set of numbers. I'm not sure how to make the program perform that function again. Also it has to clear the answer field no matter if they get it right or wrong. Thanks!
var x, y; // global variables for randomly generated numbers
var correct = ['Very good!', 'Excellent!', 'Correct - Nice work!', 'Correct - Keep up the good work!'];
var incorrect = ['No. please try again.', 'Wrong. Try once more.', 'Incorrect - Dont give up!', 'No - Keep trying.'];
// getting two random numbers between 1-12 then assigning them to x and y
function generateNumbers() {
function aNumber() {
return Math.floor((Math.random() * 12) + 1);
}
x = aNumber();
y = aNumber();
}
// generating the question that will be used with the random numbers x and y
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
function genQuestion() {
generateNumbers();
document.getElementById('question').value = x + " times " + y;
}
window.alert(correctans);
var total = document.getElementById('total').value++;
}
else { // incorrect
window.alert(incorrectans);
}
}
You're not calling the genQuestion function, and it makes little sense to redefine it.
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
var answer = document.getElementById('answer').value;
if (answer == x * y) // correct
{
//call genQuestion to create new question
genQuestion();
window.alert(correctans);
var total = parseInt(document.getElementById('total').value)++;
}
else { // incorrect
window.alert(incorrectans);
}
//clear 'answer' field
document.getElementById('answer').value = '';
}
I have a equation like this stored in a varible
(50 * 1.07^1) its very simple. I want to know how I can change the power each time a function runs like so: 50*1.07^2, 50*1.07^3 and so forth. Any help?
Here is my code:
var mathForCost = 50 * 1.07 ^ 1;
function gainCoinsPS() {
if (coins >= costPS) {
coinsPS += 10;
coins -= costPS;
// Here is where I am changing the cost each time the function runs,
// so I need to make the power(^1) add 1 each time
costPS = document.getElementById("changePrice1").innerHTML = "Cost: " + costPS;
} else {;
alert("You dont have enough coins!");
};
}
Save the power to a variable, and you can update it when needed. It is preferred that you put the equation into a function and pass power to it, and return the solution.
var power = 1,
eq = function(p){
return 50*1.07^+p; // returns solution
};
for(var i=0; i<10; i++){
power = i;
console.log( eq(power) ); // solution
}
You can store your power in a variable and increment it each time your function is called.
var power = 1;
function calculate() {
console.log(50 * Math.pow(1.07, power));
power++;
}
calculate();
calculate();
calculate();
In Javascript you can't really store an equation in a variable, except maybe as a string (but that is fraught with issues of its own). Your function will be evaluated the moment you execute, and the value of the output will instead be stored in the variable.
To do what you want to do, you would be better having a function that runs the equation, and increments the power each time-- this works if the power is in a higher scope (or it can be accomplished with a closure)
var power = 1;
function getCost()
var cost = Math.pow(50*1.07, power);
power++;
return cost;
}
Each time this function runs, it returns the calculated cost and also increments the value of power, so it will be one higher the next time it runs.
Alternately, if you wanted to go the closure route, you could do something like this:
var getCost = (function () {
var power = 1;
return function () {
var cost = Math.pow(50*1.07, power);
console.log(power);
power++;
return cost;
}
})();
You can store a state to the function that runs the equation. This helps you avoid adding more state outside of the function. Let the function keep track of how many times it has been called.
function calc() {
if (!this.i) {
this.i = 1;
}
return (50 * Math.pow(1.07, this.i++));
}
console.log(calc());
console.log(calc());
console.log(calc());
There is Math.pow function is javascript for this.
You can use something like this
var pow = 1;
for(var power=1; power<limit; power++){ // run the loop upto a limit
console.log(Math.pow(50*1.07, power);
}
To increment power of 1.07 by 1, just multiply value by 1.07 every time (pow function is not needed at all)
var mathForCost = 50 * 1.07;
...
mathForCost = mathForCost * 1.07;
You could use a function for it.
getCost = function (n) { return 50 * Math.pow(1.07, n); };
Or with ES6's arrow function
getCost = n => 50 * Math.pow(1.07, n);
Call it with
value = getCost(1);
I am building a hot and Cold App in JS and jQuery.
My issue is on form submit that user input inserts a number and the game tells them if its hold or cold or hotter or holder based on how close or far from the number.
Issue is that It only works the first time. After that it does nothing.
How do I made it so that when the user input on submit it generates a new secretNumber and based on the checker I have setup outputs either hot or cold or hotter or colder.
Seems its not generating a new secret number or it is just not inputing it.
Code here http://codepen.io/mackenzieabby/pen/qOXNLg
JS
$(document).ready(function(){
// Global Variables.
var theSecret = Math.floor((Math.random() * 100) + 0); // Creates Secret Number
var userGuess = $('#userGuess').val(); // User Inut Guess
var count = 0;
var addList = document.createElement("li")
// Display information modal box
$(".what").click(function(){
$(".overlay").fadeIn(1000);
});
// Hide information modal box
$("a.close").click(function(){
$(".overlay").fadeOut(1000);
});
// Functions
// New Game
function newGame() {
// new gama data here
}
// Add To List
function addtoList() {
}
function preventRefresh() {
$("form").submit(function(event) {
event.preventDefault();
theSecret();
veryHotGuess();
hotGuess();
veryColdGuess();
coldGuess()
correctAnswer();
});
}
preventRefresh();
function addGuess() {
$("ul#guessList").append("<li>" + userGuess + "</li>");
}
// Checks if hot or cold or correct
function veryHotGuess() {
if (userGuess < 25 && theSecret < 25) {
document.getElementById('feedback').innerHTML = "Very Hot";
}
}
function hotGuess() {
if (userGuess < 50 && theSecret < 50) {
document.getElementById('feedback').innerHTML = "Hot";
}
}
function veryColdGuess() {
if (userGuess < 100 && theSecret < 100) {
document.getElementById('feedback').innerHTML = "Very Cold";
}
}
function coldGuess() {
if (userGuess < 75 && theSecret < 75) {
document.getElementById('feedback').innerHTML = "Cold";
}
}
function correctAnswer() {
if (userGuess == theSecret) {
document.getElementById('feedback').innerHTML = "You Got It";
}
}
});
Calling theSecret(); causes a JavaScript error. You are calling the variable as a function, which it isn’t obviously.
BTW, I think your calculation of guess "temperature" might be quite wrong.
You have to redefine your definition of Global variable in javascript:
$(document).ready(function(){
// Global Variables.
var theSecret = Math.floor((Math.random() * 100) + 0); // Creates Secret Number
var userGuess = $('#userGuess').val(); // User Inut Guess
var count = 0;
var addList = document.createElement("li")
...
those ARE NOT global variables, because you made then in a scope, the document.ready scope... a Global Variable must be defined outside any scope, so it's available in all scopes, including inside the document.ready as well inside any function method you wrote.
Secondly, you need to rethink what you are doing, as a rule, you are repeating yourself over and over with
document.getElementById('feedback').innerHTML = xxxx;
one day you need to change the feedback to something else, or also write something else, can you see in how many places you need to change your code? When you see several lines of almost the same code: You're doing it wrong...
And you need to simplify your calculations, you make it hard to code and see what's going on...
Third, as Alexander pointed out, you need to re-think how you're calculating, what you want to calculate if not the userGuess or the theSecret, but give an answer based on how close/far the user guess is from the correct value ... that I would call it the difference between 2 numbers.
something like: Math.abs(theSecret - userGuess)
Here's my approach:
http://codepen.io/anon/pen/wKqzvg?editors=001
(irrelevant code removed)
var theSecret = 0,
guesses = [];
$(document).ready(function() {
// Creates Secret Number
theSecret = Math.floor((Math.random() * 100) + 0);
$("form").submit(function(evt) {
evt.preventDefault();
checkTemperature();
});
});
// Functions
// Add To List
function addToList(txt) {
guesses.push(txt);
$("#count").text(guesses.length);
$("ul#guessList").append("<li>" + txt + "</li>");
}
function write(txt) {
document.getElementById('feedback').innerHTML = txt;
}
function checkTemperature() {
var userGuess = parseInt($('#userGuess').val()),
dif = Math.abs(theSecret - userGuess);
// for debug only
console.log("theSecret:" + theSecret);
console.log("userGuess:" + userGuess);
console.log("dif:" + dif);
addToList(userGuess);
if (dif < 5)
write("Vulcan Hot");
else if (dif < 25)
write("Very Hot");
else if (dif < 50)
write("Hot");
else if (dif < 75)
write("Cold");
else if (dif < 100)
write("Very Cold");
else if (dif === 0)
write("You Got It");
}
The problem isn't with theSecret but with userGuess. You were not grabbing the value on submit so it was empty. I suggest to always console.log or inspect variables to make sure they are getting populated correctly. In your submit I added this: userGuess = $('#userGuess').val(); and it will now check correctly.
However, as Alexander mentioned the math is wrong. The value will always be under 100 and so it will always be Very Cold. You have to get the absolute difference of both numbers and then do your guess check:
var difference = Math.abs(theSecret - userGuess);
if (difference < 100) {
document.getElementById('feedback').innerHTML = "Very Cold";
}
if (difference < 75) {
document.getElementById('feedback').innerHTML = "Cold";
}
if (difference < 50) {
document.getElementById('feedback').innerHTML = "Hot";
}
if (difference < 25) {
document.getElementById('feedback').innerHTML = "Very Hot";
}
if (difference == 0) {
document.getElementById('feedback').innerHTML = "You Got It";
}
I forked your project here: http://codepen.io/paulmg/pen/xwLExM
function mathProb() {
var x = parseInt(prompt("Enter first integer", ""));
var y = parseInt(prompt("Enter the second integer", ""));
var operand = prompt("Enter type of operation", "");
if (operand == "+" || "add") {
var sum = x + y;
document.write("Your sum is " + sum);
} else if (operand == "-") {
var difference = x - y;
document.write("Your difference is " + difference);
} else if (operand == "*") {
var product = x * y;
document.write("Your product is " + product);
} else if (operand == "/") {
var quotient = x / y;
document.write("Your quotient is " + quotient);
} else {
document.write("Oops something went wrong");
}
}
Well to start I am reading a book on JavaScript and have been doing pretty well, I am now on functions and was getting those until parameters were introduced can someone explain what a parameter is in a clear simple way?
Why does this function work when named function mathProb() and function mathProb(x,y,operand)?
And a third question off of the previous one is why when I call the function in html
(<input type="button" value="Calculator" onclick="mathProb()"/>)
I have to use mathProb() even if its named mathProb(x,y,operand). If I call it using that name it wont work. Please help?
First, the line:
if(operand=="+"||"add")
Will always be true, as the expression "add" will always return a true-ish value. You probably mean to use:
if(operand=="+" || operand=="add")
Your question about parameters is probably a pretty broad topic. Basically, a parameter is a variable given to a function so that the function can be generalized to work with any data. For example, if you wanted to write a function that can add two numbers, the function must know which two numbers to add. These numbers would be supplied as parameters:
function add(x, y)
{
return x + y; // x and y are variables known within this function
}
You'd then call your function as so:
var oneplusone = add(1, 1); // Adds 1 and 1
Using this knowledge, you could rewrite your code as this:
function mathProb(x, y, operand)
{
// No need for var x, etc as these can now be passed in..
}
Then call your function:
mathProb(
parseInt(prompt("Enter first integer","")), // This is x
parseInt(prompt("Enter the second integer","")), // This is y
prompt("Enter type of operation","") // This is operand
);
Keep in mind you could still call your function mathProb without the parameters:
mathProb();
...if you really wanted to. JavaScript does allow this (unlike many other languages). However, within your function, the variables x, y and operand will be undefined which might cause unexpected results if you don't account for that.
You need call and pass function like mathProb(1,2,'+')
HTML:
<input type="button" value="Calculator" onclick="mathProb(1,2,'+')"/>
Javacript:
function mathProb(x,y,operand)
{
//var x = parseInt(prompt("Enter first integer",""));
//var y = parseInt(prompt("Enter the second integer",""));
//var operand = prompt("Enter type of operation","");
if(operand=="+"|| operand=="add")
{
var sum = x+y;
document.write("Your sum is " +sum);
}
else if(operand=="-")
{
var difference = x-y;
document.write("Your difference is " +difference);
}
else if(operand=="*")
{
var product = x*y;
document.write("Your product is " +product);
}
else if(operand=="/")
{
var quotient = x/y;
document.write("Your quotient is " +quotient);
}
else
{
document.write("Oops something went wrong");
}
}