JS get random value from array and update array - javascript

I need your help on this!
I'm generating an array which corresponds to a question number.
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
then I use this number to append the corresponding question, answer then click.
Then I'm getting a new value from the array like this
const randomQ = arrayCharge;
const random = Math.floor(Math.random() * randomQ.length);
It works and a new question is charged but the array is still the same.
I've tried this
var remQ = arrayCharge.indexOf(randomQ[random]);
arrayCharge.splice(remQ,1);
But It doesn't work ;-(
Thanks a lot for your help.
Nicolas
Here is the entire code to help comprehension! sorry for that, I should have done it from the begining.
<!DOCTYPE HTML>
<!--
Hyperspace by HTML5 UP
html5up.net | #ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>Repérez vos messages contraignants - Quiz</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript>
<link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Sidebar -->
<!-- <section id="sidebar">
</section> -->
<!-- Wrapper -->
<div id="wrapper">
<!-- Intro -->
<section id="intro" class="wrapper style1 fullscreen fade-up">
<div class="inner">
<header>
<button id="start">Commencer</button>
<p> </p>
</header>
<form action="" method="post">
<p id="Qnum"></p>
<p id="Q" data-qnumber="" data-type=""></p>
<section id="answer">
<input type="submit" id="1" name="R1" value="Non">
<input type="submit" id="2" name="R2" value="Parfois">
<input type="submit" id="3" name="R3" value="Souvent">
<input type="submit" id="4" name="R4" value="Oui">
</section>
</form>
</div>
</section>
<!-- Footer -->
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script>
$(document).ready(function() {
if (localStorage.getItem("clic") >= 45) {
console.log('45');
sessionStorage.clear();
localStorage.clear();
}
var Q1 = [1, "My first question", "FP"];
var Q2 = [2, "My second question", "SP"];
var Q3 = [3, "My third question", "SE"];
var Q4 = [4, "My foutrh question", "DP"];
var Q5 = [5, "My fifth question", "FP"];
//etc... until Q45
if (sessionStorage.getItem("FP") == null) {
$("form").attr("action", "driversV2.php");
$("#answer").hide();
$("#start").click(function() {
$("#Qnum").append(1+" / 45");
$("#Q").append(Q1[1]).attr("data-qnumber", Q1[0]).attr("data-type", Q1[2]);
$("#answer").show();
$("header").hide();
var pageType = $("#Q").attr("data-type");
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
localStorage.setItem("clic", 1);
});
});
} else {
$("header").hide();
var clicNum = parseInt(localStorage.getItem("clic"));
var QNumber = clicNum + 1;
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push(i);
}
const randomQ = arrayChargeNew;
const random = Math.floor(Math.random() * randomQ.length);
console.log('valeur random new = '+randomQ[random]);
var QCharge = "Q" + randomQ[random];
var Charge = eval(QCharge);
localStorage.setItem("random",randomQ[random]);
$("#Qnum").append(QNumber+" / 45");
$("#Q").append(Charge[1]).attr("data-qnumber", Charge[0]).attr("data-type", Charge[2]);
//création de la variable du type de question
var pageType = $("#Q").attr("data-type");
//alert(sessionStorage.getItem(pageType));
if (localStorage.getItem("clic") < 44) {
$("form").attr("action", "driversV2.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
} else {
$("form").attr("action", "driversResultat.php");
if (sessionStorage.getItem(pageType) != null) {
var x = parseInt(sessionStorage.getItem(pageType));
$("input").click(function() {
var reponse = parseInt(this.id);
var addition = reponse + x;
sessionStorage.setItem(pageType, addition);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
} else {
$("input").click(function() {
var reponse = this.id;
sessionStorage.setItem(pageType, reponse);
var clic = parseInt(localStorage.getItem("clic"));
localStorage.setItem("clic", clic + 1);
});
}
}
}
});
</script>
</body>
</html>

