html and javascript game function not changing global variable - javascript

When X,Y, and Z are equal to 3 then locationName should be equal to Sol, but this is not the case. I believe the problem is with my variable name not being updated but it could be something else.
<!DOCTYPE html>
<html>
<head>
<title>Jordan's Space Explorer </title>
</head>
<body>
<button onclick="goNorth()">Go North</button>
<button onclick="goSouth()">Go South</button>
<button onclick="goEast()">Go East</button>
<button onclick="goWest()">Go West</button>
<button onclick="goUp()">Go Up</button>
<button onclick="goDown()">Go Down</button>
<button onclick="locationQuery()">Where am I?</button>
<button onClick="quit"()>Quit</button>
</body>
<script>
// Confirm user wants to play.
confirm("Do you want to play Jordan's Space Explorer?");
alert("The game is working.");
// Declare start location.
var locationY = 0;
var locationX = 0;
var locationZ = 0;
var locationName = "in Space";
//Go directions
function goNorth(){
locationY ++;
console.log("You head North.");
}
function goSouth(){
locationY --;
console.log("You head South.");
}
function goEast(){
locationX ++;
console.log("You head East");
}
function goWest(){
locationX --;
console.log("You head West");
}
function goUp(){
locationZ ++;
console.log("You go up.");
}
function goDown(){
locationZ --;
console.log("You go down.");
}
function locationQuery(){
console.log("X" +locationX);
console.log("Y" +locationY);
console.log("Z" +locationZ);
console.log("You are " +locationName);
}
// Encounters
if(locationX === 3 && locationY === 3 && locationZ === 3){
locationName = "Sol";
alert("Arrived at " + locationName);
}
if(locationX===0 && locationY===0 && locationZ===0){
alert("It worked.");
}
</script>
</html>
I am new to programming and would appreciate any help.

The problem is that you execute your // Encounters part only once, at initialization. You should put it in a function :
function encounters(){
if(locationX === 3 && locationY === 3 && locationZ === 3){
locationName = "Sol";
alert("Arrived at " + locationName);
}
if(locationX===0 && locationY===0 && locationZ===0){
alert("It worked.");
}
}
and call that function every time you change the position :
function goDown(){
locationZ --;
console.log("You go down.");
encounters();
}

Try with,
function locationQuery(){
console.log("X" +locationX);
console.log("Y" +locationY);
console.log("Z" +locationZ);
// Encounters
if(locationX === 3 && locationY === 3 && locationZ === 3){
locationName = "Sol";
alert("Arrived at " + locationName);
}
if(locationX===0 && locationY===0 && locationZ===0){
alert("It worked.");
}
console.log("You are " +locationName);
}
Update locationName against given condition by invoking locationQuery() function

Related

While loop in js faulty

