How to correct my wpm formula in JavaScript? - 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);
};

Related

'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>

JS get random value from array and update array

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);

CountUp Function failing to increment from 0 to inputted time

The details and code of this issue are as follows:
Problem:
The countUp function runs with no errors, but the UI displays the number inputted, and nothing before it.
Current Approach:
const countUp = () => {
let inputTime = document.getElementById("input").value; // 5
console.log(inputTime);
if (inputTime != 0) { // 5 != 0
document.getElementById("countupClock").innerHTML = 0;
let run = run => { // 5 > 0
let clock = document.getElementById("countupClock");
clock.value = clock.value < inputTime ? clock.value++ : inputTime;
clock.innerHTML = clock.value;
}
setInterval(run(), 3000);
} else {
clearInterval(run);
};
}
This is what I have so far for the actual CountUp function.
The Click Event is handled here:
// Begin Countup:
let btn = document.getElementById("enterTime");
btn.addEventListener("click", () => {
console.log("New Time Entered");
countUp();
});
Then this is the HTML:
<html>
<body>
<div class="controls">
<p id="countup">Countup</p>
</div>
<div class="center-controls">
<input type="number" id="input" placeholder="Enter a number">
</input>
</div>
<div class="right-controls">
<button id="enterTime">START</button>
</div>
</div>
</main>
<div class="clocksContainer">
<!-- Displays Time counting down -->
<span id="countupClock"></span>
<!-- A Field that allows you to enter a time to countup from -->
</div>
<script src="script.js"></script>
</body>
</html>
Expected Output:
The Number on the UI should increment from 0, to the users inputted number. In this case, 5.
The clock variable is a span element, it doesn't have value property. Simply doing clock.innerHTML++ will increment the displayed counter value. Also you should be saving the setInterval value and using it inside clearInterval.
const countUp = () => {
let interval;
let inputTime = document.getElementById('input').value; // 5
console.log(inputTime);
if (inputTime != 0) {
document.getElementById('countupClock').innerHTML = 0;
let run = () => {
let clock = document.getElementById('countupClock');
if (clock.innerHTML < inputTime) {
clock.innerHTML++;
console.log('Counter value:', clock.innerHTML);
} else {
clearInterval(interval);
console.log('Cleared interval');
}
};
interval = setInterval(run, 1000);
}
};

clearInterval is not stopping time consistenly