Nicolas, this is the sort of thing you should end up with:
// From my library js file
// returns a random number in the given range
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Variables for objects that need to be available throughout
let availableQuestions = [];
let rnd = 0;
let counter = 0;
// Populate the question array - how this is done depends on where the question data comes from
function createQuestions() {
availableQuestions.length = 0;
for (let i = 1; i <= 10; i++) {
availableQuestions.push({"questionnumber": i, "question": "Text for question " + i});
}
}
// Pick a random question and display that to the user
function getRandomQuestion() {
let osQuestions = availableQuestions.length;
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
// If there are no more questions, stop
if (osQuestions == 0) {
qnElement.innerHTML = "Finished!";
qElement.innerHTML = "";
sButton.style.display = "none";
rButton.style.display = "inline";
} else {
// display a sequential question number rather than the actual question number
counter++;
rnd = getRandomNumber(0, osQuestions - 1);
let thisQuestion = availableQuestions[rnd];
qnElement.innerHTML = "Question: " + counter + " (Actually question: " + thisQuestion.questionnumber + ")";
qElement.innerHTML = thisQuestion.question;
}
}
// Process the user's answer and remove the question from the array
function submitAnswer() {
// ALSO Add in what needs to be done to update backend database etc when the user clicks submit
availableQuestions.splice(rnd, 1);
getRandomQuestion();
}
// Reset everything - for testing purposes only
function restart() {
let qnElement = document.getElementById("questionnumber");
let qElement = document.getElementById("question");
let sButton = document.getElementById("submit");
let rButton = document.getElementById("restart");
qnElement.innerHTML = "";
qElement.innerHTML = "";
sButton.style.display = "inline";
rButton.style.display = "none";
// Reset the displayed question number counter
counter = 0;
createQuestions();
getRandomQuestion();
}
// Needed to populate the array and display the first question
function runsetup() {
createQuestions();
getRandomQuestion();
}
window.onload = runsetup;
<div id="questionnumber"></div>
<hr>
<div id="question"></div>
<button id="submit" onclick="submitAnswer();">Submit</button>
<button id="restart" onclick="restart();" style="display:none;">Restart</button>
I've included a counter variable so that the user does't see the actual question number - just 1, 2, 3 etc but I've shown the actual question number so that you can see it working

Nicolas, this is what I think you should be doing:
// Create the array in whatever way you need to
var arrayCharge = [];
for (var i = 2; i <= 45; i++) {
arrayCharge.push({"questionnumber": i, "question": "Text of question " + i});
}
// Just confirm the length of the array - should be 44
console.log(arrayCharge.length);
// Generate a random number based on the length of the array
var rnd = Math.floor(Math.random() * arrayCharge.length);
// Get the question at the randomly generated index number
let thisQuestion = arrayCharge[rnd];
// Check that we have a random question
console.log(thisQuestion.questionnumber);
console.log(thisQuestion.question)
// Present the question to the user on the page
// The user completes question and clicks "Submit"
// Now remove the question, using the SAME index number
arrayCharge.splice(rnd,1);
// Check that the array has lost an entry - the size should now be 43
console.log(arrayCharge.length);

Related

How to correct my wpm formula in JavaScript?

