Javascript calculator stringing multiple operators - javascript

I'm working on The Odin Project curriculum at the moment, and the calculator is the final project of the foundations. I have a mostly working app, but I just can't seem to be able to chain multiple operators without having to press the equals button in between. To clarify, I should be able to do 5+5+5 etc. At the moment however, it does nothing after the first 5+5. I have been stuck on this for quite a while, and am getting frustrated.
Any help is greatly appreciated.
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Calculator</title>
</head>
<body>
<div class="calculator">
<div class="output">
<div class="previous"></div>
<div class="operator-display"></div>
<div class="current"></div>
</div>
<button class="span-two clear">Clear</button>
<button class="span-two delete">Delete</button>
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button class="operator">+</button>
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button class="operator">-</button>
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button class="operator">*</button>
<button class="decimal">.</button>
<button class="number">0</button>
<button class="equals">=</button>
<button class="operator">/</button>
</div>
</body>
<script src="script.js"></script>
</html>
javascript:
const numberBtns = document.querySelectorAll(".number");
const operationBtns = document.querySelectorAll(".operator");
const equalsBtn = document.querySelector(".equals");
const clearBtn = document.querySelector(".clear");
const deleteBtn = document.querySelector(".delete");
const previous = document.querySelector(".previous");
const current = document.querySelector(".current");
const operatorDisplay = document.querySelector(".operator-display");
let decimalBtn = document.querySelector(".decimal");
let firstNumber = 0;
let secondNumber = 0;
let result;
//function to clear output screen
function clearOutput(){
previous.innerText = "";
current.innerText = "";
operatorDisplay.innerText = "";
}
//calls function to clear screen on a click
clearBtn.addEventListener("click", ()=>{
clearOutput();
})
//add number to screen on click
numberBtns.forEach(button => {
button.addEventListener('click', ()=>{
current.innerText += button.innerText;
})
})
decimalBtn.addEventListener('click', ()=>{
addDecimal();
})
//when pressing an operator button, the current operand is moved to the previous operand //place
operationBtns.forEach(button =>{
button.addEventListener('click', ()=>{
if (operatorDisplay.innerText != "") {
operate();
}
else{
previous.innerText = current.innerText;
firstNumber = previous.innerText;
current.innerText = "";
operatorDisplay.innerText = button.innerText;
}
})
})
//calculates result based on chosen operator
equalsBtn.addEventListener('click', ()=>{
secondNumber = current.innerText;
operate();
//Display error message if user tries to divide by 0
if (secondNumber === "0" && operatorDisplay.innerText === "/") {
errorMessage();
}
//pressing equals button does nothing if either operand is empty
if (current.innerText != "" && previous.innerText != "") {
displayResult();
}
})
//deletes last number of the current operand on click
deleteBtn.addEventListener('click', ()=>{
current.innerText = current.innerText.slice(0, -1);
})
//displays result
function displayResult(){
clearOutput();
//rounds the result in case of a ridiculous number of decimals
current.innerText = Math.round(result * 10000) / 10000;
}
function operate(){
if (operatorDisplay.innerText === "+") {
result = parseFloat(firstNumber) + parseFloat(secondNumber);
}
if (operatorDisplay.innerText === "-") {
result = parseFloat(firstNumber) - parseFloat(secondNumber);
}
if (operatorDisplay.innerText === "*") {
result = parseFloat(firstNumber) * parseFloat(secondNumber);
}
if (operatorDisplay.innerText === "/") {
result = parseFloat(firstNumber) / parseFloat(secondNumber);
}
}
function errorMessage(){
clearOutput();
result = "Division by 0 impossible";
}
//adds decimal point
function addDecimal(){
if (!current.innerText.includes(".")) {
current.innerText += ".";
}
}

Related

The value is Incrementing instead of Decrementing in JavaScript?

