Problems with Javascript Decreasing Value and Quitting Loop - javascript

I am having trouble with this hangman game that I am building. I am adding basic functionality so that if you do not guess a correct letter then a guessNumber variable decreases by one. The problem I am having with my current code is that when a player guesses an incorrect letter - it quits the while loop altogether. Am I structuring either my while loop or the positioning of the guessNumber--;? I have been tinkering around with this code for about an hour and still cannot figure this out!
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>Hangman</h1>
<script>
// array of words
var words = [
"trajectory", "symphony", "desire", "antfarm", "dancer", "happiness", "positioning",
"hobbit", "obituary", "cheetah", "sunrise", "antithesis", "wrong", "diamonds",
"partnership", "oblique", "sanctuary"];
// pick a random word
var word = words[Math.floor(Math.random() * words.length)];
// set up the answer array
var answerArray = [];
for (var i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
var remainingLetters = word.length;
//amount of guesses
var guessNumber = 5;
//the game loop
while (remainingLetters > 0 && guessNumber > 0) {
//show the player their progress
alert("Your word is " + answerArray.join(" ") + "and you have " +guessNumber+ " guesses left");
//get a guess from player
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
//exit the loop
alert("Ok you can quit");
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else
//update the game state with the guess
for (var j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
}
} else {
guessNumber--;
}
}
//end game loop
//alert to congratulate player
alert(answerArray.join(" "));
alert("Good job! The answer was " + word);
</script>
</body>
</html>

You were decrementing guessNumbers each time the loop didn't find the letter. The guessNumbers-- needs to be outside of the loop so it only reduces the guess number once per input.
// array of words
var words = [
"trajectory", "symphony", "desire", "antfarm", "dancer", "happiness", "positioning",
"hobbit", "obituary", "cheetah", "sunrise", "antithesis", "wrong", "diamonds",
"partnership", "oblique", "sanctuary"];
// pick a random word
var word = words[Math.floor(Math.random() * words.length)];
// set up the answer array
var answerArray = [];
for (var i = 0; i < word.length; i++) {
answerArray[i] = "_";
}
var remainingLetters = word.length;
//amount of guesses
var guessNumber = 5;
//the game loop
while (remainingLetters > 0 && guessNumber > 0) {
//show the player their progress
alert("Your word is " + answerArray.join(" ") + "and you have " +guessNumber+ " guesses left");
//get a guess from player
var guess = prompt("Guess a letter, or click cancel to stop playing.");
if (guess === null) {
//exit the loop
alert("Ok you can quit");
break;
} else if (guess.length !== 1) {
alert("Please enter a single letter.");
} else {
//update the game state with the guess
for (let j = 0; j < word.length; j++) {
if (word[j] === guess) {
answerArray[j] = guess;
remainingLetters--;
}
}
guessNumber--;
}
} //end game loop
//alert to congratulate player
alert(answerArray.join(" "));
if (remainingLetters === 0) alert("Good job! The answer was " + word);
else alert("No more guesses! The answer was " + word);
<!DOCTYPE html>
<html>
<head>
<title>Hangman</title>
</head>
<body>
<h1>Hangman</h1>
</body>
<html>

Related

can not display the dialog when load both file .js or .html?

I am having trouble with this problem. When I coded this very simple javascript code from head first javasript book, they said to me that I must saved it as the name battle.js and run it, but after that, they said to me that I must run it as the name battle.html. Here is the code
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = promt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3/guesses);
alert(stats);
As they described, it must appear a dialog and we can enter something into that, but when I ran it, nothing appeared.
I just a newbie with javascript, could you please give me some ideas ? Thank you very much.
Your code has typing mistake. replace promt to prompt
var location1 = 3;
var location2 = 4;
var location3 = 5;
var guess;
var hits = 0;
var guesses = 0;
var isSunk = false;
while (isSunk == false) {
guess = prompt("Ready, aim, fire! (enter a number from 0-6):")
if (guess < 0 || guess > 6) {
alert("Please enter a valid cell number!");
} else {
guesses = guesses + 1;
if (guess == location1 || guess == location2 || guess == location3) {
alert("HIT!");
hits = hits + 1;
if (hits == 3) {
isSunk = true;
alert("You sank my battleship!");
}
} else {
alert("MISS");
}
}
}
var stats = "You took " + guesses + " guesses to sink the battleship, " +
"which means your shooting accuracy was " + (3 / guesses);
alert(stats);

My JavaScript console game is not working