I am a learning student, Currently I am working on a typing website. I am using codingartist code as base. I have done some modification in this code. At the time variable I am taking value from user with the help of select option menu, so this is my time variable :
let time = parseInt(document.getElementById("time-select").value);
This is my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Typing Test</title>
<!-- Google Fonts -->
<link
href="https://fonts.googleapis.com/css2?family=Poppins:wght#400;600&display=swap"
rel="stylesheet"
/>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="select">
<label for="time-select">Select time:</label>
<select id="time-select">
<option value="60">1 minute</option>
<option value="90" selected>1.5 minutes</option>
<option value="120">2 minutes</option>
<option value="300">5 minutes</option>
<option value="480">8 minutes</option>
<option value="600" >10 minutes</option>
</select>
</div>
<div class="stats">
<p>Time: <span id="timer">0s</span></p>
<p>Mistakes: <span id="mistakes">0</span></p>
</div>
<div
id="quote"
onmousedown="return false"
onselectstart="return false"
></div>
<textarea
rows="3"
id="quote-input"
placeholder="Type here when the test starts.."
></textarea>
<button id="start-test" onclick="startTest()">Start Test</button>
<button id="stop-test" onclick="displayResult()">Stop Test</button>
<div class="result">
<h3>Result</h3>
<div class="wrapper">
<p>Accuracy: <span id="accuracy"></span></p>
<p>Speed: <span id="wpm"></span></p>
</div>
</div>
</div>
<!-- Script -->
<script src="script.js"></script>
</body>
</html>
This is my index.js
//Random Quotes Api URL
const quoteApiUrl = "https://api.quotable.io/random?minLength=80&maxLength=100";
const quoteSection = document.getElementById("quote");
const userInput = document.getElementById("quote-input");
let quote = "";
let time = parseInt(document.getElementById("time-select").value);
let timer = "";
let mistakes = 0;
function updateTime() {
// Get the new time value from the dropdown menu
let time = parseInt(document.getElementById("time-select").value);
// Update the timer display
document.getElementById("timer").innerText = time + "s";
}
// Add an event listener to the dropdown menu to call the updateTime function when the value changes
document.getElementById("time-select").addEventListener("change", updateTime);
//Display random quotes
const renderNewQuote = async () => {
//Fetch contents from url
const response = await fetch(quoteApiUrl);
//Store response
let data = await response.json();
//Access quote
quote = data.content;
//Array of characters in the quote
let arr = quote.split("").map((value) => {
//wrap the characters in a span tag
return "<span class='quote-chars'>" + value + "</span>";
});
//join array for displaying
quoteSection.innerHTML += arr.join("");
};
//Logic for comparing input words with quote
userInput.addEventListener("input", () => {
let quoteChars = document.querySelectorAll(".quote-chars");
//Create an arrat from received span tags
quoteChars = Array.from(quoteChars);
//array of user input characters
let userInputChars = userInput.value.split("");
//loop through each character in quote
quoteChars.forEach((char, index) => {
//Check if char(quote character) = userInputChars[index](input character)
if (char.innerText == userInputChars[index]) {
char.classList.add("success");
}
//If user hasn't entered anything or backspaced
else if (userInputChars[index] == null) {
//Remove class if any
if (char.classList.contains("success")) {
char.classList.remove("success");
} else {
char.classList.remove("fail");
}
}
//If user enter wrong character
else {
//Checks if we alreasy have added fail class
if (!char.classList.contains("fail")) {
//increment and display mistakes
mistakes += 1;
char.classList.add("fail");
}
document.getElementById("mistakes").innerText = mistakes;
}
//Returns true if all the characters are entered correctly
let check = quoteChars.every((element) => {
return element.classList.contains("success");
});
//End test if all characters are correct
if (check) {
displayResult();
}
});
});
//Update Timer on screen
function updateTimer() {
if (time == 0) {
//End test if timer reaches 0
displayResult();
} else {
document.getElementById("timer").innerText = --time + "s";
}
}
//Sets timer
const timeReduce = () => {
time = parseInt(time);
timer = setInterval(updateTimer, 1000);
};
//End Test
const displayResult = () => {
//display result div
document.querySelector(".result").style.display = "block";
clearInterval(timer);
document.getElementById("stop-test").style.display = "none";
userInput.disabled = true;
let timeTaken = 1;
if (time != 0) {
timeTaken = (60 - time) / 60;
}
document.getElementById("wpm").innerText =
(userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
document.getElementById("accuracy").innerText =
Math.round(
((userInput.value.length - mistakes) / userInput.value.length) * 100
) + " %";
};
//Start Test
const startTest = () => {
mistakes = 0;
timer = "";
userInput.disabled = false;
timeReduce();
document.getElementById("start-test").style.display = "none";
document.getElementById("stop-test").style.display = "block";
};
window.onload = () => {
userInput.value = "";
document.getElementById("start-test").style.display = "block";
document.getElementById("stop-test").style.display = "none";
userInput.disabled = true;
renderNewQuote();
};
I am trying to create a typing test that measures the words per minute (WPM) of the user's input. However, the WPM calculation is not giving the correct results. When I test the code, the WPM value is always much higher or as same as word typed (even if i take 2min. for typing) than expected.
let timeTaken = 1;
if (time != 0) {
timeTaken = (60 - time) / 60;
}
document.getElementById("wpm").innerText =
(userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
I know given code is wrong with 60 default value. so i tried this:
let remainTime = time - parseInt(timer);
let timeTaken = time - remainTime;
but it also gives doesn't give correct wpm value.
Try this I am sure that it will work as per my research:
let timerLengthInput = document.getElementById("time-select");
const timerLength = timerLengthInput.value;
let time = timerLength;
and write the in your displayResult-
let timeTaken = 1;
if (time !== 0) {
timeTaken = (timerLength - time) / 60;
}
document.getElementById("wpm").innerText =
(userInput.value.length / 5 / timeTaken).toFixed(2) + " wpm";
timeReduce function-
const timeReduce = () => {
timer = setInterval(updateTimer, 1000);
};

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>

Multiple progress bars visualy update only one

i'm working on my JavaScript skills and this is my first program trial here.
Everything was going quite well for me, but i'm stuck on this problem for about 3 days now and i guess there is something i don't get over here.
Well, diving in - i have 2 separate "Training Fields" - each has it's own "Train" button (onclick function) , "Level up" button (onclick function) and progress bar.
The problem is that the higher "Training Field" will progress the lower progress bar and not it's own.
Help will be appreciated! thx
//ignore this line, it's for me for testing
document.getElementById('hideMe').style.visibility = 'hidden';
/*========================================
Javascript for first set
========================================*/
var bodyTotal = 0;
var totalBodyCost = 0;
var bodyCost = 100;
var amountLoaded = 1;
function buyBody(){
bodyCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
if(amountLoaded >= bodyCost){
totalBodyCost += bodyCost;
bodyTotal = bodyTotal + 1;
document.getElementById('bodyTotal').innerHTML = bodyTotal;
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalBodyCost + Math.floor(100 * Math.pow(1.1,bodyTotal));
document.getElementById('bodyCost').innerHTML = nextCost;
document.getElementById("bodyProgressBar").max = nextCost;
bodyCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('bodyProgressBar');
var status = document.getElementById('bodyStatus');
status.innerHTML = al+"/" +bodyCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainBody(){
progressBarSim(amountLoaded);
if(amountLoaded < bodyCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('bodyFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
/*========================================
Javascript for second set
========================================*/
var mindTotal = 0;
var totalMindCost = 0;
var mindCost = 100;
var amountLoaded = 1;
function buyMind(){
mindCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
if(amountLoaded >= mindCost){
totalMindCost += mindCost;
mindTotal = mindTotal + 1;
document.getElementById('mindTotal').innerHTML = mindTotal;
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'hidden';
amountLoaded = 0;
};
var nextCost = totalMindCost + Math.floor(100 * Math.pow(1.1,mindTotal));
document.getElementById('mindCost').innerHTML = nextCost;
document.getElementById("mindProgressBar").max = nextCost;
mindCost = nextCost;
progressBarSim(amountLoaded);
};
function progressBarSim(al) {
var bar = document.getElementById('mindProgressBar');
var status = document.getElementById('mindStatus');
status.innerHTML = al+"/" +mindCost;
bar.value = al;
al++;
var sim = "progressBarSim("+al+")";
}
function trainMind(){
progressBarSim(amountLoaded);
if(amountLoaded < mindCost){
amountLoaded++;
}else{
var finalMessage = document.getElementById('mindFinalMessage').style.visibility = 'visible';
finalMessage.innerHTML = "";
}
};
/*=============================================*/
<html>
<head>
<link rel="stylesheet" type="text/css" href="interface.css" />
</head>
<body>
<div style="float:right">
Body Level: <span id="bodyTotal">0</span>
<button onclick="trainBody()">Train Body</button><br>
<progress id="bodyProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="bodyStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="bodyFinalMessage" style="float:left; visibility:hidden" onclick="buyBody()">Body Level Up</button>
<br><br>
Mind Level: <span id="mindTotal">0</span>
<button onclick="trainMind()">Train Mind</button><br>
<progress id="mindProgressBar" value="0" max="100" style="width:200px; float:left;"></progress>
<span id="mindStatus" style="float:left; z-index:555; margin-left:-110px;">0/100</span>
<button id="mindFinalMessage" style="float:left; visibility:hidden" onclick="buyMind()">Mind Level Up</button>
</div>
<div id="hideMe" style="position:absolute; top:400; left:400">
Body Cost: <span id="bodyCost">100</span><br>
Mind Cost: <span id="mindCost">100</span>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
You are reassigning variables and functions using the exact same names amountLoaded, progressBarSim(al).
Because body and mind behavior are very similar you could use a module pattern (http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) to use the same variable and function names within their own scopes.
<button onclick="Body.onClick()">Body</button>
<button onclick="Mind.onClick()">Mind</button>
And in your script file
var Body = (function() {
var me = {};
me.onClick = function() {
console.log("body click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
var Mind = (function() {
var me = {};
me.onClick = function() {
console.log("mind click");
progressBar(al);
};
function progressBar(al) {
}
return me;
})();
The gotcha here is you can't use body with the inline onclick since that already refers to the body element.

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