I have a counter (up to 5) with Increment and Decrement Buttons the Thing is that When the maximum Limit of 5 is reached and I click the Decrement Button (minus Button) instead of going Down to 4 it goes up to 6 and After that it decrements Properly and this is the Same issue with the Increment Button.
So can anyone tell why this is happening and How to resolve it?
Any help is Highly Appreciated.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 1
function incre() {
if (value <= 5) {
let holder = value++
text.innerText = holder
let updatedEth = 0.25 * holder
addedAmount.innerText = updatedEth
} else {
alert('You can not take More than Five NFTs')
}
}
function decre() {
if (value >= 1) {
let holder = value--
text.innerText = holder
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
} else {
alert('you can not')
}
}
<div>
<button class="decrement" onclick="decre()">-</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">+</button>
</div>
<div>
<p><span class="added-amount"> 0.25 </span> eth</p>
</div>
You need to use the prefix operator to appear the result on click, also make the value as 0 in initialization otherwise the first value will be 2. you could remove the holder variable in this use case.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 0
function incre(){
if(value < 5){
text.innerText = ++value
let updatedEth = 0.25 * value
addedAmount.innerText = updatedEth
}else{
alert('You can not take More than Five NFTs')
}
}
function decre(){
if(value > 0){
text.innerText = --value
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
}else{
alert('you can not')
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button class="decrement" onclick="decre()">
-
</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">
+
</button>
</div>
<div>
<p> <span class="added-amount"> 0.25 </span> eth</p>
</div>
</body>
</html>
Instead of pre/post decrementing the value, you can simply do text.innerText = holder-1; and then decrease value by 1.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 1
function incre(){
if(value <= 5){
let holder = value++
text.innerText = holder
let updatedEth = 0.25 * holder
addedAmount.innerText = updatedEth
}else{
alert('You can not take More than Five NFTs')
}
}
function decre(){
if(value >= 1){
let holder = value;
text.innerText = holder-1;
value -= 1;
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
}else{
alert('you can not')
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<button class="decrement" onclick="decre()">
-
</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">
+
</button>
</div>
<div>
<p> <span class="added-amount"> 0.25 </span> eth</p>
</div>
</body>
</html>

Using PokeAPI to fetch data. Can't figure out why span element is not updating

So I'm using the PokeAPI to fetch the name of a Pokemon, then shuffling that name, and the user is supposed to guess what it is in the input. If they don't know then they can click the next button and it reshuffles a new mon. If they guess right they can press the same next button for a new mon. Each time they guess right the score increases by 1. That's working but I cant figure out why the out of/total games span isn't updating as well. Please excuse my terrible attempt at JS I'm very new if you can help me make my code look better that would be great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<title>Who's that Pkmn?</title>
</head>
<body>
<header>
<h1>Who's that Pokemon?!</h1>
</header>
<div id="jumble">?????</div>
<div class="container">
<input id="guess" type="text" placeholder="enter pkmn name" />
<button id="submit" class="btn" type="submit">go</button>
<button id="next" class="btn">next</button>
<p id="msg">unshuffle the letters</p>
</div>
<div id="scorekeepers">
<p>Score: <span id="score">0</span>
out of: <span id="gamesPlayed">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
let jumbledName = document.querySelector("#jumble");
let guessInput = document.querySelector('#guess')
let submitButton = document.querySelector('#submit')
let nextButton=document.querySelector('#next')
let messageDisplay = document.querySelector('#msg')
let score = document.querySelector('#score')
let gamesPlayed = document.querySelector('#gamesPlayed')
score = 0;
gamesPlayed = 0;
let getPokemonName = function() {
fetch(`https://pokeapi.co/api/v2/pokemon/${Math.floor(Math.random()*151+1)}/`)
.then(function(response) {
return response.json();
})
.then(function(data) {
const pokeName = data.name;
const pokeNameJumbled = pokeName.shuffle();
displayInfomation(pokeName, pokeNameJumbled);
});
};
getPokemonName();
guessInput.value=''
// pokeNameJumbled=''
const displayInfomation = function(name, jumbledName) {
pokeName = name;
pokeNameJumbled = jumbledName;
jumble.textContent = jumbledName;
};
const displayMessage = function(message) {
document.querySelector("#msg").textContent = message;
};
const checkName = function () {
document.querySelector("#guess").textContent = guessInput;
const guess = document.querySelector("#guess").value.toLowerCase();
if (!guess) {
displayMessage("No guess entered!");
} else if (guess === pokeName) {
displayMessage(`Thats correct! It's ${pokeName}!`)
score++
document.querySelector("#score").textContent = score;
guessInput.value=''
} else if (guess != pokeName) {
displayMessage(`Wrong!`);
document.querySelector("#gamesPlayed").textContent = gamesPlayed;
}
};
submitButton.addEventListener('click', checkName)
nextButton.addEventListener('click',getPokemonName)
String.prototype.shuffle = function() {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
};

'Bounce' in if else statement causing alert box to pop up more than once

I am designing a quiz that generates the question & answers dynamically each time, I have written an if-else statement to check if the answer is right but something isn't quite right. The increment score function doesn't work properly as random numbers are added and the alert box pops up more than once. It seems there is a bounce within the function but I can't figure out what it is.
// Game controls
const startButton = document.getElementById('start-button');
const quitButton = document.getElementById('quit-button');
const mainHeading = document.getElementById('main-heading');
const gameContainer = document.getElementById('game-container');
const scoreOutput = document.getElementById('score-total');
var questionCountOutput = document.getElementById('question-count');
let currentScore = 0;
let questionCount = 0;
startButton.addEventListener('click', startGame);
quitButton.addEventListener('click', quitGame);
const maxQuestions = 10;
const scoreValue = 20;
// Start game
function startGame(event) {
startButton.classList.add('hidden')
mainHeading.classList.add('hidden')
gameContainer.classList.remove('hidden')
questionCount = 0;
currentScore = 0;
generateQuestion()
};
// Quit Game
function quitGame(event) {
if (window.confirm('Are you sure you want to quit?')) {
gameContainer.classList.add('hidden')
startButton.classList.remove('hidden')
}
};
// Generates the questions
function generateQuestion() {
// Increment question count by 1 each time
questionCount++;
questionCountOutput.innerText = `${questionCount}`;
// variables to help generate question
let countriesCount = countriesList.length;
let randomNumber = getRandomInt(0, countriesCount);
let chosenCountry = (countriesList[randomNumber].country); // Generate random country from array
let correctAnswer = (countriesList[randomNumber].capital); // Generate the correct capital city from array
// Define correct answer
let isCorrectQuestionAnswer = {
question: chosenCountry,
option: correctAnswer
};
// Generate 3 random cities from capitalListOptions to act as other answer options
let answerOption1 = (countriesList[getRandomInt(0, countriesList.length)].capital);
let answerOption2 = (countriesList[getRandomInt(0, countriesList.length)].capital);
let answerOption3 = (countriesList[getRandomInt(0, countriesList.length)].capital);
// define option outputs to loop through
let optionOutputs = [{
'question': chosenCountry,
'option': correctAnswer
},
{
'question': chosenCountry,
'option': answerOption1
},
{
'question': chosenCountry,
'option': answerOption2
},
{
'question': chosenCountry,
'option': answerOption3
}
];
// Randomise the outputs so the correct answer isn't in the same place all the time
randomOptionOutputs = optionOutputs.sort(() => Math.random() - 0.5);
let buttonOutputs = '';
let i = 0;
// Loop through the options and retrieve their key values
//add key values to as button attributes
Object.keys(randomOptionOutputs).forEach(function(key) {
// Code to define the html for the buttons
buttonOutputs += '<button id="answer-' + i + '" data-answer="' + randomOptionOutputs[key]['option'] + '" data-country="' + randomOptionOutputs[key]['question'] + '" class="answer-btn" >' + randomOptionOutputs[key]['option'] + '</button>';
i++;
});
// Create the answer buttons and the questionText
document.getElementById('country-name').innerHTML = chosenCountry;
document.getElementById('answers-container').innerHTML = buttonOutputs;
// Loop through the buttons that have been created and add event listeners to them
for (let i = 0; i < 4; i++) {
document.getElementById("answer-" + i).addEventListener("click", function() {
checkAnswer(isCorrectQuestionAnswer)
});
};
};
// Generate random number to use as array index to generate questions and answers
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
};
// Checks if the answer selected is right, increments the score if it is, then moves on the to the next question
function checkAnswer(isCorrectQuestionAnswer) {
// Using a jquery method, retrieve the data-answer for the button clicked and compare this with the isCorrectQuestionAnswer object 'option'
$(document).on('click', '.answer-btn', function() {
var clickedButtonAnswer = $(this).data('answer');
// var clickedButtonQuestion = $(this).data('country');
if ((clickedButtonAnswer === isCorrectQuestionAnswer["option"])) {
$(this).addClass("correct");
incrementScore(scoreValue);
alert('Well done!!! You got that right');
generateQuestion();
return
} else {
$(this).addClass("incorrect");
alert("Ahhh that wasn't quite right - no worries, you'll get it next time!");
generateQuestion();
return
};
});
};
// function to increment the score with each new question
function incrementScore(num) {
currentScore += num;
scoreOutput.innerText = `${currentScore}`;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../assets/css/style.css">
<title>Around the World!</title>
</head>
<body>
<div class="navbar-container">
<nav class="navbar-top">
<ul>
<li>
Home
</li>
<li>
Rules
</li>
<li>
Play Game
</li>
<li>
High Scores
</li>
</ul>
</nav>
</div>
<div class="title-container">
<h1 id="main-heading">Let's Play</h1>
</div>
<div id="start-game" class="container">
<button id="start-button" class="btn">Start Game</button>
</div>
<div id="game-container" class="hidden">
<div id="progress-container">
<p class="progress">Question <span id="question-count"></span> of 10</p>
</div>
<div id="score-container">
<p class="progress">Score: <span id="score-total">0</span></p>
</div>
<div id="questions-container" class="container">
<h2 class="question">What is the capital city of <span id="country-name">country name</span>?</h2>
</div>
<div id="answers-container" class="container">
</div>
<div id="quit-game" class="container">
<button id="quit-button" class="btn">Quit Game</button>
</div>
</div>
<script src="../assets/js/script.js" defer></script>
<script src="../assets/js/quiz.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>

Javascript number game not showing output

I have been trying to make a game in Javascript where the browser generates 2 random numbers and an operand by clicking a button and the user has to type in the answer of the displayed calculation in an input area. If the answer is correct, the browser displays an alert saying that it is correct. Everything works fine, the numbers and operands are getting displayed, the user is able to type in his answer, but I am not getting any alert from the browser.
Here is the HTML and Javascript code (I haven't applied any style to it yet).
function displayOperation() {
let num1 = Math.floor(Math.random() * 100) + 1;
let num2 = Math.floor(Math.random() * 100) + 1;
let operandArr = ["+", "-", "*"];
let randomOperand = operandArr[Math.floor(Math.random() * operandArr.length)];
document.getElementById("number_one").innerHTML = num1;
document.getElementById("number_two").innerHTML = num2;
document.getElementById("operand_type").innerHTML = randomOperand;
switch (randomOperand) {
case "+":
add();
break;
case "-":
subtract();
break;
case "*":
multiply();
break;
}
function add() {
let res = num1 + num2;
let userAnswer = document.getElementById("text_Area").value;
document.getElementById("calculate").addEventListener("click", function () {
if (userAnswer === res) {
alert("correct!");
window.location.reload();
}
});
}
function subtract() {
let res = num1 - num2;
let userAnswer = document.getElementById("text_Area").value;
document.getElementById("calculate").addEventListener("click", function () {
if (userAnswer === res) {
alert("correct!");
window.location.reload();
}
});
}
function multiply() {
let res = num1 * num2;
let userAnswer = document.getElementById("text_Area").value;
document.getElementById("calculate").addEventListener("click", function () {
if (userAnswer === res) {
alert("correct!");
window.location.reload();
}
});
}
}
document.getElementById("reload").addEventListener("click", function () {
displayOperation();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="number_one">
</div>
<div id="operand_type">
</div>
<div id="number_two">
</div>
<div id="text_Area">
<label for="answer">
<input type="number" id="answer">
</label>
</div>
<div class="buttons">
<button type="button" id="calculate">Calculate</button>
<button type="button" id="reload">Load</button>
</div>
<div id="result">
</div>
<script src="index.js" charset="UTF-8"></script>
</body>
</html>
Some input would be appreciated.
Thank you!
You had multiple issues in your code. The input field for the answer has the id answer not text_Area. you were defining the functions for add, multiply and substract in the wrong scope. and you were using === for the check but .value returns a string and num1 + num2 (for example) returns a integer, so the check would always be wrong. If you have questions about my changes to your code, I'm happy to help.
var operandArr = ["+", "-", "*"];
var num1;
var num2;
var randomOperand;
function displayOperation() {
num1 = Math.floor(Math.random() * 100) + 1;
num2 = Math.floor(Math.random() * 100) + 1;
randomOperand = operandArr[Math.floor(Math.random() * operandArr.length)];
document.getElementById("number_one").innerHTML = num1;
document.getElementById("number_two").innerHTML = num2;
document.getElementById("operand_type").innerHTML = randomOperand;
}
document.getElementById("reload").addEventListener("click", function () {
displayOperation();
});
function calculate() {
switch (randomOperand) {
case "+":
add()
break;
case "-":
subtract()
break;
case "*":
multiply()
break;
}
}
function add() {
let res = num1 + num2;
let userAnswer = document.getElementById("answer").value;
if (parseInt(userAnswer) === res) {
alert("correct!");
window.location.reload();
}
}
function subtract() {
let res = num1 - num2;
let userAnswer = document.getElementById("answer").value;
if (parseInt(userAnswer) === res) {
alert("correct!");
window.location.reload();
}
}
function multiply() {
let res = num1 * num2;
let userAnswer = document.getElementById("answer").value;
if (parseInt(userAnswer) === res) {
alert("correct!");
window.location.reload();
}
}
document.getElementById("calculate").addEventListener("click", function () {
calculate();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="number_one">
</div>
<div id="operand_type">
</div>
<div id="number_two">
</div>
<div id="text_Area">
<label for="answer">
<input type="number" id="answer">
</label>
</div>
<div class="buttons">
<button type="button" id="calculate">Calculate</button>
<button type="button" id="reload">Load</button>
</div>
<div id="result">
</div>
<script src="index.js" charset="UTF-8"></script>
</body>
</html>
You can extract computation into another function and do required computation with Function()
function displayOperation() {
let num1 = Math.floor(Math.random() * 100) + 1;
let num2 = Math.floor(Math.random() * 100) + 1;
let operandArr = ["+", "-", "*"];
let randomOperand = operandArr[Math.floor(Math.random() * operandArr.length)];
document.getElementById("number_one").innerHTML = num1;
document.getElementById("number_two").innerHTML = num2;
document.getElementById("operand_type").innerHTML = randomOperand;
}
document.getElementById("calculate").addEventListener("click", function () {
let num1 = document.getElementById("number_one").innerHTML;
let num2 = document.getElementById("number_two").innerHTML;
let randomOperand = document.getElementById("operand_type").innerHTML;
let userAnswer = document.getElementById("answer").value;
let res = Function(`'use strict'; return (${num1 + randomOperand +num2})`)() ;
console.log(res)
if (parseInt(userAnswer) === res) {
alert("correct!");
window.location.reload();
} else {
console.log('huuu')
}
});
document.getElementById("reload").addEventListener("click", displayOperation);
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Number Game</title>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="number_one">
</div>
<div id="operand_type">
</div>
<div id="number_two">
</div>
<div id="text_Area">
<label for="answer">
<input type="number" id="answer">
</label>
</div>
<div class="buttons">
<button type="button" id="calculate">Calculate</button>
<button type="button" id="reload">Load</button>
</div>
<div id="result">
</div>
<script src="index.js" charset="UTF-8"></script>
</body>
</html>

2 players Javascript hangman game problem with prompt

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

Categories

Resources