I'm creating a guess the number with limited guesses. I have add an incrementor to check the number of times a user submits an answer. Everything seems to work except the loop starts at the final iteration and the games ends on the first try.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<div>Guess The Number</div>
<input type="text" id="input">
<button id="btn">Check Answer</button>
<p id="guesses" style="display: inline-block;"></p>
<p id="hint"></p>
</body>
</html>
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
btn.addEventListener('click', () => {
if(isNaN(input.value)){
input.value = "Please type a number"
} else{
const hint = document.getElementById("hint");
let i = 0;
while (i < 10){
if(input.value === rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
break;
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else{
hint.innerHTML = "Too low";
} i++; guesses.innerHTML = "You have guessed " + i + " times";
}
if(i === 10){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
}
})
I've tried changing the number in the while loop condition. I've tried moving the incrementor in and out of the loops function. I've also tried chatgpt to see if it would work. But no luck. I would really appreciate your help.
I think you're misunderstanding the while loop. The loop will run once for every instance of i from 1 to 10 then stop running when the condition in the while loop is false. Based on what you mentioned you don't want a loop at all but to store the number of guesses into its own variable and increase that variable until you reach your limit.
const rndmNum = Math.floor(Math.random() * 100) + 1;
let numberOfGuesses = 0;
btn.addEventListener('click', () => {
if (isNaN(input.value)) {
return input.value = "Please type a number";
}
const hint = document.getElementById("hint");
if (input.value === rndmNum) {
hint.innerHTML = "Congratulations, You guessed correctly!";
return;
} else if (input.value > rndmNum) {
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
numberOfGuesses++;
guesses.innerHTML = "You have guessed " + numberOfGuesses + " times";
if (numberOfGuesses === 10) {
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
}
})
I believe this is what you were trying to accomplish. The reason why it's not working with the loop because it will run ten times with the click of the button once.
const input = document.getElementById("input")
const btn = document.getElementById("btn")
const guesses = document.getElementById("guesses")
const rndmNum = Math.floor(Math.random() * 100) + 1;
//keep track of guess count
let count = 0;
//event listner to check the users answer
btn.addEventListener("click", checkAnswer)
//this function will check for answers or display game over
function checkAnswer(){
if(count > 9){
hint.innerHTML = "Game Over! The correct number was " + rndmNum;
} else if(input.value == rndmNum){
hint.innerHTML = "Congratulations, You guessed correctly!";
} else if(input.value > rndmNum){
hint.innerHTML = "Too High";
} else {
hint.innerHTML = "Too low";
}
count++
guesses.innerHTML = "You have guessed " + count + " times";
}

JavaScript - begginner questions

I have some difficulties with my first number guessing "game" in JavaScript. Can someone have a look and guide me what I did wrong? Started with that language not that long ago..
Function is assigned to one button
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start !
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check(guess) {
window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
You designed your check function to have a guess passed to it but you are just calling it without doing so. So all your comparisons are against undefined.
You are also using window.prompt to get the actual guess. What you need to do is save the value returned from the prompt into a variable and then compare it. Check the snippet.
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert(
"Guess number " + attemps + " is incorrect. The number is " + result + "."
);
}
if (attemps >= 3) {
window.alert(
"Sorry, you have run out of guesses! The number was " + hiddenNum
);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value="Guess" onClick="check()">Click to start
you need to assign the prompt
var hiddenNum;
var attemps;
hiddenNum = Math.floor(Math.random() * 10);
hiddenNum = hiddenNum + 1;
attemps = 0;
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
} else {
attemps = attemps + 1;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attemps + " is incorrect. The number is " + result + ".");
}
if (attemps >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again == "N" || again == "n") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
}
<input id="box;" class="btn" ; type="button" value='guess'onClick="check()">Click to start!
User (player) have to press the button, guess the number (1-10) within 3 attemps and then play again or not. Every attemp I do it says "number is higher" but at the end result is random, even if you chose 10.
You should store the value from window.prompt. In your code, you just use guess in the parameter of the function as the value of window.prompt which is incorrect.
Syntax for window.promp:
result = window.prompt(message, default);
Also, I have shorten your codes and store the duplicate item in a function to make it a little bit less messy.
function smallcheck() {
let again = window.prompt("Would you like to try again? Enter Y or N.", "Y");
if (again.toUpperCase() == "N") {
window.alert("Thanks for trying. Goodbye.");
window.close();
} else {
window.alert("The number has been randomized.");
window.location.reload();
}
}
function check() {
let guess = window.prompt("Please enter the number between 1 and 10", "10");
console.log(guess)
if (hiddenNum == guess) {
window.alert("Congratulations! You guessed correctly !");
smallcheck()
} else {
attempts++;
if (hiddenNum < guess) {
result = "lower";
} else {
result = "higher";
}
window.alert("Guess number " + attempts + " is incorrect. The number is " + result + ".");
}
if (attempts >= 3) {
window.alert("Sorry, you have run out of guesses! The number was " + hiddenNum);
smallcheck()
}
}
Noticed you never declared 'result'. So I made that variable into a ternary operator to shorten up your code a little more. Also, I added template literals :)
let hiddenNum = Math.floor(Math.random() * 10);
//console.log(hiddenNum);
hiddenNum = hiddenNum;
let attempts = 0;
const nextRound = function () {
let again = window.prompt('Would you like to try again? Enter Y or N.');
if (again.toUpperCase() === 'N') {
window.alert("Thank's for trying. Later nerd");
window.close();
} else {
window.alert('Try to guess the new number, nerd.');
window.location.reload();
}
};
function check() {
let guess = prompt('Please enter the number between 1 and 10');
console.log(guess);
if (hiddenNum === guess) {
alert('Congratulations! You guessed correctly !');
nextRound();
} else {
attempts++;
let result = hiddenNum < guess ? 'lower' : 'higher';
alert(`Guess number is ${attempts} is incorrect. The number is ${result}.`);
}
if (attempts >= 3) {
alert(`Sorry, you have run out of guesses! The number was ${hiddenNum}`);
nextRound();
}
}
<div>
<input
id="box"
class="btn"
style="
display: inline-block;
border-radius: 2em;
box-sizing: border-box;
color: white;
background-color: blueviolet;
cursor: pointer;
"
type="button"
value="Guess"
onClick="check()"
/>Click to start !
</div>

