How to build a string with a loop? - javascript

var game = prompt('Do you want to play?');
var i = 0;
do {
if (prompt === 'Yes');
{
var game2 = prompt('Enter your word.');
var game3 = prompt('Do you want to play again?');
}
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
console.log("You're words are: " + game2);
How do I take all the words outputted from this loop and build a string with it?
Ex: if all my words are "basketball, football, racing"
I want them to come out outputted like --> basketball football racing

Hope this helps...
var game = prompt('Do you want to play?');
var game2 = '';
var space = ' ';
var i = 0;
do {
if (prompt === 'Yes');
{
game2 = game2 + space + prompt('Enter your word.');
var game3 = prompt('Do you want to play again?');
}
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
prompt("You're words are: " + game2);

It looks like you have a few things wrong with your code. You could use the .join method if you put all of the responses into an array.
var game = prompt('Do you want to play?');
var i = 0;
var words = [];
do {
// if (prompt === 'Yes'); // this isn't doing anything
// {
words.push(prompt('Enter your word.'));
var game3 = prompt('Do you want to play again?');
// }
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
console.log("You're words are: " + words.join(' '));

To what i understood from your question, This should Work.
var game = prompt('Do you want to play?');
var i = 0;
var game2="";
do {
if (prompt === 'Yes');
{
game2 += " "+prompt('Enter your word.');
var game3 = prompt('Do you want to play again?');
}
i++;
} while (game3 !== 'No');
console.log(game3);
console.log("You're words are: " + game2);
Basically, you are just concatenating dynamically.

Try this one
var words = [];
var i = 0;
do {
var game = prompt('Do you want to play' + ((words && words.length) ? ' again' : '') + '? (type yes to continue else exit)');
if(game && game.toLowerCase() === 'yes') {
var word = prompt('Enter your word.');
if(word) {
words.push(word);
}
}
} while (game && game.toLowerCase() === 'yes');
if(words && words.length) {
console.log("You're words are: " + words.join(', '));
} else {
console.log("no words selected!");
}

You can go with String Array:
var gameArr =[];
gameArr.push(prompt('Do you want to play?'));
var i = 0;
do {
if (prompt === 'Yes');
{
gameArr.push(prompt('Enter your word.')); // This will append new string in current string.
gameArr.push(prompt('Do you want to play again?'));// this also append the new string.
}
i++;
} while (game3 !== 'No');
{
console.log(game3);
}
console.log("Your words are: " + gameArr[1]);
Let me know if you are unsure how you will get your responses from the array gameArr[].

Related

Finding the number of words without split() or heavy regex

Ive been struggling with this a bit and haven't found anything good on the website. I'm trying to find the number of words in a textarea without split() (cuz it counts whitespaces and miscounts words in some situations) this is what i've tried :
text.addEventListener('input', () => {
let wordCounter = 0;
let sentenceCounter = 0;
let charCounter = text.value.split('').length;
let flag = false;
let flag2 = false;
if(text.value === ' ' || text.value === ''){
wordCounter = 0;
}
for(let z = 0; z < text.value.length; ++z){
if(text.value[z] == '.' && flag == false){
sentenceCounter++;
flag = true;
}
if((/\w/).test(text.value[z])){
flag = false;
}
}
for(let z = 0; z < text.value.length; ++z){
if(text.value[z] == " " && flag2 == false){
wordCounter++;
flag2 = true;
}
if((/\w/.test(text.value[z]))){
flag2 = false;
}
}
sentences.innerHTML = `${sentenceCounter} : Sentences`
char.innerHTML = `${charCounter} : Characters`
words.innerHTML = `${wordCounter} : Words`
});
the problem here is that it counts words only if press space so that means "fa" is not counted as a word but "fa " is. Thanks in advance for your help!
You need to increase the counter when you find a letter, instead of when you find a space. You can also count words and sentences on the same loop. To finish a word, had to change from comparing to " " to \W.
let sentenceCounter = 0, sentenceFinished = false,
wordCounter = 0, wordFinished = true,
input = "Test text. Test.";
for (let z = 0; z < input.length; ++z) {
var letter = input[z];
if (!sentenceFinished && letter == ".") {
sentenceCounter++;
sentenceFinished = true;
}
if (sentenceFinished && /\w/.test(letter)) {
sentenceFinished = false;
}
if (!wordFinished && /\W/.test(letter)) {
wordFinished = true;
}
if (wordFinished && /\w/.test(letter)) {
wordCounter++;
wordFinished = false;
}
}
console.log(`Words: ${wordCounter}, Sentences: ${sentenceCounter}`);

Javascript array push issue or loop issue

When I'm running my code I'm going into 'do' loop, then I'm entering input 'new' and then trying to add new array, but for some reason my code starting looping in if(answ == "new"). What am I doing wrong?
Here is my code:
var answ;
var arr = [];
do{
answ = prompt("What would like to do?");
if(answ == "new"){
var add = prompt("Add new todo: ");
add = arr.push(answ);
}
else if(answ == "list"){
for(var i=0; i<arr.length; ++i){
answ = answ + arr[i] + '<br>';
}
}
else if(answ == "delete"){
var choose = prompt("Which one (index)?");
delete arr[choose];
}
}while(answ !== "quit")
Don't run in browser in current form (never ending loop)
See if this helps you Mark.
there were some errors with you logic and storing values and also you were not showing the values, if what I suggest is right.
var answ;
var arr = [];
do {
answ = prompt("What would like to do?");
if (answ == "new") {
var add = prompt("Add new todo: ");
arr.push(add);
} else if (answ == "list") {
var output = '';
for (var i = 0; i < arr.length; ++i) {
output += arr[i] + '\r\n';
}
alert('listing:' + '\r\n' + output );
} else if (answ == "delete") {
var choose = prompt("Which one (index)?");
arr.splice(choose,1);
} else {
if(answ !== "quit")
alert('option invalid!');
}
} while (answ !== "quit")

Make previous selected word go away on html and replace with new word in Hangman game for javascript

I am currently making a hangman game with javascript and I am struggling with how to remove and replace the previously selected word, with a new word. Currently I ahve my code set up so that when the player guesses the word correctly, a message pops up and asks the user if they want to play again. If they press Y, I call the function that randomly selects a word from and array and also uses the push method to fill and empty array with blank lines the same length of the chosen word. But when I call this function after Y has been pressed, the previous word doesnt go away and key presses also do not register.
var hangmanObject = {
randomWords: ['rock','paper','modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction()
{
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}
function displayChosenWord()
{
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random()*hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
document.onkeyup = function(event)
{
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
for (x = 0; x < hangmanObject.chosenWord.length; x++)
{
if (hangmanObject.chosenWord.charAt(x) === userGuess)
{
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1)
{
hangmanObject.numWins++;
// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event)
{
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y')
{
hangmanObject.numLives = 10;
displayChosenWord();
}
}
}
if (hangmanObject.numLives <= 0)
{
document.getElementById("lose").innerHTML = "You Lose";
}
}
You are setting the document.onkeyup callback inside the callback, effectively disabling it for letter guesses.
Also, the empty array is never emptied so the next word is appended to the empty letters array from the previous word. Here's a simpler approach, by using a gameState flag, you can decide whether the user is entering letters to guess, or they are deciding to play again. Also, a single div for status can be used ;)
var hangmanObject = {
gameState: 'playing',
randomWords: [
'rock',
'paper',
'modular synthesizer',
'led zeppelin'
],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction() {
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
chooseNewWord();
}
function chooseNewWord() {
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
// Reset guesses and misses
hangmanObject.empty = [];
hangmanObject.incorrect = [];
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push("_");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}
document.onkeyup = function(event) {
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
// Game status is "playing"
if (hangmanObject.gameState === 'playing') {
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === userGuess) {
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join(" ");
}
}
// checking to see if wrong letter chosen
if (hangmanObject.splitArray.indexOf(userGuess) === -1) {
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect.join(",");
}
// Some debug
console.log(hangmanObject.empty);
// WIN situation
if (hangmanObject.empty.indexOf("_") === -1) {
hangmanObject.numWins++;
// Set status message and game state
document.getElementById("status").innerHTML = "You won " + hangmanObject.numWins + " times";
hangmanObject.gameState = 'finished';
}
// LOSE situation
if (hangmanObject.numLives <= 0) {
// Set status message and game state
document.getElementById("status").innerHTML = "You Lose";
hangmanObject.gameState = 'finished';
}
// Set message if game finished
if (hangmanObject.gameState === 'finished') {
document.getElementById("Play").innerHTML = "Play Again? Y/N";
}
// Game status is "finished"
} else {
// If user selects play again
if (userGuess === 'y') {
// Set status back to "playing"
hangmanObject.gameState = 'playing';
// Reset lives and messages
hangmanObject.numLives = 10;
document.getElementById("status").innerHTML = "";
document.getElementById("LettersGuessed").innerHTML = "";
document.getElementById("Play").innerHTML = "";
// Choose new word
chooseNewWord();
} else {
// Set message
document.getElementById("status").innerHTML = "Goodbye!";
// Disable key handler
document.onkeyup = null;
}
}
}
startFunction();
<div id="numLives"></div>
<div id="blanks"></div>
<div id="LettersGuessed"></div>
<div id="status"></div>
<div id="Play"></div>
words joining - You need to clear the array.
no keyup - you replaced it with the 'y/n' keyup, you need to reset it.
also worth clearing the wrong letters and lives too on a new game.
see working example below:-
var hangmanObject = {
randomWords: ['rock', 'paper', 'modular synthesizer', 'led zeppelin'],
chosenWord: "",
numWins: 0,
numLives: 10,
empty: [],
incorrect: [],
splitArray: []
}
function startFunction() {
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
displayChosenWord();
}
function displayChosenWord() {
hangmanObject.empty = []; // empty the array
hangmanObject.incorrect = [];
hangmanObject.chosenWord = hangmanObject.randomWords[Math.floor(Math.random() * hangmanObject.randomWords.length)]
hangmanObject.splitArray = hangmanObject.chosenWord.split("");
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === " ")
hangmanObject.empty.push(" ");
else
hangmanObject.empty.push(" _ ");
}
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
document.getElementById("LettersGuessed").innerHTML = '';
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
document.onkeyup = gameKeyUp;
}
function gameKeyUp(event) {
var userGuess = String.fromCharCode(event.keyCode).toLowerCase();
for (x = 0; x < hangmanObject.chosenWord.length; x++) {
if (hangmanObject.chosenWord.charAt(x) === userGuess) {
hangmanObject.empty[x] = userGuess;
document.getElementById("blanks").innerHTML = hangmanObject.empty.join("");
}
}
if (hangmanObject.splitArray.indexOf(userGuess) === -1) //checking to see if wrong letter chosen
{
hangmanObject.numLives--;
document.getElementById("numLives").innerHTML = hangmanObject.numLives;
hangmanObject.incorrect.push(userGuess);
document.getElementById("LettersGuessed").innerHTML = hangmanObject.incorrect;
}
console.log(hangmanObject.empty);
if (hangmanObject.empty.indexOf(" _ ") === -1) {
hangmanObject.numWins++;
// console.log("i won");
document.getElementById("wins").innerHTML = hangmanObject.numWins;
document.getElementById("Play").innerHTML = "Play Again? Y/N";
document.onkeyup = function(event) {
// Determines which exact key was selected. Make it lowercase
var Choice = String.fromCharCode(event.keyCode).toLowerCase();
if (Choice === 'y') {
hangmanObject.numLives = 10;
displayChosenWord();
}
}
}
if (hangmanObject.numLives <= 0) {
document.getElementById("lose").innerHTML = "You Lose";
}
}
displayChosenWord();
document.onkeyup = gameKeyUp;
<div id="numLives"></div>
<div id="blanks"></div>
<div id="LettersGuessed"></div>
<div id="wins"></div>
<div id="Play"></div>
<div id="lose"></div>

I am writing a hangman program in java script and need help getting the word to display if the player loosed

Here is the javascript code:
I need help getting the word to display after the player looses.
var can_play = true;
//this is the array of words
var words = new Array("VALIDATE", "DESIGN", "INPUT", "ARRAY", "OBJECT", "DOCUMENTATION", "JQUERY", "CALCULATE", "ABSOLUTE", "DREAMWEAVER", "BROWSER", "HTML", "CONCATINATION");
var display_word = "";
var used_letters = "";
var wrong_guesses = 0;
//this will allow the letters to be entered in only 1 time
function selectLetter(l) {
if (can_play == false) {
return;
}
if (used_letters.indexOf(l) != -1) {
return;
}
used_letters += l;
document.game.usedLetters.value = used_letters;
if (to_guess.indexOf(l) != -1) {
// this will display the correct letter guesses
pos = 0;
temp_mask = display_word;
while (to_guess.indexOf(l, pos) != -1) {
pos = to_guess.indexOf(l, pos);
end = pos + 1;
start_text = temp_mask.substring(0, pos);
end_text = temp_mask.substring(end, temp_mask.length);
temp_mask = start_text + l + end_text;
pos = end;
}
display_word = temp_mask;
document.game.displayWord.value = display_word;
if (display_word.indexOf("*") == -1) {
// this will display a message if you win
$('#win').html("Well done, you won!");
can_play = false;
}
} else {
// this will display the incorrect letter guesses
wrong_guesses += 1;
$('#wrong_guesses').html(wrong_guesses);
if (wrong_guesses == 6) {
// this will display a message if you loose
$('#win').html("Sorry, you have lost!");
can_play = false;
}
}
}
//this will reset the game to play again
function reset() {
selectWord();
document.game.usedLetters.value = "";
guessed_letters = "";
wrong_guesses = 0;
$('#win').html("");
$('#wrong_guesses').html("");
}
//this will have the computer select a word from my array
function selectWord() {
can_play = true;
random_number = Math.round(Math.random() * (words.length - 1));
to_guess = words[random_number];
// this will display mask
masked_word = createMask(to_guess);
document.game.displayWord.value = masked_word;
display_word = masked_word;
}
function createMask(m) {
mask = "";
word_length = m.length;
for (i = 0; i < word_length; i++) {
mask += "*";
}
return mask;
}
$('#win').html("Sorry, you have lost, the word was " + to_guess + "!");
You assigned the to be guessed word here:
to_guess = words[random_number];
You would learn much from posting your code to Code Review.

Trying to add and remove items from an array

The script works by asking user for add or remove an item in the array. Then asks to continue this loop. The problem here is that my script doesn't seem to match my user's input (removeItem) to the item in the list (myList[i]). I'm at a lost as to why this is failing to match.
// new method for removing specific items from a list
Array.prototype.remove = function(from,to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
printList = function() {
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
document.write(i + ":");
document.write(myList[i] + "<br/>");
};
document.write("<br/><br/>");
};
// initial list
var myList = new Array ();
if (myList.length === 0) {
document.write("I have " + myList.length + " item in my list. It is: <br/>");
}
else {
document.write("I have " + myList.length + " items in my list. They are: <br/>");
}
printList();
var continueAdding = "yes";
var askToContinue = "";
while (continueAdding === "yes") {
// loop
var askUser = prompt("What do you want to [A]dd or [R]emove an item to your inventory?").toUpperCase();
switch (askUser) {
case "A": { // add an user specified item to the list
var addItem = prompt("Add something to the list");
myList.push(addItem);
printList();
break;
}
case "R": { // remove an user specified item from the list
var removeItem = prompt("what do you want to remove?");
var listLength = myList.length;
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
break;
}
if (myList.length === 0) {
myList[0] = "Nada";
}
};
printList();
break;
}
default: {
document.write("That is not a proper choice.");
}
};
askToContinue = prompt("Do you wish to continue? [Y]es or [N]o?").toUpperCase(); // ask to continue
if (askToContinue === "Y") {
continueAdding = "yes";
}
else {
continueAdding = "no";
}
}
Your loop never allows it to loop through all the items, because it breaks on the first iteration if the item doesn't match.
The break statement should be in the if block, not in the else block - use this instead:
for (i = 0; i < listLength; i++) {
if (removeItem === myList[i]) {
document.write("I found your " + removeItem + " and removed it.<br/>");
myList.remove(i);
break;
}
else {
document.write(removeItem + " does not exist in this list.<br/>");
}
};
if (myList.length === 0) {
myList[0] = "Nada";
}
Also, note that it's looking for an exact match, case sensitive, same punctuation, and everything. If you want it to be a little more lenient you'll need to modify the script to convert both strings to lowercase and strip punctuation before comparing them.
Edit: Just noticed something else -- testing for an empty list needs to be done outside the loop. I updated the above code to reflect this.

Categories