How to reset variables to original, vanilla Javascript? - javascript

I'm making a simple hangman game in vanilla javascript and would like the game to reset after a player losses. Specifically, I'd like to:
1. reset the "guessRemain" variable
2. clear out the "guess" id, so none of the guessed letters are shown
3. choose another random word from the array.
Thanks in advance for your help!
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Hangman Game</title>
<link rel="stylesheet" type="text/css" href="assets\css\reset.css"/>
<link rel="stylesheet" type="text/css" href="assets\css\style.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
<script src="https://use.fontawesome.com/ca6de464ee.js"></script>
</head>
<body>
<div id="white">
<img src="assets\images\turkey.png" alt="turkey" class="turkeyImage">
</div>
<div id="orangebox">
<h4>thanksgiving</h4>
<h4 class="hangman">hangman</h4>
</div>
<div class="instructions">
<h1>Instructions:</h1>
<br/>
<h2>1. Guess a Thanksgiving dish!</h2>
<br/>
<h3>2. Press any key to begin.</h3>
</div>
<div class="display">
<p class="greywords">Current Word:</p>
<br/>
<p id="current"></p>
<br/>
<br/>
<p class ="greywords">Number of Guesses Remaining:</p>
<br/>
<p id="remain"></p>
<br>
<br/>
<p class="greywords">Letters Already Guessed:</p>
<p id="guess"></p>
<br>
<br/>
<p class="greywords">Wins:</p>
<p id="win"></p>
<br>
<br/>
<p class="greywords">Losses:</p>
<p id="loss"></p>
</div>
<!-- End of HTML -->
<script type="text/javascript">
// Step 2: create variable of the food words
var wins = 1;
var losses = 1;
var guessRemain = 10;
var foodWords = [
"pie",
"turkey",
"bacon",
"bread"
];
// Step 1: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
var randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
var count = [];
for (var i = 0; i < randomWord.length; i++) {
count[i] = "_ ";
}
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;
//Step 6: have it recognize that there are remaining letters
var remainingLetters = randomWord.length;
console.log("I HAVE " + remainingLetters + " left");
//Step 7: function for when they click a key
document.onkeyup=function(event) {
var userGuess = event.key;
document.getElementById("guess").innerHTML += userGuess + " ";
// console.log(randomWord.length);
if (randomWord.includes(userGuess)) {
// console.log("test");
// Step 7: if this statment is true, then modify the count variable, replace the dash in count with letter, and it has the correct position, and display the letter
var guessIndex = randomWord.indexOf(userGuess);
//console.log(randomWord.indexOf(userGuess));
count[guessIndex] = userGuess
//console.log(count);
document.getElementById("current").innerHTML = count;
remainingLetters--;
console.log("I HAVE " + remainingLetters + " left");
if (remainingLetters === 0) {
document.getElementById("win").innerHTML = wins++;
console.log("I have won");}
}
// Step 8: if not true, then subtract a guess
else {
document.getElementById("remain").innerHTML = guessRemain--;
document.getElementById("remain").innerHTML = guessRemain;
if (guessRemain === 0) {
document.getElementById("loss").innerHTML = losses++;
console.log("I have lost");
}
}
}
// Step 10: if there are no letters remaining in count, then add "1" to the win id and reset the page
// if (remainingLetters === 0) {
// document.getElementById("#win").innerHTML = winSs++;
// console.log("I have won");
//console.log("i win");
// function reset() {
// document.getElementById("display").reset();
// }
// }
// Step 11: if there are no guesses remaining, add a "1" to the loss id and reset the page
// if (remainingGuess < 0) {
// document.getElementById("#loss").innerHTML = ++1;
// function reset() {
// document.getElementById("display").reset();
// }
// }
</script>
</body>
<div class="footer">
</div>
</html>

Simply set the variable, so to "reset" guessRemain you'd just type
guessRemain = 10;
inside your reset function, The same would go for any other variables.
As for the Guesses already displayed on the web page, you'd do something similar to this
document.getElementById("guess").innerHTML = "";
Hope that helps :)

First off, clear the guess element somewhere in steps 1-6 by setting its innerHTML to an empty string. Take your steps 1-6 and put them in a function called initialize like so:
Edit: declare your variables wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters outside of the function below so that you'll have access to them in your onkeyup handler
var wins, losses, guessRemain, foodWords, randomWords, count, remainingLetters;
function initialize() {
// Step 1: create variable of the food words
wins = 1;
losses = 1;
guessRemain = 10;
foodWords = [
"pie",
"turkey",
"bacon",
"bread"
];
// Clear the guess
document.getElementById("guess").innerHTML = "";
// Step 2: display remaining gueses
document.getElementById("remain").innerHTML = guessRemain;
// Step 3: create a variable to pick a random word from that array
randomWord = foodWords[Math.floor(Math.random() * foodWords.length)];
console.log(randomWord);
//Step 4: make it count the number of letters in that word that you just picked
count = [];
for (var i = 0; i < randomWord.length; i++) {
count[i] = "_ ";
}
//Step 5: write the var on the screen
document.getElementById("current").innerHTML = count;
//Step 6: have it recognize that there are remaining letters
remainingLetters = randomWord.length;
console.log("I HAVE " + remainingLetters + " left");
}
Call the function initialize() somewhere in your code (outside of the onkeyup handler) to initialize your game for the first time.
Now, you can reuse the initialize function whenever you want to reset your game. For example, you can do something like this when the game is over (place this code inside your onkeyup handler towards the bottom):
if (remainingLetters === 0 || remainingGuess === 0) {
inititalize();
}

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>

