2 players Javascript hangman game problem with prompt - javascript

I am currently making a hangman game, 1st player need to enter a word the player 2 need to guess via a prompt. When i enter the word via the prompt it's in the console log but it's not showing in the page. It is suppose to be show in underslash like: '_ _ _ _ _' depending on the length of the word. How do I get to show the word in underslash form?
Here is what I have so far.
Thanks!
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Hangman</title>
</head>
<body>
<div class="container">
<h1>Hangman</h1>
<div>Wrong Guesses: <span id='mistakes'>0</span> of <span id='maxWrong'></span></div>
<div>
<img id='hangmanPic' src="./images/0.jpg" alt="">
<p>Guess the word:</p>
<p id="wordSpotlight">The word to be guessed goes here</p>
<div id="keyboard"></div>
<button class="btn btn-info" onClick="reset()">Reset</button>
</div>
</div>
</body>
</html>
Script:
<script>
let answer = '';
let maxWrong = 8;
let mistakes = 0;
let guessed = [];
let wordStatus = null;
function randomWord() {
var secretWord = prompt("Player 1, enter a word to guess", "");
secretWord = secretWord.toUpperCase();
console.log("Word to guess: " + secretWord);
var secretWordArray = Array.from(secretWord);
console.log("Word to guess (array): " + secretWordArray);
var wordArray = [];
for (var i = 0; i < secretWordArray.length; i++) {
motArray[i] = " _ ";
}
return wordArray;
}
function generateButtons() {
let buttonsHTML = 'abcdefghijklmnopqrstuvwxyz'.split('').map(letter =>
`<button class="btn btn-lg btn-primary m-2" id='` + letter + `'onClick="chooseLetter('` + letter + `')">` + letter + `</button>`).join('');
document.getElementById('keyboard').innerHTML = buttonsHTML;
}
function chooseLetter(chosenLetter) {
guessed.indexOf(chosenLetter) === -1 ? guessed.push(chosenLetter) : null;
document.getElementById(chosenLetter).setAttribute('disabled', true);
if (answer.indexOf(chosenLetter) >= 0) {
guessedWord();
checkIfGameWon();
} else if (answer.indexOf(chosenLetter) === -1) {
mistakes++;
updateMistakes();
checkIfGameLost();
updateHangmanPicture();
}
}
function updateHangmanPicture() {
document.getElementById('hangmanPic').src = './images/' + mistakes + '.jpg';
}
function checkIfGameWon() {
if (wordStatus === answer) {
document.getElementById('keyboard').innerHTML = 'You Won!!!';
}
}
function checkIfGameLost() {
if (mistakes === maxWrong) {
document.getElementById('wordSpotlight').innerHTML = 'The answer was: ' + answer;
document.getElementById('keyboard').innerHTML = 'You Lost!!!';
}
}
function guessedWord() {
wordStatus = answer.split('').map(letter => (guessed.indexOf(letter) >= 0 ? letter : " _ ")).join('');
document.getElementById('wordSpotlight').innerHTML = wordStatus;
}
function updateMistakes() {
document.getElementById('mistakes').innerHTML = mistakes;
}
function reset() {
mistakes = 0;
guessed = [];
document.getElementById('hangmanPic').src = './images/0.jpg';
randomWord();
guessedWord();
updateMistakes();
generateButtons();
}
document.getElementById('maxWrong').innerHTML = maxWrong;
randomWord();
generateButtons();
guessedWord();
</script>

Using a for loop, iterate over the secret word character by character, and check if it's in the guessed array. If it is, output the character followed by a space. If not, output an underscore followed by a space.
If there are no guessed letters this will output a row of underscores.
Watch for issues with upper and lower case.
let output = '';
let secret = "secret";
let guessed = ['e', 't'];
for (let char of secret) {
output += ((guessed.indexOf(char) === -1)?'_':char)+" ";
}
output = output.trim();
console.log(output); // _ e _ _ e t

Related

I am having trouble getting my function mygame() to run in my Javascript program