How to stop execution of a JavaScript program

So as a practice, I made a guess game in JavaScript where you have to guess the randomly generated number between 1 and 10 in three tries. It worked fine, but when the three tries are completed (or the user guesses the number), it starts all over again. I want it to stop when the above given circumstances are met.
Here is the code:
function runGame() {
var isPlaying = true;
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying = true) {
runGame();
}
A few things:
Put isPlaying variable global. Although you can remove it entirely as well. You already have a while loop condition that does the same thing.
Remove the equal sign when comparing your tries to zero. Otherwise it will run still when the tries reached zero.
Use a break statement when the user guessed the right answer, otherwise it will still run after guessing.
Other than those your code is fine. Here's the final code:
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries > 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
break;
}
tries--;
}
}
runGame();
= in JavaScript is used for assigning values to a variable. == in JavaScript is used for comparing two variables.
So change isPlaying = true to isPlaying == true and it will be fine.
while (tries >= 0) here you can use just while (tries > 0)
You can also declare these variables outside of the function but it's not necessary.
var isPlaying = true;
var tries = 3;
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
}
else if (guess < num) {
alert("Too low!");
}
else {
alert("Exactly! " + num + " it is! You've won!");
}
tries--;
}
if (tries == 0) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Remove the isPlaying and call runGame() directly, not in a while loop, You can break the execution if chances gets done and rest tries if the user wins
function runGame() {
var num = Math.floor(Math.random() * 10);
var guess;
var tries = 3;
alert("You have 3 chances to guess a mindset between 1 and 10!");
while (tries >= 0) {
if (tries == 0) {
alert("You have finished your chances");
break;
}
guess = prompt("Enter a guess:");
if (guess > num) {
alert("Too high!");
} else if (guess < num) {
alert("Too low!");
} else {
alert("Exactly! " + num + " it is! You've won!");
// reset tries back to three
tries = 3;
}
tries--;
}
}
runGame();

Score adds 2 points sometimes instead of 1 point

I have written a rock, paper, scissor game using javascript. I have got it to play 5 rounds and to keep track of the score every round. However, for some reason every now and then it will add 2 points to the score instead of 1. I am a beginner to javascript and have no idea where I am going wrong. I keep logically going through my loop and don't understand why it does this. How can I stop this from happening?
Help would be greatly appreciated!
let playerScore = 0;
let compScore = 0;
let draw;
/* Players Choice */
function round() {
let userInput = prompt('Rock, Paper, or Scissor?: ');
console.log(userInput);
if (userInput == 'rock'){
console.log(userInput = 1);
} else if (userInput == 'paper'){
console.log(userInput = 2);
} else if (userInput == 'scissor'){
console.log(userInput = 3);
}
/* Computers Choice */
let compMove = Math.floor(Math.random()*3) + 1;
console.log(compMove);
if (compMove == 1) {
alert('Rock!');
} else if (compMove == 2){
alert('Paper!');
} else if (compMove == 3){
alert('Scissor!');
}
return {
compMove,
userInput
};
};
/* Compare */
function result(compMove, userInput) {
if (compMove == 2 && userInput == 1) {
alert('You lose!');
compScore += 1;
} else if (compMove == 3 && userInput == 1){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 2){
alert('You Win!');
playerScore += 1;
} else if (compMove == 1 && userInput == 3){
alert('You Lose!')
compScore += 1;
} else if (compMove == userInput){
compScore;
playerScore;
}
return {
compScore,
playerScore
};
}
function game() {
for (let i=1; i <= 5; i++) {
let roundNumber = round();
result(roundNumber.compMove, roundNumber.userInput);
console.log(result(compScore, playerScore));
};
return {
compScore,
playerScore
};
};
console.log(game());
if (playerScore > compScore) {
alert('You Won the Best of 5!');
} else if (playerScore < compScore) {
alert('You Lost.')
} else {
alert('It is a Draw!');
}
You have made calls to result() twice in game(). Store the result() in a
const and put that in console.log.
Also, in the result function, you haven't really covered all the possibilities of outcomes by computer and the user. You should cover the cases where userInput is 2 and compMove is 3, also where userInput is 3 and compMove is 2.

