for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/
Related
I'd like to write a JavaScript program that displays a symmetric histogram like this image:
The program should ask the user to enter the number of bars to print and the character to use to draw the bars. The count of characters in the bar needs to be displayed on the right-side of each bar.
The example showed is when I entered # as the character and 13 as the number.
Here's my code:
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let text = "";
let symbolNum = symbol;
while (currentNum <= number) {
text += "<br>" + symbolNum + " " + currentNum;
symbolNum += symbol;
currentNum++;
}
document.write(text + "<br>");
And at last, I only can output the following:
I'd like to know what I can do in order to reverse the loop?
Try this
function SymmetricHistogram(){
const size = 10;
let numberX = 0;
let numberY = 0;
for(let i = size; i>=-size; i--) {
for(let j=size; j>=Math.abs(i); j--){
process.stdout.write("#");
}
numberX <=size ? console.log(numberX++) : console.log(--numberY);
}
}
SymmetricHistogram();
Or try the below
https://onecompiler.com/javascript/3x58bqr3h
Two different way for the same result. Not realy clean, but work.
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let textTOP = "";
let textBOTTOM = "";
let symbolNum = symbol;
while (currentNum <= number) {
textTOP += "<br>" + symbolNum + " " + currentNum;
if (currentNum < number)
textBOTTOM = "<br>" + symbolNum + " " + currentNum + textBOTTOM;
symbolNum += symbol;
currentNum++;
}
document.write(textTOP + textBOTTOM + "<br>");
var symbol = '#';
var number = 13;
var currentNum = 1;
let text = "";
while (currentNum < number * 2) {
if (currentNum <= number) {
let num = currentNum;
text += "<br>" + symbol.repeat(num) + " " + num;
} else {
let num = Math.abs(number * 2 - currentNum);
text += "<br>" + symbol.repeat(num) + " " + num;
}
currentNum++;
}
document.write(text + "<br>");
This question already has answers here:
issue with comparing two numbers in javascript
(5 answers)
Closed 1 year ago.
This code is supposed to give you an equation and when you solve it, you get another one in three seconds. You can choose the amount of equations you're getting and how "high" the math is. And it will give you an alert when you did your chosen amount of questions. This code returns no error but it never gives me the alert as it is supposed to. How do I fix this? (I know I am a beginner so my code is a bit messy)
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " +
Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
var h = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> " +
correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " +
" <button onclick=' check() '> check </button> "
+ correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>
Aside from using strict equality, you're also displaying the correct var before updating the value when it's correct. This should work how you want it:
var rand1, rand2, text1, text2
let count = 0;
let correct = 0;
function button() {
text1 = document.getElementById("number").value;
text2 = document.getElementById('questions').value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check() {
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if (answer == text11) {
count = count + 1;
correct = correct + 1;
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count == text2) {
alert(correct + '/' + text2);
}
function wait() {
button()
}
}
<html>
<body>
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id='but'> ok </button>
<div id='div'> </div>
count is an integer and text2 is a string so the if statement comparing count and text2 will never return true. Therefore that block delivering the alert will never fire.
I would simply use javascript's parstInt function to make sure text2 is an integer
text2 = parseInt(document.getElementById('questions').value);
My code works fine up until I try to save my data, exit out, then reopen then load saved data. I save using localStorage.setItem('key', value) then I load using localStorage.getItem('key'), but after I load my vars are not holding the right values. Is localStorage.getItem('key') returning a string, because 1 +1 = 2, not 11 like it's displaying. please help.
The page itself is stored on my PC not online, I'm opening it up with Google Chrome. I run Windows Edge. When I try opening this with Internet Explorer, forget about localStorage.set/getItem all together. I've tried just running my code with the variables then try to save and load. (note:All my code works flawlessly until I try to save the variables, then reload them). I'm working on a video game so I need to be able to save my variables. And since I'm not sure where the problem in my code lies, I'm sorry but I see no other option than to post about 180 lines of code
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="black" >
<font color="white" >
<progress id="myProgress" value="10" max="10"></progress><br>
<p id='demo5' ;></p>
<button id="enemy" type="button" onclick="dealDamage(), imageSwap()"><img
id="enemy1" src="Game_Images/smiley_1.png"></button>
<button id="spriteTest" type="button" onclick="imageSwap2()"><img
id="enemy2" src="Game_Images/smiley_1.png"></button><br>
<button id="upgrade" type="button" onclick="upgradeClickDamage()">
</button>
<button type="button" onclick="moreGold()">More Gold</button><br>
<button type="button" onclick="saveGame()">Save Game</button>
<button type="button" onclick="loadGame()">Load Game</button>
<p id='demo' ;></p>
<p id='demo2' ;></p>
<p id='demo3' ;></p>
<p id='demo4' ;></p>
<script>
var clickDamage = 1;
var gold = 0;
var stage = 1;
var enemyNum = 1;
var enemiesTotal = 10;
var enemiesKilled = 0;
var cost = 100;
var enemyHPTotal = 10;
var enemyHPCurrent = 10;
document.getElementById("upgrade").innerHTML = "Upgrade click damage for:"
+ cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
document.getElementById("demo3").innerHTML = "Enemies Killed This Stage:"
+ enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:" +
enemyHPCurrent + "/" + enemyHPTotal;
function imageSwap() {
var image = document.getElementById("enemy1");
if (image.src.match("Game_Images/smiley_1")){
image.src="Game_Images/smiley_2.png"
}
else if (image.src.match("Game_Images/smiley_2")){
image.src="Game_Images/smiley_3.png"
}
else {
image.src="Game_Images/smiley_1.png"
}
}
function imageSwap2(){
var image2 = document.getElementById("enemy2");
if(image2.src.match("Game_Images/smiley_1")){
setTimeout(image2.src="Game_Images/smiley_2.png", 300);
}
else if(image2.src.match("Game_Images/smiley_2")){
setTimeout(image2.src="Game_Images/smiley_3.png", 300);
}
else {
setTimeout(image2.src="Game_Images/smiley_1.png", 300);
}
}
function dealDamage() {
document.getElementById("myProgress").value -= clickDamage;
//If enemy is hit but does not die
if(document.getElementById("myProgress").value >= 1){
enemyHPCurrent = document.getElementById("myProgress").value
enemyHPTotal = document.getElementById("myProgress").max
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If enemy is killed and there are remaining enemies in the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum < 10) {
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyHPTotal = document.getElementById("myProgress").value;
enemyNum += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled += 1;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
//If the enemy is killed and it is the last enemy of the current stage
if (document.getElementById("myProgress").value == 0 && enemyNum == 10) {
document.getElementById("myProgress").max += 1;
document.getElementById("myProgress").value =
document.getElementById("myProgress").max;
gold += (1 * stage);
enemyNum = 1;
stage += 1;
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo2").innerHTML = "Stage: " + stage;
enemiesKilled = 0;
document.getElementById("demo3").innerHTML = "Enemies Killed This
Stage:" + enemiesKilled + "/" + enemiesTotal;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
enemyHPTotal = document.getElementById("myProgress").max;
enemyHPCurrent = enemyHPTotal;
document.getElementById("demo5").innerHTML = "Enemy HP remaining:"
+ enemyHPCurrent + "/" + enemyHPTotal;
}
}
function upgradeClickDamage() {
if (gold >= cost) {
gold -= cost;
clickDamage += 1;
cost += 100;
document.getElementById("messageBox").innerHTML =
"Congratulations!!! You just upgraded your click damage."
document.getElementById("upgrade").innerHTML = "Upgrade click damage
for:" + cost + " gold.";
document.getElementById("demo").innerHTML = "Gold: " + gold;
document.getElementById("demo4").innerHTML = "Click Damage:" +
clickDamage;
}
else if (gold < cost) {
document.getElementById("messageBox").innerHTML = "You don't have
enough gold for this upgrade."
}
}
function moreGold() {
gold += 100;
document.getElementById("demo").innerHTML = "Gold: " + gold;
}
function saveGame(){
//save all vars
localStorage.setItem('CLICKDAMAGE', clickDamage);
localStorage.setItem('GOLD', gold);
localStorage.setItem('STAGE', stage);
localStorage.setItem('ENEMYNUM', enemyNum);
localStorage.setItem('ENEMIESTOTAL', enemiesTotal);
localStorage.setItem('ENEMIESKILLED', enemiesKilled);
localStorage.setItem('COST', cost);
localStorage.setItem('ENEMYHPTOTAL', enemyHPTotal);
localStorage.setItem('ENEMYHPCURRENT', enemyHPCurrent);
}
function loadGame(){
//load all vars
clickDamage = localStorage.getItem('CLICKDAMAGE');
gold = localStorage.getItem('GOLD');
stage = localStorage.getItem('STAGE');
enemyNum = localStorage.getItem('ENEMYNUM');
enemiesTotal = localStorage.getItem('ENEMIESTOTAL');
enemiesKilled = localStorage.getItem('ENEMIESKILLED');
cost = localStorage.getItem('COST');
enemyHPTotal = localStorage.getItem('ENEMYHPTOTAL');
enemyHPCurrent = localStorage.getItem('ENEMYHPCURRENT');
}
</script>
<div id="messageBox"></div>
</font>
</body>
</html>
I expected all variables to function properly after loading.
gold, cost, and enemiesKilled are all affected by this same problem. If gold = 1, and I save that variable then load that variable later, then add 1 again, I get 11, not 2. With cost, if cost = 100, then I save, then I load later, then I add 100 to cost, cost = 100100 not 200.
(This will restate a bit of what you hypothesized in your question for the sake of completeness)
If you look at the documentation for Storage.getItem(), it says:
Return value
A DOMString containing the value of the key. If the key does not exist, null is returned.
This means that no matter what data type you give in setItem, the output of getItem will always be a string. This is easy to test in the console:
localStorage.setItem("test", 1);
> undefined
localStorage.getItem("test");
> "1"
When you add a string to a number, it just concatenates the two together. In your case, you're adding "1" + 1 which becomes "11" instead of adding 1 + 1 which would be 2. The solution is to convert the number string into a number, which can be done several ways, but is easiest to do (in my opinion) by simply prefixing the expression with a +.
+localStorage.getItem("test");
> 1
The localStorage.setItem converts all passed values to string. Once you call localStorage.getItem you are getting back string value.
So you are trying to concatenate string and number "1" + 1 === "11".
To prevent this behavior you need to manually convert values to stringified JSON:
localStorage.setItem('CLICKDAMAGE', JSON.stringify(clickDamage));
And then parse it back:
clickDamage = JSON.parse(localStorage.getItem('CLICKDAMAGE'));
Trying to get Break Even Point (BEP) and selling value using jquery.
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
$("#cost").on("change keyup paste", function() {
var cost = Number($('#cost').val());
var text
var total_cost = roundToTwo(((cost * 18) / 100) + cost);
var profit = -0.5;
var sell = cost + 0.01;
while (profit <= 0) {
sell = sell + 0.01;
profit = roundToTwo(sell - total_cost);
text += "<br />New Sell " + sell + " and profit " + profit;
}
var bep = roundToTwo(sell - total_cost);
$('#bep_display').text(bep);
document.getElementById("testing").innerHTML = text;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="cost" placeholder="cost" name="cost">
<h1 id="bep_display">
</h1>
<p id="testing"></p>
Now by running the above code, I entered 1 in the input, so the result (BEP) should be 0, but it gives NaN
Because your answer returns with e so it shows NaN. Try:
var bep = parseFloat(sell - total_cost).toFixed(8);
This will give you the result 0.00000000.
If you need a result as 0. Add:
bep = roundToTwo(bep);
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
$("#cost").on("change keyup paste", function() {
var cost = Number($('#cost').val());
var text
var total_cost = roundToTwo(((cost * 18) / 100) + cost);
var profit = -0.5;
var sell = cost + 0.01;
while (profit <= 0) {
sell = sell + 0.01;
profit = roundToTwo(sell - total_cost);
text += "<br />New Sell " + sell + " and profit " + profit;
}
var bep = parseFloat(sell - total_cost).toFixed(8);
bep = roundToTwo(bep);
$('#bep_display').text(bep);
document.getElementById("testing").innerHTML = text;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="number" class="form-control" id="cost" placeholder="cost" name="cost">
<h1 id="bep_display">
</h1>
<p id="testing"></p>
The problem is with this line :
var bep = roundToTwo(sell - total_cost);
One solution is to fixed your decimals, for example :
var bep = roundToTwo(sell.toFixed(8) - total_cost.toFixed(8));
First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check