I'm creating a simple game of boggle that limits the user to 30 seconds. After that time, the game ends and the results are displayed. The problem is SOMETIMES everything works fine and the "timer" html shows Times Up. Other times, the countdown starts counting backward. My interval id variable is global and initially set to null. I'm not sure what's going on.
function words(x)
{
switch (x)
{
case 1:
var word = new Array("balte","table","hat","tab","belt","lab","eat","tea","ate","tale","bale","let","bet","teal","late","beat");
break;
case 2:
var word = new Array("atwre","water","wet","wear","tear","war","ret","rate","eat","ate","tea","awe","raw","rat","wart","art","tar");
break;
case 3:
var word = new Array("dclaen","can","cane","and","clan","lane","lean","lend","land","den","dean","dance","lance","clean","deal","ale","dale","candle","clad");
break;
case 4:
var word = new Array("aepinlar","air","airplane","plane","plan","lane","lean","pane","ear","near","nap","nape","lair","pen","pan","ape","leap","ale","peal","nap","rap","par", "pare", "pale", "are", "rail", "ail", "pail", "nail", "air", "pair", "ran", "pin", "pine", "line", "nip", "rip", "ripe", "lip", "earn", "learn", "ire");
break;
case 5:
var word = new Array("redykboa","keyboard","key","board","bored","bore","bark","dark","dork","oar","boar","ark","dare","bare","are","red","rod","road","bode","rode","ode","bread", "read", "bead", "bred", "break", "drey", "day", "boy", "broke", "rake", "bake", "ear", "dear", "bear", "dye", "dyer", "doer", "oak", "boa", "doe", "okay","dab", "bade", "ade", "drake", "bard", "yard", "year", "beak", "beard", "bad", "bed", "bay");
break;
case 6:
var word = new Array("evtsaedri","advertise","side","eat","sad","sat","rat","rate","vet","advise","read","rest","vest","serve","served","aside","east","tread","dear","deer","tear","trade","starve","steer","stare","veer","seat","seed","tree","drives","strive");
break;
case 7:
var word = new Array("rcseanbh","branches","bra","she","ran","bran","car","cab","race","ranch","share","bench","bar","char","can","crane","ban","hear","hare");
break;
case 8:
var word = new Array("vradntseue","adventures","vent","dent","stun","dust","rust","vase","sure","ensure","star","vend","dare","tar","starve","trade","sad","eat veer","tear","seat","seed","sand","tree","rest");
break;
case 9:
var word = new Array("wokcnalgede","acknowledge","and","land","wand","wage","ledge","led","lead","lend","leg","gown","know","now","no","lean","wean","week","wed","lack","leak","deal","deck","knew","kneel");
break;
case 10:
var word = new Array("muprith","triumph","hit","hurt","pit","trim","rum","rump","tip","thump","put","rim","him","hum","hip","rut");
break;
}
return word;
}
<html>
<head>
<title>Greg's Gambits | Greg's Game of Boggle</title>
<link href="greg.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="gregBoggle2.js"></script>
<script>
compWords = new Array(); notAword = new Array();
playWords = new Array();
var play = ""; /*var today;*/ var count = 30;
var score = 0; var interval = null;
var quit = false;
function start()
{
/*var start = new Date();
today = start.getTime();*/
timeIt();
boggle();
}
function displayLetters()
{
var num = Math.floor(Math.random()*10) +1;
compWords = words(num);
yourWord = compWords[0];
document.getElementById("letters").innerHTML = yourWord;
}
function timeIt()
{
interval = window.setInterval("countdown()",1000);
}
function countdown()
{
count--;
if (count == 0)
{
window.clearInterval(interval);
interval = null;
document.getElementById("timer").innerHTML = "Time's Up";
var btn =document.getElementById("start");
btn.disabled = true;
quit = true;
checkWin();
return;
}
document.getElementById("timer").innerHTML = count;
}
function boggle()
{
play = document.getElementById("words").value;
if (!quit)
{
playWords.push(play);
displayEntries();
document.getElementById("words").value = "";
document.getElementById("words").focus();
}
else
{
document.getElementById("words").value = "";
document.getElementById("words").focus();
checkWin();
}
}
function displayEntries()
{
document.getElementById("entries").innerHTML = playWords.toString();
}
/*function toMinutesAndSeconds(millis)
{
var minutes = Math.floor(millis/60000);
var seconds = ((millis%60000)/1000).toFixed(0);
return minutes + ":" + ((seconds < 10 ? '0' : "")+ seconds);
}*/
function checkWin()
{
// check winning score and list bad words
var complgth = compWords.length;
var playlgth = (playWords.length);
var flag; var timePlayed;
/*var endTime = new Date().getTime();
var diff = endTime - today;
timePlayed = toMinutesAndSeconds(diff);*/
for (var i = 0; i < playlgth; i++)
{
flag = 0;
for (var k = 0; k < complgth; k++)
{
if (playWords[i] == compWords[k])
{
score= score + 1;
flag = 1;
}
}
if (flag == 0)
notAword.push(playWords[i]);
}
document.getElementById("result").innerHTML = ("Your score is " +
score + ". The following entries " + "are not valid words: <br />" +
notAword.toString());
/*document.getElementById("timer").innerHTML = ("Your time: " + timePlayed);*/
}
</script>
</head>
<body>
<div id="container">
<img src="images/superhero.jpg" width="120" height="120" class="floatleft" />
<h1 align="center"><em>Greg's Game of Boggle</em></h1>
<div style = "clear:both;"></div>
<div id = "nav">
<p>Home
About
Play a Game
Sign In
Contact Us</p>
</div>
<div id="content">
<p>The object of the game is to create as many words as
you can. Please click the Display letters button and your letters will
be shown below. You have 10 possible letter combinations and 30 seconds. When you are ready to begin, enter the word then click the Submit Word button. The timer will start after first entered word.</p>
<p><input type="button" value="Display letters" onclick="displayLetters();" /><br/>
<input type="text" id="words">
<input type="button" id="start" value="Submit Word" onclick="start();" />
</p>
<h2><br /><br />Letters you can use:<br /><div id="letters"> </div><br /></h2>
<h2>Your words so far: <br /><div id="entries"> </div><br /></h2>
<h2>Results:<br /><div id="result"> </div></h2>
<h2>Timer: <br /><div id="timer"> </div></h2>
</div>
<div id="footer">Copyright © 2013 Greg's Gambits<br />
foulksy#gmail.com
</div>
</div>
</body>
</html>
Every time you submit a word, you call your start() function which calls timeIt(). Your solution works if you only submit one word, but if you submit multiple, you'll run into the issue where you see a negative timer.
I believe you have to clear the previous setInterval before creating a new one and storing it on your interval variable:
function timeIt()
{
window.clearInterval(interval);
interval = window.setInterval(countdown, 1000);
}
You should replace this line
interval = window.setInterval("countdown()",1000);
with the following
interval = window.setInterval(countdown, 1000);
You need to pass a function as the first parameter which can be called by the timer. You pass a string, which can't be called.
More information here.
Not sure if this is why it's failing, but setInterval takes a function as its first argument, not a string. It should be setInterval(countdown, 1000) not setInterval("countdown()", 1000).

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