Can someone explain this function/argument?

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

How to push score into an array, then display it

I'm trying to make a dice game where the goal for each of participants is to collect points as fast as possible to pass 100. Each participant can throw the die as many times as they want and add the points, but achieved points within a certain game fall away if a one is rolled. For example, if you have 15 points in a game and have stopped in time, these points can be taken further to round two. These points cannot be lost in a later round and thus become included in the summary.
I've managed to:
write the code that shows images of dice and sums up the current score (images = 1.png, 2.png etc).
Resets the current score to 0 when the player rolls a one.
What I need help with is how to write the code that activates the button "done for now" and takes that value and pushes it into an array(????) then clears the score for the next round -> then displaying the score on the site while the other rounds keep on going. It should also sum up the score and throws from each round (first to 100).
Here is my code:
var points = 0;
var start, dice, print;
window.onload = run;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button>Done for now</button>
<div id="dice" class="dice"></div>
<h2 id="print"></h2>
<p id="print2"></p>
</div>
Basically you just have to add another click event listener to the 'Done for now' button whose callback function
pushes the current points to an array
resets the points to 0
updates the text elements on screen
Something like:
var points = 0;
var pointsArray = new Array();
var start, dice, print;
function $(id) {
return document.getElementById(id);
}
function run() {
start = $("throwDice");
dice = $("dice");
print = $("print");
start.onclick = throwDice;
done = $("done");
done.onclick = stopRound;
}
function stopRound() {
pointsArray.push(points);
points = 0;
$("print").innerHTML = points;
$("print3").innerHTML = pointsArray;
}
function throwDice() {
var throwD = Math.floor(Math.random() * 6) + 1;
throwD.innerHTML = '<img width="20%" src="' + throwD + '.jpg">';
add(throwD);
}
function add(value) {
points += value;
if (value == 1) {
points = 0;
$("print2").innerHTML = "GAME OVER"
} else {
$("print2").innerHTML = "";
$("print").innerHTML = points;
}
}
run();
<div class="round">
<h1>The endless road</h1>
<button id="throwDice">Throw Dice</button> <button id="done">Done for now</button>
<div id="dice" class="dice"></div>
<p id="print3" style="float:right;"></p>
<h2 id="print"></h2>
<p id="print2"></p>
</div>

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

JavaScript/HTML: find longest word and compare to current word

I'm writing a code that :
Allow my user to type in a sentence.
Find the longest word in that sentence.
Compare that longest one to every word in the sentence.
The words of the string directly out to a webpage, laid out so that no
single line is longer than the longest word in the string.
I've been working this code for two days and feel like completely lost in somewhere. Please advise me to improve my code.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Wrap Text </title>
<script>
//Determine Longest word and compare to currend word
function longWord(string){
var lengthOfString = 0;
var arrayOfText = string.split(" ");
for ( i = 0; i < arrayOfText.length; i++){
if (arrayOfText[i].length > lengthofString){
lengthOfString = arrayOfText[i].length;
}
}
return lengthOfString;
}
// Longest vs current word
function layoutString(string, length){
var x = 0;
var testLength = 0;
var testLength = arrayOfText[i].length;
do {
testLength + 1 + arrayOfText[i].length
} while (testLength > longWord);
}
//Call this function in HTML
function wrapText(string) {
var length = longWord(string);
layoutString(string, length);
document.getElementById("demo").innerHTML += arrayOfText + "<br>";
}
</script>
</head>
<body>
<h3>Let's Wrap your text!</h3>
<!--User Input Section-->
<p>Enter Text: <input id="yourValue" value=""></p>
<p id="demo"></p>
<!--Button executing function-->
<button onclick="wrapText(yourValue.value)">Wrap Text</button>
</body>
</html>
Some issues:
arrayOfText is not accessible in layoutString and wrapText as it is a locale variable of longWord
In layoutString you use longWord (the function name) instead of the parameter length.
The line "testLength + 1 + arrayOfText[i].length" has no effect, it just adds the three values together but does not assign it to anything.
layoutString generally does nothing ...
I'm not sure about your 4th requirement as all words' length will be less or equal than the longest word's length, so I add hyphens in front of all shorter words so they are all the same length. Maybe that gets you closer to your final goal.
Try this:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Wrap Text </title>
<script>
//Determine Longest word and compare to current word
function longWord(string){
var lengthOfString = 0;
var arrayOfText = string.split(" ");
for (var i = 0; i < arrayOfText.length; i++){
if (arrayOfText[i].length > lengthOfString){
lengthOfString = arrayOfText[i].length;
}
}
return lengthOfString;
}
// Longest vs current word
function layoutString(string, length){
var arrayOfText = string.split(" ");
for (var i = 0; i < arrayOfText.length; i++){
while (arrayOfText[i].length < length) {
arrayOfText[i] = '-' + arrayOfText[i];
};
}
return arrayOfText;
}
//Call this function in HTML
function wrapText(string) {
var longestWordLength = longWord(string),
strings = layoutString(string, longestWordLength),
demo = document.getElementById("demo");
demo.innerHTML = '';
for (var i = 0; i < strings.length; i++){
demo.innerHTML += strings[i] + "<br>";
}
}
</script>
</head>
<body>
<h3>Let's Wrap your text!</h3>
<!--User Input Section-->
<p>Enter Text: <input id="yourValue" value=""></p>
<p id="demo"></p>
<!--Button executing function-->
<button onclick="wrapText(yourValue.value)">Wrap Text</button>
</body>
</html>

Categories

Resources