I am creating a wheel of fortune like game where a player may have 10 guesses to guess a hidden word and I am using charAt and for loops for the guessing. When I go to click on the button in my html the program will not run.
function myGame()
{
var name = prompt("What is your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = "Today's date is " + d;
var count = 0;
var phrase = "javascriptisneat";
var word = "";
var checkWin = false;
var w_lgth = phrase.length;
var guess;
var correct_guess = false;
for (var i = 0; i < w_lgth; i++)
word = word + "/ ";
document.getElementById("wheel_game").innerHTML = word;
while (checkWin == false && count < 10)
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < w_lgth; j++)
{
if(guess == phrase.charAT(j))
{
correct_guess = true;
var set = 2 * j;
word = setCharAt(word, set, guess);
}
}
document.getElementById("wheel_game").innerHTML = word;
checkWin = checkWord(phrase, word);
if(checkWin == true)
{
document.getElementById("game_result").innerHTML = ("you are a winner");
else if (checkWin == false)
{
document.getElementById("game_result").innerHTML = ("You Lose");
if(correct_guess == false)
count = count + 1;
}
}
}
function checkWord(phrase, o_word) { var c_word; c_word = o_word; c_word = o_word.replace(/ /g, ""); if(phrase == c_word) return true; else return false; }
function setCharAt(str, index, chr) { if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
HTML
<!DOCTYPE html>
<html>
<head>
<title>CIS 223 Chapter 7 program</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1>Welcome Player</h1>
<p> Click to begin </p>
<button type="button" onclick="myGame();">Begin</button>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<div id="wheel_game"> </div> <br>
<div id ="game_result"> </div>
<script src="myScript.js"></script>
</body>
</html>
I tried commenting out parts of the code to see what will run and what won't and it seems that the program will run up until the first else if that is on line 39. After that though the program will not run. I checked and I should have the curly brackets in the right places and am not missing any. I am using a external JavaScript file but I know this should not matter.
You forgot to close the curly braces at line 37 of the if statement. I closed the curly braces and it worked for me

I am writing a hangman style program but am having trouble checking if more than one character has been entered and the set word is guessed

I am using a while loop to check if the number of guesses is less than 10 and once 10 guesses has been made it will prompt you one last time to input the whole answer not just individual characters. I know you can use .length to check the length of the input but I am not sure how to check for a particular input of characters. I have already tried doing "(guess.length === phrase)" which is the prompt variable on the left and the word variable on the right.
Here is my code.
function myGame()
{
var name = prompt("Please enter your name");
document.getElementById("user_name").innerHTML = "Welcome " + name + " to Wheel of Fortune";
const d = new Date();
document.getElementById("today_date").innerHTML = d;
var count = 0;
phrase = "parseint";
var qs = document.querySelector("#hWord").addEventListener("keydown", qSelect);
var lgth = phrase.length; var checkWin = false; var correct_guess = false; var guess;
var numCols = lgth; new_word = ""; var crazyWord = ""; var new_word = ""; crzLgth = crazyWord.length;
for (var cols = 0; cols < numCols; cols++)
document.getElementById('wheel_game' + cols).innerHTML = ("/ ");
document.getElementById('hWord').innerHTML = "The word was " + (phrase);
function qSelect()
{
correct_guess = false;
guess = prompt("Guess a letter");
for (var j = 0; j < lgth; j++)
{
if (guess === phrase.charAt(j))
{
correct_guess = true;
count = count + 1;
document.getElementById('wheel_game' + j).innerHTML = guess;
for (var nw = 0; nw < lgth; nw++)
crazyWord = crazyWord + (document.getElementById('wheel_game' + nw).innerHTML);
}
new_word = crazyWord.substr((crzLgth - lgth), lgth);
checkWin = checkWord(phrase, new_word);
}
if (checkWin === true)
{
document.getElementById("result").innerHTML = ("You win!");
}
else if (checkWin === false)
{
document.getElementById("result").innerHTML = ("You Lose");
if (correct_guess === false)
count = count + 1;
if (count === 10)
{
guess = prompt("One last chance to guess the word");
}
else if (guess.length === phrase) {
checkWin = true;
document.getElementById("result").innerHTML = ("You win!");
}
}
function checkWord(phrase, otherWord)
{
var cleanWord;
cleanWord = otherWord;
if (phrase === cleanWord)
return true;
else
return false;
}
}
}
HTML.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<meta name="description" content="Wheel of Fortune">
<title>Wheel of Fortune Game</title>
</head>
<body>
<h1>Welcome player</h1>
<p> Click to begin </p>
<p>
<input type="button" value="Begin" onclick="myGame();" />
</p>
<p id="user_name"> </p> <br>
<p id="today_date"> </p> <br>
<p id="catagory"> </p> <br>
<div id="wheel_game0"></div> <br>
<div id="wheel_game1"></div> <br>
<div id="wheel_game2"></div> <br>
<div id="wheel_game3"></div> <br>
<div id="wheel_game4"></div> <br>
<div id="wheel_game5"></div> <br>
<div id="wheel_game6"></div> <br>
<div id="wheel_game7"></div> <br>
<div id="wheel_game8"></div> <br>
<div id="wheel_game9"></div> <br>
<div id="hWord"><p></p></div>
<div id="result"><p></p></div>
<script src="myScript.js"></script>
</body>
</html>
all you have in your while loop should be in separate function being triggered by
document.querySelector("#hWord").addEventListener("keydown", yourFunction);
and while keyword should be removed

How to add an animation gif to a javascript program

I am very new to the world of coding and I am in a coding bootcamp learning about JavaScript. We created a number guessing game and I am trying to add an animation that will run after the correct answer is entered. I have googled a few times trying to find the answer, but I was looking to see if there is an easier way. I have included a copy of the program below. If I wanted an animation to appear after the correct answer is entered, how could I do that?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
To be able do that you need to learn DOM Manipulation.
Here is a simple example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Number Guessing Game</title>
</head>
<body style='background-color:black'>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script>
function runGame() {
let guessString ='';
let guessNumber = 0;
let correct = false;
let numTries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target, numTries);
} while (!correct);
alert('You got it! The number was ' + target + '.\n\nIt took you ' + numTries + ' tries to guess correctly.');
// add your gif to the dom
// create an img element
const img = document.createElement("img")
// set the source of the gif
img.src = "https://i0.wp.com/badbooksgoodtimes.com/wp-content/uploads/2017/12/plankton-correct-gif.gif?fit=400%2C287"
// add the img element to the dom
// in this case we are gonna add it after the 'start game' button, so
// select the button element
const btn = document.querySelector("button")
// insert the img element after the button
btn.parentNode.insertBefore(img, btn.nextSibling);
}
function checkGuess(guessNumber, target, numTries) {
let correct = false;
if (isNaN(guessNumber)) {
alert('Alright smarty pants!\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!\n\nGuess Number: ' + numTries + '.');
} else if (guessNumber < target) {
alert('Your number is too small!\n\nGuess Number: ' + numTries + '.');
} else {
correct = true;
}
return correct;
}
</script>
</body>
</html>
keep going and good luck.