This is my first time asking a question here, so pardon if it has an error/is less descriptive.
Actually, I am a beginner in JavaScript, and while making a console guess game, there is just nothing in the output window(it supports alert and prompt boxes). Here's the code:
function runGame() {
Boolean isPlaying = true;
var tries = 3;
var guess = 0;
var randInt = Math.floor(Math.random(10) * 1);
alert("You have 3 chances to guess a number between 1 & 10!");
while (guess != randInt && tries > 0) {
guess = prompt("Enter a guess between 1 & 10: ");
if (guess > randInt) {
tries--;
alert("Too high!");
} else if (guess < randInt) {
tries--;
alert("Too low!");
} else {
alert("Exactly! " + randInt + " it is! You've won!");
}
}
if (tries < 1) {
isPlaying = false;
}
}
while (isPlaying == true) {
runGame();
}
Moved your while isPlaying to the inside while loop. A while loop with a function inside will just call that function over and over again.
Math.random(10) only changes the seed, it does not choose between 1-10.
function runGame() {
var isPlaying = true;
var tries = 3;
var guess = 0;
var randInt = Math.floor(Math.random() * 10);
alert("You have 3 chances to guess a number between 1 & 10!");
while (guess != randInt && tries > 0 && isPlaying) {
guess = prompt("Enter a guess between 1 & 10: ");
if (guess > randInt) {
tries--;
alert("Too high!");
} else if (guess < randInt) {
tries--;
alert("Too low!");
} else {
alert("Exactly! " + randInt + " it is! You've won!");
}
}
if (tries < 1) {
isPlaying = false;
}
}
runGame()

Hangman same letter cannot be used again javascript