How to add +1 to win counter every time a win occurs?

I am trying to add +1 to the win counter every time a win occurs but it doesn't work no matter what I try.
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="mycss.css">
<script src="myjavascript2.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="center">
<button onclick="myFunction1()">Play</button>
<p id="rolled">You rolled:</p>
<p id="test"></p>
<p id="rolled1">Your opponent rolled:</p>
<p id="test1"></p>
<p id="test2"></p>
<p id="test3"></p>
<br><br><br>
<span>Wins:</span><span id="span1"></span><br>
<span>Losses:</span><span id="span2"></span><br>
<span>Draws:</span><span id="span3"></span>
</div>
</body>
</html>
Javascript:
var things = [ 'rock', 'paper', 'scissors'];
function myFunction1() {
var random1 = Math.floor((Math.random()*things.length));
var random2 = Math.floor((Math.random()*things.length));
document.getElementById("test").innerHTML=things[random1];
document.getElementById("test1").innerHTML=things[random2];
document.getElementById("test2").innerHTML='';
document.getElementById("test3").innerHTML='';
document.getElementById("span1").innerHTML=win;
document.getElementById("span2").innerHTML=loss;
document.getElementById("span3").innerHTML=draw;
if (random1 == random2) {
document.getElementById("test2").innerHTML="<h3>It's a draw.</h3>";
}
else if (random1 == 0 && random2 == 2) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 1 && random2 == 0) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 2 && random2 == 1) {
document.getElementById("test3").innerHTML="You win!";
}
else if (random1 == 0 && random2 == 1) {
document.getElementById("test3").innerHTML="You lost!";
}
else if (random1 == 1 && random2 == 2) {
document.getElementById("test3").innerHTML="You lost!";
}
else if (random1 == 2 && random2 == 0) {
document.getElementById("test3").innerHTML="You lost!";
}
var test3 = document.getElementById("test3");
var win = 0;
var loss = 0;
var draw = 0;
Here is where I want to add +1 to the win counter every time a win occurs, but I can't get it to work. I have tried this:
if (test3.innerHTML == "You win!") {
document.getElementById("span1").innerHTML=win + 1;
}
This:
if (test3.innerHTML == "You win!") {
document.getElementById("span1").innerHTML=win++;
}
And this:
if (test3.innerHTML == "You win!") {
win = win + 1;
}
} //End of myFunction1
What am I doing wrong exactly?
You did not declare the variable outside the function, Declare the win variable outside the function with 0 default value. eg:-
var win = 0;
function myFunction1() {
if (test3.innerHTML == "You win!") {
win = win + 1;
....
UPDATE
Here is the fixed version DEMO
Define var win=0; outside of your function, as it is now your win variable is being created in the function and dying at the end of the function.
Another thing that you can do is: inside the function add this at the top:
var win=parseInt(document.getElementById('span1').innerText);
is test3 defined?
if (test3.innerHTML == "You win!") {
}
if not, use
if (document.getElementById("test3").innerHTML == "You win!") {
}

Categories