Can someone explain this function/argument?

I understand what the function is doing, but I don't understand why it's doing what it's doing. Specifically, I don't understand the argument for the checkLetters function (letter) and (guesses), how it works, and how it can be used in the if/else statement to determine if the letter chosen is correct or not. "Letter" is not a variable, and is only mentioned as an argument within a function, and is still used in the following fashion:
randomWord[i] == letter
blanksAndCorrect[i] = letter;
checkLetters(guesses);
Was the argument converted to a variable? The code I'm referencing is is in the Javascript text under the following sections: //call start game function & //CHECK LETTERS/COMPARE FUNCTION.
//VARIABLES
var words = ["arthur", "rugrats", "thesimpsons", "scoobydoo", "spongebob", "dannyphantom", "teentitans"]
//Empty variables to store values later
var randomWord = "";
var lettersOfWord = []
var blanks = 0;
var blanksAndCorrect = [];
var wrongGuess = [];
//Counter Variables
var wins = 0;
var losses = 0;
var guessesRemaining = 9;
// ALL FUNCTIONS
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//__________________________________________________________
//GAME START FUNCTION
//__________________________________________________________
function Game() {
//computer generates random word from words array
randomWord = words[Math.floor(Math.random() * words.length)];
// split the individual word into separate arrays, and store in new array
lettersOfWord = randomWord.split("");
//store length of word in blanks, for later use
blanks = lettersOfWord.length;
//creating a loop to generate "_" for each letter in array stored in blanks
for (var i = 0; i < blanks; i++) {
blanksAndCorrect.push("_");
}
//showing the "_" within HTML
document.getElementById("currentword").innerHTML = " " + blanksAndCorrect.join(" ");
//console logging
console.log(randomWord);
console.log(lettersOfWord)
console.log(blanks)
console.log(blanksAndCorrect)
}
//__________________________________________________________
//AUDIO FUNCTION
//__________________________________________________________
//variables for audio function
var a = document.getElementById("arthur");
var r = document.getElementById("rugrats");
var simpsons = document.getElementById("simpsons");
var scoobydoo = document.getElementById("scoobydoo");
var spongebob = document.getElementById("spongebob");
var danny = document.getElementById("danny");
var teent = document.getElementById("teent");
//__________________________________________________________
//RESET FUNCTION
//__________________________________________________________
function reset() {
guessesRemaining = 9;
wrongGuess = [];
blanksAndCorrect = [];
Game()
}
//__________________________________________________________
//CHECK LETTERS/COMPARE FUNCTION
//__________________________________________________________
//If/Else, to see if letter selected matches random word
function checkLetters(letter) {
var letterInWord = false;
//if the generated randomword is equal to the letter entered... then variable is true
for (var i = 0; i < blanks; i++) {
if (randomWord[i] == letter) {
letterInWord = true;
}
}
//if letterInWord (false)
if (letterInWord) {
//check each letter to see if it matches word
for (var i = 0; i < blanks; i++) {
if (randomWord[i] == letter) {
blanksAndCorrect[i] = letter;
console.log(blanksAndCorrect[i])
}
}
}
//otherwise, push the incorrect guess in the wrong guesses section, and reduce remaining guesses
else {
wrongGuess.push(letter);
guessesRemaining--;
}
console.log(blanksAndCorrect);
}
//__________________________________________________________
//FINAL COMPLETE FUNCTION
//__________________________________________________________
//check to see if player won...
function complete() {
console.log("wins:" + wins + "| losses:" + losses + "| guesses left:" + guessesRemaining)
//if WON...then alert, play audio, display image and reset new round
if (lettersOfWord.toString() == blanksAndCorrect.toString()) {
wins++;
aud()
reset()
//display wins on screen
document.getElementById("winstracker").innerHTML = " " + wins;
//if LOST...then alert and reset new round
} else if (guessesRemaining === 0) {
losses++;
reset()
document.getElementById("image").src = "./assets/images/try-again.png"
document.getElementById("losstracker").innerHTML = " " + losses;
}
//display losses on screen && guesses remaining countdown
document.getElementById("currentword").innerHTML = " " + blanksAndCorrect.join(" ");
document.getElementById("guessesremaining").innerHTML = " " + guessesRemaining;
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//_____________________________________________________
// EXECUTE CODE
//_____________________________________________________
//call start game function
Game()
//check for keyup, and convert to lowercase then store in guesses
document.onkeyup = function (event) {
var guesses = String.fromCharCode(event.keyCode).toLowerCase();
//check to see if guess entered matches value of random word
checkLetters(guesses);
//process wins/loss
complete();
//store player guess in console for reference
console.log(guesses);
//display/store incorrect letters on screen
document.getElementById("playerguesses").innerHTML = " " + wrongGuess.join(" ");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>CHILDHOOD SHOWS GAME</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<!--Main Heading-->
<div class="heading">
<h1>CHILDHOOD SHOWS</h1>
</div>
<div class="background">
<div class="container">
<!--Changing Image based on correct answers-->
<h2>Press Any Key To Guess This Word!</h2>
<!--Current Word Container-->
<div>
<h3 id="currentword">_ _ _ _ _</h3>
</div>
<div id="scoreboard">
<!--Guesses left Container-->
<div class="sidebar">
<h3>GUESSES LEFT:
<span id="guessesremaining"></span>
</h3>
</div>
<!--Wins counter Container-->
<div class="sidebar">
<h3>WINS:
<span id="winstracker"></span>
</h3>
</div>
<!--Loss counter Container-->
<div class="sidebar">
<h3>LOSSES:
<span id="losstracker"></span>
</h3>
</div>
<!--Wrong guesses container-->
<div class="sidebar">
<h3>LETTERS YOU GUESSED WRONG:
<span id="playerguesses"></span>
</h3>
</div>
</div>
</div>
</div>
<script src="./game.js"></script>
</body>
</html>

Making a javascript hangman game and I can't get my function to apply to repeated letters

Everything about the script works great right now unless there's a repeated letter in the word. If so, then it will only display the first of the letters. For example, if the random word is "look" it would display like this "lo k".
Unfortunately the only other related javascript hangman question here was for a script that didn't actually have issues on repeated letters. For reference: how to deal with repeated letters in a javascript hangman game. Can anyone help me get through the repeated letter issue? Thanks!
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="js/jquery-1.11.2.min.js"></script>
<script src="js/jquery-1.11.2.js"></script>
<link rel="stylesheet" href="css/main.css">
<title>Hang a Blue Devil</title>
</head>
<body>
<div class="wrapper">
<h1 class="title">Hangman</h1>
<h2 class="attempt-title">You have this many attempts left: </h2>
<ul class="hangman-word">
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
<li class="tester"></li>
</ul>
<h3 class="hangman-letters"></h3>
<input class="text-value" type="text" maxlength="1" onchange="setGuess(this.value)">
<button class="text-button" onclick="checkGuess()"></button>
<p class="letters-guessed"></p>
</div>
</body>
<script src="js/hangman.js"></script>
</html>
My JS:
var hangmanWords = [
"the","of","and","a","to","in","is","you","that","it","he",
"was","for","on","are","as","with","his","they","I","at","be",
"this","have","from","or","one","had","by","word","but","not",
"what","all","were","we","when","your","can","said","there",
"use","an","each","which","she","do","how","their","if","will",
"up","other","about","out","many","then","them","these","so",
"some","her","would","make","like","him","into","time","has",
"look","two","more","write","go","see","number","no","way",
"could","people","my","than","first","water","been","call",
"who","oil","its","now","find","long","down","day","did","get",
"come","made","may","part"
];
// declared variables
var randomNumber = Math.floor(Math.random() * 100);
var randomWord = hangmanWords[randomNumber];
var underscoreCount = randomWord.length;
var underscoreArr = [];
var counter = randomWord.length +3;
var numberTest = 0;
var lettersGuessedArr = [];
var lettersGuessedClass = document.querySelector('.letters-guessed');
var li = document.getElementsByClassName('tester');
var textValue = document.querySelector('.text-value');
var attemptTitle = document.querySelector('.attempt-title');
var hangmanWordClass = document.querySelector('.hangman-word');
var hangmanLettersClass = document.querySelector('.hangman-letters');
// actions
attemptTitle.innerHTML = "You have this many attempts left: " + counter;
console.log(randomWord);
function setGuess(guess) {
personGuess = guess;
}
for (i=0;i<underscoreCount;i+=1) {
underscoreArr.push("_ ");
underscoreArr.join(" ");
var underscoreArrString = underscoreArr.toString();
var underscoreArrEdited = underscoreArrString.replace(/,/g," ");
hangmanLettersClass.innerHTML = underscoreArrEdited;
}
function pushGuess () {
lettersGuessedArr.push(personGuess);
var lettersGuessedArrString = lettersGuessedArr.toString();
var lettersGuessedArrEdited = lettersGuessedArrString.replace(/,/g," ");
lettersGuessedClass.innerHTML = lettersGuessedArrEdited;
}
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
i += 20;
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
};
My bin:
http://jsbin.com/dawewiyipe/4/edit
You had a stray bit of code that didn't belong:
i += 20;
I took it out, and the problem went away (the loop was intended to check each character, the +=20 broke the process of checking each character)
function checkGuess() {
for (var i=0;i<randomWord.length;i+=1) {
if (personGuess === randomWord[i]) {
console.log(personGuess);
numberTest = i;
li[i].textContent = randomWord[i];
textValue.value= "";
} else if ((randomWord.length - 1) > i ) {
console.log("works");
} else {
pushGuess();
counter -= 1;
attemptTitle.innerHTML = "You have made this many attempts: " + counter;
textValue.value= "";
}
}
}
http://jsbin.com/noxiqefaji/1/edit

Categories

Resources