I am trying to run a program that makes the user guess the word by typing in the letter. The same letter should not be allowed to be inputted twice. I was thinking of storing each letter inputted in a list and then I would loop through the list checking each element against the user input. If it is inputted twice and error message like try again will occur. This is what I have so far.
var x = ["Football", "Pie", "Red", "Amber", "Purple", "Blue"];
var y = x[Math.floor(Math.random() * x.length)].toLowerCase();
var answerArray = [];
var lettersUsed = [];
var numberOfGuesses = 10;
for (var i = 0; i < y.length; i++)
{
answerArray[i] = "_";
}
var remainingLetters = y.length;
while (remainingLetters > 0 && numberOfGuesses > 0)
{
console.log(answerArray.join(" "));
var guess = prompt("Guess a letter\n");
if (guess === null)
{
console.log("Game over");
break;
}
else if (guess.length !== 1)
{
console.log("Enter a single letter\n");
}
else
{
numberOfGuesses--;
lettersUsed.push(guess);
for (var j = 0; j < y.length; j++)
{
if (y[j] === guess.toLowerCase() && answerArray[j] === "_")
{
answerArray[j] = guess.toLowerCase();
remainingLetters--;
}
}
}
}
console.log(answerArray.join(" "));
if (numberOfGuesses > 0)
{
console.log("Well done! You've won! Your stick guy has been saved!\n");
}
else
{
console.log("Game over! The word was " + y);
}
///console.log(lettersUsed);
How do I write the for loop? Any help would be appreciated.
You can use the Array.includes(item) method. It will return true if the item is in the array. For example:
let lettersUsed = ['a', 'b', 'c'];
let newLetter = 'b';
if (lettersUsed.includes(newLetter)) {
console.log('letter already used');
} else {
console.log('letter not used yet');
}
Edit in response to question from OP:
You could add this after you check the input length:
else if (guess.length !== 1)
{
console.log("Enter a single letter\n");
}
else if (lettersUsed.includes(guess))
{
console.log('Letter already used');
}
else
{
numberOfGuesses--;

Can't understand the logic of a JavaScript code block [Bulls and Cows game]

I'm in need of a little help. I need to write a detailed interpretation of a JavaScript code for a game of Bulls and Cows and I don't understand exactly what's happening in the main logic block. This is the block:
//Check Bull,Cow,Try Again
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
for (var k = 0; k < userText.length; k++) {
if ((getNum[i] == userText[k]) && (i == k)) {
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
cow++;
}
}
}
if (bull == 0 && cow == 0) {
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
}
check = true;
}
Also here's the entire program in case you need to check the interconnection of variables and such:
var getNum = new Array();
var numLength;
var check = true;
window.onload = function() {
numLength = document.getElementById("select").value;
setNumber();
}
/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
var random;
getNum.splice(0, getNum.length);
while (getNum.length < numLength) {
random = Math.floor(Math.random() * 9) + 1;
for (var i = 0; i < getNum.length; i++) {
if (getNum[i] == random) {
check = false;
break;
}
}
if (check) {
getNum.push(random);
}
check = true;
}
}
//Check user number
function checkUserText() {
var userText = document.getElementById("userText").value;
var setText = document.getElementById("textArea");
//Check if userText is number
for (var i = 0; i < userText.length; i++) {
if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
|| userText.length != numLength) {
setText.innerHTML += "Type only" + numLength + " numbers!\n";
check = false;
break;
}
}
//Check Bull,Cow,Try Again
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
for (var k = 0; k < userText.length; k++) {
if ((getNum[i] == userText[k]) && (i == k)) {
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
cow++;
}
}
}
if (bull == 0 && cow == 0) {
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
}
check = true;
}
//change difficulty
function difficulty() {
numLength = document.getElementById("select").value;
reload();
}
//restart game
function reload() {
setNumber();
document.getElementById("textArea").innerHTML = "";
}
I understand the general idea of the block but I can't see the specifics, I can't see the logic behind it, if someone could explain this block to me or make a quick flow chart I would be more than grateful.
var getNum = new Array();
var numLength;
var check = true;
window.onload = function() {
numLength = document.getElementById("select").value;
setNumber();
}
/*Get random numbers
Numbers must not be the same as each other
(found this entire codeblock on the internet
and adapted it, not gonna lie)*/
function setNumber() {
var random;
getNum.splice(0, getNum.length);
while (getNum.length < numLength) {
random = Math.floor(Math.random() * 9) + 1;
for (var i = 0; i < getNum.length; i++) {
if (getNum[i] == random) {
check = false;
break;
}
}
if (check) {
getNum.push(random);
}
check = true;
}
}
//Check user number
function checkUserText() {
var userText = document.getElementById("userText").value;
var setText = document.getElementById("textArea");
//Check if userText is number
for (var i = 0; i < userText.length; i++) {
if (userText.charCodeAt(i) < 48 || userText.charCodeAt(i) > 57
|| userText.length != numLength) {
setText.innerHTML += "Type only" + numLength + " numbers!\n";
check = false;
break;
}
}
//Check Bull,Cow,Try Again
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
for (var k = 0; k < userText.length; k++) {
if ((getNum[i] == userText[k]) && (i == k)) {
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
cow++;
}
}
}
if (bull == 0 && cow == 0) {
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
}
check = true;
}
//change difficulty
function difficulty() {
numLength = document.getElementById("select").value;
reload();
}
//restart game
function reload() {
setNumber();
document.getElementById("textArea").innerHTML = "";
}
<!DOCTYPE html>
<html>
<head>
<title>Bulls and Cows</title>
<script type="text/javascript" src="operation.js">
</script>
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<style>
h2 {
font-family: Lobster;
color: blue;
}
body {
background-color: #cccccc
}
</style>
</head>
<body>
<h2>Bulls and Cows</h2>
<label for="userText">Type here: </label>
<input type="text" id="userText"/>
<br />
<button id="ch" onclick="checkUserText()">check</button>
<button id="re" onclick="reload()">restart</button>
Length : <select id="select" onchange="difficulty()">
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>
<br />
<textarea id="textArea" rows="20" cols="30" readonly="readonly" style="overflow-y: scroll"></textarea>
</body>
</html>
// ok lets assume the getNum.length is 3
// and the random getNum is 123
// and user enters 321 and clicks check
var bull, cow;
if (check) {
bull = 0;
cow = 0;
for (var i = 0; i < getNum.length; i++) {
// this will loop three times
// in the first iteration getNum[i] == 1
// the second iteration getNum[i] == 2
// the third iteration getNum[i] == 3
for (var k = 0; k < userText.length; k++) {
// for each iteration of getNum it will iterate all user input (also 3 times)
// so 3 times per iteration of getNum, clear so far? good
// so at first iteration userText[k] == 3
// so at second iteration userText[k] == 2
// so at third iteration userText[k] == 1
// while i keeps the value of the outer loop
// this expression checks if user input matches the same number on the same position in getNum
if ((getNum[i] == userText[k]) && (i == k)) {
// in the second iteration of the outer loop its a bull because
// getNum[i] == 2 == userText[k] == 2 AND 1 == 1 (number and position of number/index is matching the random number
bull++;
} else if ((getNum[i] == userText[k]) && (i != k)) {
// in the first and last iteration of the outer loop its a cow because
// getNum[i] == 1/2 == userText[k] == 1/2 AND 0/2 is NOT 2/0 (number is matching but position not matching)
cow++;
}
// if the getNum[i] doesnt exist at all in userText, neither cow or bull will count up
}
}
if (bull == 0 && cow == 0) {
// so if no number matched - try again
setText.innerHTML += "try again\n";
} else if (bull == numLength) {
// if all numbers and positions (cow) matched you won
setText.innerHTML += numLength + " bulls! you won the game!!!\nclick restart to play again\n";
} else {
// else show how many "cows" and "bulls"
setText.innerHTML += userText + " : ";
setText.innerHTML += (bull + " bull(s), " + cow + " cow(s)!\n");
}
// so the output of above assumption would be
// 1 bull, 2 cows
// cool game ;-)
}

Simple Guessing Game Program in Javascript

Trying to create a very simple number guessing game as a first project. I want the player to have 5 guesses before they lose.
I'm having difficulty troubleshooting the bugs or coding mistakes.
var num = Math.floor((Math.random(1,10) * 10) +1);
console.log(num); //To check
var counter = 5;
while(counter > 0){
function guess(){
counter = counter-1
var guess = prompt("You've got " + counter + " tries to guess the number.");
if (num == guess){
alert("That's the number!");
}else if (guess != (int){
alert("That's not a number...");
}else{
alert("Nice try");
}
}
}
alert("You lost.");
Working fiddle: http://jsfiddle.net/0skh4t4r/
var num = Math.floor((Math.random(1, 10) * 10) + 1);
console.log(num); //To check
var counter = 5;
function guess() {
var x = prompt("You've got " + counter + " tries to guess the number.");
if (!x) return; // cancel the game
counter--;
if (num === parseInt(x)) {
alert("That's the number!");
return;
} else if (isNaN(x)) {
alert("That's not a number...");
} else {
alert("Nice try");
}
if(counter === 0) {
alert("You lost");
} else {
guess(); // next try
}
}
guess();

Categories

Resources