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 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
I'm currently making a simple math game where it generates random multiplication problems and there is multiple choices that the user can pick from. Right now I am getting stuck on how to place my shuffled answers into separate divs for the multiple choices. Also if you notice any collisions that may arise in the future a heads up would be greatly appreciated
Here's the Javascript:
var gameOn = false;
var score;
var interval;
Array.prototype.shuffle = function(){
var i = this.length, j, temp;
while(--i > 0){
j = Math.floor(Math.random() * (i+1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}//while loop bracket
return this;
}
function stopGame() {
gameOn = false;
if (interval) {
clearInterval(interval);
interval = null;
}//if interval bracket
document.getElementById("startreset").innerHTML = "Start Game";
document.getElementById("time-remaining").style.display = "";
}//function stopGame bracket
//if we click on the start/reset
document.getElementById("startreset").onclick = function () {
//if we are not playing
if (gameOn) {
stopGame();
}/*if gameOn bracket*/ else {
//change mode to playing
gameOn = true;
//set score to 0
score = 0;
document.getElementById("scorevalue").innerHTML = score;
//show countdown box
document.getElementById("time-remaining").style.display = "block";
document.getElementById("startreset").innerHTML = "Reset Game";
var counter = 60;
//reduce time by 1sec in loops
interval = setInterval(timeIt, 1000);
function timeIt(){
document.getElementById("timer-down").innerHTML = counter;
counter--;
//timeleft?
//no->gameover
if ( counter === 0) {
stopGame();
document.getElementById("game-over").style.display = "block";
document.getElementById("game-over").innerHTML = "Game Over" + "<br />" + "<br />" + "Your Score is " + score + "!";
}//if counter bracket
}//timeIt function bracket
//generate new Q&A
generateQA();
function generateQA(){
//this is the first number in the equation
var Na = 1+ Math.round(Math.random() * 9);
//this is the second number in the equation
var Nb = 1+ Math.round(Math.random() * 9);
//the correct answer is when you multiply both together
correctAnswer = Na * Nb;
//these are the randomly generated wrong answers
var w1 = 1+ Math.round(Math.random() * 16);
var w3 = 1+ Math.round(Math.random() * 22);
var w4 = 1+ Math.round(Math.random() * 92);
document.getElementById("question").innerHTML = Na + "x" + Nb;
console.log(correctAnswer);
var myArray = [w1, correctAnswer, w3, w4];
var result = myArray.shuffle();
document.getElementById("box1", "box2", "box3", "box4").innerHTML = result;
}//generateQA function bracket
}//else statement bracket
}//startreset button function bracket
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Math Game</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
<link rel="stylesheet" href="styling.css">
</head>
<body>
<div id="title">
The Matheroo
</div>
<div id="sunYellow">
<!--Because the score value is going to change as the user plays the game we need to place it in a span and refer to it later with some JAVA-->
<div id="score">
Score: <span id="scorevalue">0</span>
</div>
<div id="correct">
Correct!
</div>
<div id="wrong">
Try Again
</div>
<div id="question">
<span id="firstInt"></span><span id="secondInt"></span>
</div>
<div id="instruction">
Click on the Correct Answer
</div>
<div id="choices">
<div id="box1" class="boxes"></div>
<div id="box2" class="boxes"></div>
<div id="box3" class="boxes"></div>
<div id="box4" class="boxes"></div>
</div>
<div id="startreset">
Start Game
</div>
<div id="time-remaining">
Time Remaining: <span id="timer-down">60</span> sec
</div>
<div id="game-over">
<br />
Game Over
</div>
</div>
<script src="Javascript.js"></script>
</body>
</html>
You can't select multiple elements with getElementById as you did in this line document.getElementById("box1", "box2", "box3", "box4").innerHTML = result;. Selecting multiple elements will be done with querySelectorAll.
But for your case, just do it this way:
document.getElementById("box1").innerHTML = result[0];
document.getElementById("box2").innerHTML = result[1];
document.getElementById("box3").innerHTML = result[2];
document.getElementById("box4").innerHTML = result[3];
You can also do it with a for loop.
I'm making a simple hangman game in vanilla javascript and would like the game to reset after a player losses. Specifically, I'd like to:
1. reset the "guessRemain" variable
2. clear out the "guess" id, so none of the guessed letters are shown
3. choose another random word from the array.
Thanks in advance for your help!
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Hangman Game</title>
<link rel="stylesheet" type="text/css" href="assets\css\reset.css"/>
<link rel="stylesheet" type="text/css" href="assets\css\style.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<script src="https://use.fontawesome.com/ca6de464ee.js"></script>
</head>
<body>
<div id="white">
<img src="assets\images\turkey.png" alt="turkey" class="turkeyImage">
</div>
<div id="orangebox">
<h4>thanksgiving</h4>
<h4 class="hangman">hangman</h4>
</div>
<div class="instructions">
<h1>Instructions:</h1>
<br/>
<h2>1. Guess a Thanksgiving dish!</h2>
<br/>
<h3>2. Press any key to begin.</h3>
</div>
<div class="display">
<p class="greywords">Current Word:</p>
<br/>
<p id="current"></p>
<br/>
<br/>
<p class ="greywords">Number of Guesses Remaining:</p>
<br/>
<p id="remain"></p>
<br>
<br/>
<p class="greywords">Letters Already Guessed:</p>
<p id="guess"></p>
<br>
<br/>
<p class="greywords">Wins:</p>
<p id="win"></p>
<br>
<br/>
<p class="greywords">Losses:</p>
<p id="loss"></p>
</div>
<!-- End of HTML -->
<script type="text/javascript">
// Step 2: create variable of the food words
var wins = 1;
var losses = 1;
var guessRemain = 10;
var foodWords = [
"pie",
"turkey",
"bacon",
"bread"
];
// Step 1: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
var randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
var count = [];
for (var i = 0; i < randomWord.length; i++) {
count[i] = "_ ";
}
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;
//Step 6: have it recognize that there are remaining letters
var remainingLetters = randomWord.length;
console.log("I HAVE " + remainingLetters + " left");
//Step 7: function for when they click a key
document.onkeyup=function(event) {
var userGuess = event.key;
document.getElementById("guess").innerHTML += userGuess + " ";
// console.log(randomWord.length);
if (randomWord.includes(userGuess)) {
// console.log("test");
// Step 7: if this statment is true, then modify the count variable, replace the dash in count with letter, and it has the correct position, and display the letter
var guessIndex = randomWord.indexOf(userGuess);
//console.log(randomWord.indexOf(userGuess));
count[guessIndex] = userGuess
//console.log(count);
document.getElementById("current").innerHTML = count;
remainingLetters--;
console.log("I HAVE " + remainingLetters + " left");
if (remainingLetters === 0) {
document.getElementById("win").innerHTML = wins++;
console.log("I have won");}
}
// Step 8: if not true, then subtract a guess
else {
document.getElementById("remain").innerHTML = guessRemain--;
document.getElementById("remain").innerHTML = guessRemain;
if (guessRemain === 0) {
document.getElementById("loss").innerHTML = losses++;
console.log("I have lost");
}
}
}
// Step 10: if there are no letters remaining in count, then add "1" to the win id and reset the page
// if (remainingLetters === 0) {
// document.getElementById("#win").innerHTML = winSs++;
// console.log("I have won");
//console.log("i win");
// function reset() {
// document.getElementById("display").reset();
// }
// }
// Step 11: if there are no guesses remaining, add a "1" to the loss id and reset the page
// if (remainingGuess < 0) {
// document.getElementById("#loss").innerHTML = ++1;
// function reset() {
// document.getElementById("display").reset();
// }
// }
</script>
</body>
<div class="footer">
</div>
</html>
Simply set the variable, so to "reset" guessRemain you'd just type
guessRemain = 10;
inside your reset function, The same would go for any other variables.
As for the Guesses already displayed on the web page, you'd do something similar to this
document.getElementById("guess").innerHTML = "";
Hope that helps :)
First off, clear the guess element somewhere in steps 1-6 by setting its innerHTML to an empty string. Take your steps 1-6 and put them in a function called initialize like so:
Edit: declare your variables wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters outside of the function below so that you'll have access to them in your onkeyup handler
var wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters;
function initialize() {
// Step 1: create variable of the food words
wins = 1;
losses = 1;
guessRemain = 10;
foodWords = [
"pie",
"turkey",
"bacon",
"bread"
];
// Clear the guess
document.getElementById("guess").innerHTML = "";
// Step 2: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
count = [];
for (var i = 0; i < randomWord.length; i++) {
count[i] = "_ ";
}
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;
//Step 6: have it recognize that there are remaining letters
remainingLetters = randomWord.length;
console.log("I HAVE " + remainingLetters + " left");
}
Call the function initialize() somewhere in your code (outside of the onkeyup handler) to initialize your game for the first time.
Now, you can reuse the initialize function whenever you want to reset your game. For example, you can do something like this when the game is over (place this code inside your onkeyup handler towards the bottom):
if (remainingLetters === 0 || remainingGuess === 0) {
inititalize();
}
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