I'm trying to learn JavaScript and when I started the MDN Tutorial, I tried to do the first exercise alone, which worked okay so far. But there is one really weird situation.
The Game generates a Random number from 1 - 100 and the User has 10 guesses to find out that number.
I simplified the game to 1 - 10 for this purpose.
When the random number is a 9 and i guess 10, the code says my input was too low. I don't understand why that is. In every other situation, it works exactly as expected.
For debugging reasons, the random number will be shown in the dialog after the first guess.
This is my code:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = (Math.random() * 10).toFixed(0);
guess = prompt("Guess a number from 1 to 10");
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
Thanks in advance. If you see something in my code you'd like to comment, I'd love to hear feedback and become better, even if it isn't directly related to this ;)
The problem is, that you are working with Strings, if you compare two strings with < it will only compare as many characters as it has to until it finds a character that is smaller (smaller being it's Integer representation) than another:
console.log("10" < "9");
Here it will only compare "1" to "9", meaning char code 49 to char code 57.
49 is less than 57, meaning the whole expression is true. You can learn more about the ASCII char codes here.
You should use Numbers instead:
console.log(Number("10") < Number("9"));
You are only dealing with Strings, since both prompt() and Number.toFixed() return Strings. If you encapsulate those in Number() calls your game works:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = Number((Math.random() * 10).toFixed(0));
guess = Number(prompt("Guess a number from 1 to 10"));
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
The Javascript Prompt returns a string. In fact, input text box always returns string. So when you enter 10 it returns "10" and toFixed() will also return string.
So you need to correct two lines from your code
number = parseInt((Math.random() * 10).toFixed(0));
guess = prompt("Guess a number from 1 to 10");
guess = parseInt(guess);
Also you need to check for NAN condition to be on safer side.
Related
I have function of "endgame" and here's how the function goes
function endgame() {
setScreen("scorescreen");
ismytimergoing = false;
appendItem(scorelist, score);
for (var i = 0; i < scorelist.length; i++) {
if (scorelist[i] > scorelist[i +1]) {
highestnumber = scorelist[i];
} else if ((scorelist[i] == scorelist[i + 1])) {
highestnumber = scorelist[i];
} else {
highestnumber = scorelist[i + 1];
}
}
setText("scoretext", (scorelist + " ") + namelist);
}
This is a fairly simple click button game and I have a loop which increases the score after each click, different amounts depending on how much the score currently is.
onEvent("clickbutton", "click", function( ) {
setProperty("gamescreen", "background-color", rgb(randomNumber(1, 250), randomNumber(1, 250), randomNumber(1, 250), 0.5));
if (score < 10) {
level = 1;
setText("levelbutton", "level " + level );
score += 1;
setText("scorecounter", "Score = " + score);
changebutton("clickbutton");
changebutton("dontclickbutton");
}
else if ((score >= 10)) {
level = 2;
setText("levelbutton", "level " + level );
score += 2;
setText("scorecounter", "Score = " + score);
changebutton("clickbutton");
changebutton("dontclickbutton");
}
else if ((score >= 50)) {
level = 3;
setText("levelbutton", "level " + level );
score += 3;
setText("scorecounter", "Score = " + score);
changebutton("clickbutton");
changebutton("dontclickbutton");
}
});
The changebutton is a function that changes the background color and text color of whatever "button" is through in the parameter, but that's not the main point here. The function of "Endgame" is what I'm expereincing difficulties with, so here we go. "endgame" is called at least when the wrong button is clicked and when the time runs out, which ever happens during the game. And in my endgame function I have
setText("scoretext", (scorelist + " ") + namelist);
But what is displayed is a whole bunch of numbers, but what I want to be displayed is the list of scores from highest to lowest with the respective names lined up from the namelist. As a side point my start button takes the user input, sets it as a variable called "name" and appends to my namelist. This is an example of the results, I put in meir for name and that displayed ok, but my score was 5 and it showed up as
0,0,0,0,1,2,2,3,3,4,
4,5,5,5 meir
even though the only that should be in my scorelist is 5, so it shouldn't print out all the other stuff. So if I could get any help on to properly sort the scorelist, and have it only print out the scores, and not whole bunch of numbers that would be great, and preferably have it print out the names in order with the scores from highest scoring names to lowest scoring names, that would be great. Thanks in advance.
Someone saw my code and pointed out at least part of the issue. One of the ways the "endgame" function starts is when the time == 0, and I have in my "endgame" function the following.
ismytimergoing = false;
appendItem(scorelist, score);
so I think
ismytimergoing = false;
stops the timer, but that happens when the timer == 0 so the endgame function is keep on happening constantly increasing the scorelist size making it print out a lot of numbers. so I changed the endgame function to be the following.
function endgame() {
setScreen("scorescreen");
ismytimergoing = false;
seconds = 60;
appendItem(scorelist, score);
for (var i = 0; i < scorelist.length; i++) {
if (scorelist[i] > scorelist[i +1]) {
highestnumber = scorelist[i];
} else if ((scorelist[i] == scorelist[i + 1])) {
highestnumber = scorelist[i];
} else {
highestnumber = scorelist[i + 1];
}
}
setText("scoretext", (scorelist + " ") + namelist);
}
I changed the endgame function, so now even if it happens because of the timer turning to zero, the seconds are reset and it's only run once, thus making the scorelist a much easier thing to deal with.
all! recently i've been trying to build a mercende prime number producer/generator, using the lucas lehmer method of testing. the code works for the first 4 numbers, and then fails for the rest. any suggestions? thanks!
var totalPrimes = Math.floor(prompt("What would you like the upper limit of
our search for primes to be?"));
for (var i = 2; i < totalPrimes; i++) {
var lucasNum = 4;
var curNumber = (Math.pow(2, (i+1))-1);
for (var x = 0; i-1 > x; x++) {
if (lucasNum / curNumber > 1) {
lucasNum = (Math.pow(lucasNum, 2)-2);
} else {
lucasNum = (Math.pow(lucasNum, 2)-2);
}
}
if (lucasNum % curNumber === 0) {
console.log("The number " + curNumber + " is prime");
} else {
console.log("The number " + curNumber + " is not prime");
}
}
The mantissa (or significand) of a Javascript number is 53-bit wide. Therefore, the biggest integer that can be stored in full precision is:
2^53 - 1 = 9007199254740991 = Number.MAX_SAFE_INTEGER
(You may want to read this page for more details.)
Your algorithm is likely to hit this limit very quickly. The precision explosion occurs within this statement:
lucasNum = (Math.pow(lucasNum, 2)-2);
which is included in a loop.
I am new to javascript and am having an issue with displaying the guessed letters in my Hangman game. When the user clicks on the "guess" button, the checkinput() method should start, and this should run:
//loop through word and if guess equals the character of the inputted work, replace - with letter.
for (i = 0; i < input.length; i++) {
//if user's guess is matched against one of the letters of the word, this will execute.
if (guess == input.substring(i, i + 1)) {
placeholder = placeholder.substring(0, i) + guess + placeholder.substring(i + 1, placeholder.length);
spguess.innerHTML = placeholder;
//if guessed letter is wrong, push into wrongg array
} else if (guess != input.substring(i, i + 1)){
wrongg.push(guess);
console.log(wrongg);
}
}
}
The else if part is where I am having issues. I would like to be able to console.log the guessed letters(incorrect letters that don't match the inputted word). Could you point me in the right direction? https://jsfiddle.net/gdbn47or/ is the jsfiddle
You're having problems i think because you have your wrongg.push inside the cycle, so even when the guess is right for the forth letter, it will still enter the wrongg array 3 or even more times, what you should do is for each cycle you should have a boolean (found), then change your if to:
if (guess == input.substring(i, i + 1)) {
placeholder = placeholder.substring(0, i) + guess + placeholder.substring(i + 1, placeholder.length);
spguess.innerHTML = placeholder;
found = true;
}
Then only do the else if part after the for cycle if the found boolean is false
I was having trouble with the OnClick method I was learning while creating a game. Every time I enter the value and click the button, it is stuck in a loop, I tried document.write and it works using that, but than it opens a new page instead of showing up on screen.
I am new to the programming community, so any help would be nice.
<body>
<p>Enter an integer between 1-100 here:
<input id="number" type="text" />
</p>
<p>
<button onclick="onclickFunction()" type="button">Enter</button>
</p>
<p id="result"></p>
<script type="text/javascript">
function onclickFunction() {
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
var intNumber;
var count = 0;
var bool = false;
do {
do {
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
if (intNumber > c) {
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
} else if (intNumber < c) {
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
} else if (intNumber == c) {
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
count = count + 1
} while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
</script>
</body>
Updated:
<script type="text/javascript">
// Declare all your functions first
// These functions expect no parameters and return values.
function onclickFunction()
{
var a = Math.random();
var b = a * 100;
var c = Math.floor(b);
// Input from text box.
var randomNumber = document.getElementById("number").value;
// Output to paragraph.
if (randomNumber < c && randomNumber != c)
{
document.getElementById("result").innerHTML = "Too Low " + "</br>";
}
else if (randomNumber > c && randomNumber != c )
{
document.getElementById("result").innerHTML = "Too High" + "</br>";
}
else if (randomNumber == c)
{
document.getElementById("result").innerHTML = "Win!";
}
// Clear text box for further input.
document.getElementById("name").value = "";
}
</script>
<p>Enter an integer between 1-100 here: <input id="number" type="text" /></p>
<p><button onclick="onclickFunction()" type="button">Enter</button></p>
<p id="result"></p>
</body>
First of all, it is always useful to create a fiddle.
That way people who are reading your question can run your code immediately.
Let's break down the code
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
This can be done in a single line, to save variables.
do
{
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
I'm not a big fan of using do/while loops this way, although it can come handy when you want to run the do code at least once, like now.
This loop keeps running when the number is bigger than 100, or smaller than 0. So if I pick an incorrect number that means my browser crashes.
if (intNumber>c){
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
}else if (intNumber<c){
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
}else if (intNumber == c){
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
First you are checking if the guess is bigger than the answer, than if it's smaller. That means that the last check if it's equal is unnecessary, since that is the only option left. You can just use an else here.
Also try to be consistent with your spacing and where you place your curly brackets.
do{
//Stuff
}
and
do
{
//Stuff
}
Are both valid ways to use brackets, but stick to one style or your code will get too confusing.
count = count + 1
A small oversight here is that the count starts at 0. So when you guess the number in a single try, it will say you have done it in 0 tries.
while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
All the previous code will be done until bool becomes true. The problem here is that if I entered a wrong number (or an invalid number). The program will keep running the if statement which requires a lot of computer power since it never stops. It is impossible to change your guess and the page crashes, because the browser is stuck in the while loop.
The simplest solution for this is to calculate if the new guess was correct when the player inputs a new number. So when onClickFunction is called again.
That way you never have to use a while loop. Although you have to calculate the random number somewhere else.
I hope that helped, if you have any question let me know!
I am trying to write a very simple JS program. I want it to generate 10 random numbers between 1 and 100 and display how many of them are even and how many are odd. I've been looking all over and I can't find why this isn't working. It's displaying 0 even numbers and 10 odd numbers, no matter the combination. What am I overlooking?
function main()
{
var number = 0;
var totalNumbers = 0;
var evenNumbers = 0;
var oddNumbers = 0;
document.write("Here are ten random numbers between 1 and 100:<br><br>");
while(totalNumbers < 10)
{
number = document.write((Math.floor((Math.random()* 100)+1)) + "<br>");
if(number % 2 == 0)
{
evenNumbers++;
}
else
{
oddNumbers++;
}
totalNumbers++;
}
document.write("<br><br>Even Numbers: " + evenNumbers + "<br>" +
"Odd Numbers: " + oddNumbers);
}
document.write() does not return a number. Store the number in a variable before calling document.write().
while(totalNumbers < 10)
{
var number = Math.floor((Math.random()* 100)+1;
document.write(number + "<br>");
if(number % 2 == 0)
{
evenNumbers++;
}
else
{
oddNumbers++;
}
totalNumbers++;
}