Random Fruit guessing Game - javascript

I'm in my second week of Javascript and the task we've been given is to create a guessing game.
The steps we've been given are:
Prepare a list of your favourite fruits and store it in an appropriate data structure and have the computer select a random fruit as the secret word.
Base on the selected fruit give the use a hint like the example below. you can use prompt, alert or console.log to show the hint
for example if the secret fruit is "banana"
hint: it's 6 characters long. Starts with b and ends with a. guess the fruit.
instead of typing out the hint manually for every fruit. try to use a template string and programmatically work out the starting letter, ending letter and how many characters long.
Allow the user to guess the fruit repeatedly until they guess correctly. keep track of the number of guesses.
Congratulate the user and display number of attempts they made.
I've been sitting on this for awhile and have tried shifting my code around. I know I'm close but would love some pointers or tips.
This is what I have so far:
var fruits = ["kiwi", "banana", "apple", "strawberry", "watermelon", "orange"];
var ranNum = Math.floor(Math.random() * fruits.length);
var secretFruit = fruits[ranNum];
var userPrompt = prompt("Guess the fruit");
var guess = 1;
while (userPrompt !== secretFruit) {
prompt(
"hint: it's " +
secretFruit.length +
" characters long. Starts with " +
secretFruit[0] +
" and ends with " +
secretFruit.slice(-1) +
". guess the fruit."
);
guess++;
}
if (userPrompt == secretFruit) {
alert(
"Congratulations you guessed the fruit, and it took you " +
guess +
" guesses"
);
}
Any help would be great, thank you.

Two things wrong: your while loop and hint prompt.
First of all, your while loop will continuously keep prompting without ever checking whether the answer was correct, because you have left the if statement outside of the loop.
Also, the if statement should be before the hint statement otherwise the person will always have to try again even if they got the answer correct.
Secondly, your hint prompt is never actually recorded. This means that despite getting the answer correct, the code never actually records it.
Also, I suggest adding a break statement so that the game ends.
This is a working version of your code:
var fruits = ["kiwi", "banana", "apple", "strawberry", "watermelon", "orange"];
var ranNum = Math.floor(Math.random() * fruits.length);
var secretFruit = fruits[ranNum];
var userPrompt = prompt("Guess the fruit");
var guess = 1;
while (userPrompt !== secretFruit) {
if (userPrompt == secretFruit) {
alert(
"Congratulations you guessed the fruit, and it took you " +
guess +
" guesses"
);break; //break statement here stops infinite loop when correct
}
userPrompt = prompt(
"hint: it's " +
secretFruit.length +
" characters long. Starts with " +
secretFruit[0] +
" and ends with " +
secretFruit.slice(-1) +
". guess the fruit."
);
guess++;
}

Related

How can I get a true random from an array? Or should I do something else entirely?

I would like to display a different madlib each time a user clicks the submit button. Only needs to be clicked 3 times. I am using the functions below, but it doesn't seem all that random. I also have a snippet of the dogLib function that creates three madlibs and then calls the function above it to generate a random madlib string.
//Class: madlibGenerator.js
//----- Private Helper Functions -----
//Get Random: word strings for randam madlib
//Get Random: madlib string to display
function getRandomString(array) {
for(var i = array.length - 1; i>0; i--){
var j = Math.floor(Math.random() * (i+1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return this.word = array.pop();
}
//Set: set user input word string arrays into the getRandomString(array)
//Get: a final array of words to add to the madLib display strings
function getFinalWordArray(){
var prpN = getRandomString(this.properNouns);
var adjt = getRandomString(this.adjectives);
var noun = getRandomString(this.nouns);
var vrb = getRandomString(this.verbs);
return finalWordArray = [prpN, adjt, noun, vrb];
}
//Get Random Dog Lib
function getDogLib() {
//Get Random Dog Words
var dogWordsArray = getFinalWordArray();
//DogLibs
var dogLibOne =
"What is that " + dogWordsArray[1] +
" sound!" +
" Hey! " + dogWordsArray[0] +
"! You come " + dogWordsArray[3] +
" you crazy " + dogWordsArray[2] +
"!";
var dogLibTwo =
dogWordsArray[0] + "!! " +
dogWordsArray[0] + "!! " +
"Come " + dogWordsArray[3] +
" and lay on my clean " + dogWordsArray[2] +
" while your treat is still " + dogWordsArray[1] + "!";
var dogLibThree =
"My human comes home and takes me for a " + dogWordsArray[3] +
" where I sit on a " + dogWordsArray[2] +
" and get my " + dogWordsArray[1] +
" belly rubbed!";
//Make array of DogLibs
var dogLibArray = [dogLibOne, dogLibTwo, dogLibThree];
//Pick random dogLib string to display
finalDogLib = getRandomString(dogLibArray);
}
//Display: Random MadLib to console for now
function displayMadlib(pDisplayIDValue) {
if(pDisplayIDValue == "dogLib"){
//display
getDogLib();
console.log(finalDogLib);
}else if(pDisplayIDValue == "loveLib"){
//display
getLoveLib();
console.log(finalLoveLib);
}else if(pDisplayIDValue == "funnyLib"){
//display
getFunnyLib();
console.log(finalFunnyLib);
}
}
The code above isn't broken, it just doesn't produce a true random.
//Preferred Result: the program displays a different madlib each time the user clicks the submit button. The user only needs to click the button 3 times to get different madlibs, the fourth click clears the form and starts the program fresh.
Thank you!
I am open to any idea to make this a truly random madlibGenerator. Maybe counting number of clicks from a submit button?
So true randomness is going to be tough to achieve. Math.Random() from the javascript library isn't truly random as you've guessed, it's pseudo-random, meaning there is a pattern to it over a large number of inputs. Computers inherently can't really do true randomness, because they are always going to have to take some number, perform some sort of algorithm on it (these are usually "Mersenne Twisters" - fun wikipedia read), and spit out the result.
That said, I don't know exactly how to improve on what you've put into place here. With PRNG, a really large number of possible inputs can help a lot. If you want absolutely true randomness, the easiest way would probably be to hook into random.org's API (https://api.random.org/dashboard - developer license is free, limited to 1000 requests per day). Hooking into an API might be more work than you were planning on, but random.org uses (if I remember right) atmospheric noise and barometric pressure from the Earth to create their random numbers, so it's about as close to true randomness as you can possibly get.
I hope this helps!

Can't get two variables to concatenate

I'm a newbie, making a little exercise to practice with arrays. I've tried solving this from previous articles but none seem to have the relevant scenario.
I want to randomly generate sentences into paragraphs using phrases from an array. I got the random sentence generation part working fine.
var ipsumText = ["adventure", "endless youth", "dust", "iconic landmark", "spontaneous", "carefree", "selvedge","on the road", "open road", "stay true", "free spirit", "urban", "live on the edge", "the true wanderer", "vintage motorcyle", "american lifestyle", "epic landscape", "low slung denim", "naturaL"];
//a simple function to print a sentence //
var sentence = function (y) {
var printSentence = "";
for (i=0; i<7; i++) {
//random selection of string from array //
var x = Math.floor(Math.random() * 20);
printSentence += y [x] + " ";
}
return printSentence
};
console.log(sentence(ipsumText));
But now I want to be able to add a comma or full stop to the end of the sentence.
Because each word/phrase from the array used in the sentence prints with a space after it, I need to add an extra word with a full stop or comma right after it to avoid the space between them. To do this I created an extra variable
// create a word and full stop to end a sentence//
var addFullstop = ipsumText[Math.floor(Math.random() * ipsumText.length)] + ". ";
var addComma = ipsumText[Math.floor(Math.random() * ipsumText.length)] + ", ";
These variables work on their own how I expect. They print a random word with a comma or full stop right after them.
However now I can't work out how to get them to add to the end of the sentence. I have tried quite a few versions referencing articles here, but I'm missing something, because when I test it, I get nothing printing to the console log.
This is what I have most recently tried.
// add the sentence and new ending together //
var fullSentence = sentence(ipsumText) + addFullstop;
console.log(fullSentence)
Can someone explain why this wouldn't work? And suggest a solution to try?
thanks
See ES6 fiddle: http://www.es6fiddle.net/isadgquw/
Your example works. But consider a different approach which is a bit more flexible. You give it the array of words, how long you want the sentence to be, and if you want an ending to the sentence, pass in end, otherwise, just leave it out and it will not be used.
The first line generates an array of length count which is composed of random indices to be used to index into the words array. The next line maps these indices to actual words. The last line joins all of these into a sentence separated by a single space, with an optional end of the sentence which the caller specifies.
const randomSent = (words, count, end) =>
[...Array(count)].map(() => Math.floor(Math.random() * words.length))
.map(i => words[i])
.join(' ') + (end || '')
randomSent (['one','two','x','compound word','etc'], 10, '! ')
// x x one x compound word one x etc two two!
To make it more flexible, consider making a function for each task. The code is reusable, specific, and no mutable variables are used, making it easy to test, understand, and compose however you like:
const randInt = (lower, upper) =>
Math.floor(Math.random() * (upper-lower)) + lower
const randWord = (words) => words[randInt(0, words.length)]
const randSentence = (words, len, end) =>
[...Array(len)].map(() => randWord(words))
.join(' ') + (end || '')
const randWordWithEnd = (end) => randWord(ipsumText) + end
const randWordWithFullStop = randWordWithEnd('. ')
const randWordWithComma = randWordWithEnd(', ')
// Now, test it!
const fullSentWithEnd = randSentence(ipsumText, 8, '!!')
const fullSentNoEnd = randSentence(ipsumText, 5)
const fullSentComposed = fullSentNoEnd + randWordWithFullStop
Link again for convenience: http://www.es6fiddle.net/isadgquw/

Javascript: Storing and Sorting Data with Arrays

I am a beginner and I need help with this programming assignment.
Need to do a prompt. Get 10 names as input from user (string inputs). Put the names into an array and then write it out to the webpage.
My question is how do I save the input in the array, when the prompt has to be displayed over and over again for each name the user enters a name? Also, depending on how many names the user wants to enter, the user has a choice of quitting the prompt by typing in the letter 'q'. I am quite proficient at coding while and for loops, but not so much at coding arrays. Tried to search online but couldn't find an answer.
I would love if somebody could explain how to do it. Thanks!
I suggest the following solution:
// Create new array with 10 default values:
var result = new Array(10).fill('');
// Fill array with names via prompt():
eval(((a, b = ['x => x' + '.' + '\n' + 'so\x6De']) => b + '\x28' + a + '\x29')((a, b) => 'q' == (x[b] = prompt())))(result);
// Print result:
console.log(result);
How about something like this?
in your html somewhere
<div id="names">
</div>
function getNames(num) {
var arr = [],
person,
max = num || 5; // number of names you want
return (function R() {
if (arr.length < max) {
person = prompt("Please enter your name");
arr.push(person)
R()
} else {
document.getElementById("names").innerHTML =
"Hello " + arr.join(", ") + "! How are you today?";
}
}())
}
getNames(4)

JavaScript For Loop with user entry error

I am currently dabbling with JavaScript and am doing some simple calculations using for loops and I am attempting to take user info for the Table set they want and the numbers they wish to multiply between e.g.
Enter Table set: 12
Enter where to start multiplying from: 3
Enter how high to multiply: 6
This would print:
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
My issue is that when I ask the user to select how high they wish to multiply to, if they select a number greater than 9 it doesn't enter the for loop and prints nothing yet 9 and below works.
This is the simple enough code:
function UserEnteredTables()
{
var tableNumber = prompt("Please enter the number tables to use: ");
var numberLowerLimit = prompt("Please select where you want to start multiplying from: ");
var numberUpperLimit = prompt("Please select how high to multiply to: ");
document.write("Before the loop " + numberUpperLimit + "<br/>");
for (i = numberLowerLimit; i <= numberUpperLimit; i++)
{
document.write("Made it inside the loop " + "<br/>");
document.write(tableNumber + " * " + i + " = " + (i * tableNumber) + "<br/>");
}
document.write("After the loop " + numberUpperLimit);
}
Apologies for any indentation issues, had issues pasting for some reason
I have attached two images, one where I enter the upper limit to 9 and then one were I enter 10. As you can see the 10 doesn't enter the loop.
I assume that I have missed something very simple but I would appreciate if someone could explain what the issue is or if its something to do with JavaScript loops.
If there is something wrong with the post or you require some other code to fully understand just let me know.
Thanks in advance :)
The issue is with the prompt value returned: its typeof is string, while what you want is number for the loop to work correctly.
Use parse() to extract the numeric value out of the prompt value, see here:
https://jsfiddle.net/jwvj2aab/1/
Note that you will need to handle user input in order to deny anything but numbers

Finding the position of all instances of a word in a string, getting unwanted repetition in console

So I'm trying to create a simple function that finds the position of all instances of a word in any given string without using a for loop, regular expressions, or converting the string into an array, though I'd be interested in seeing those solutions too.
The code:
function wordFinder(word, text) {
var findStart = text.search(word);
var total = findStart + ' to ' + (findStart += word.length);
console.log(total);
text = text.replace(word[0], ' ');
if(text.search(word) == -1) {
console.log("all done");
} else {
return wordFinder(word, text);
}
};
wordFinder("hello", "hijellohellohello");
I would expect the console to show
"7 to 12"
"12 to 17"
"all done"
But instead I get
"7 to 12"
"7 to 12"
"12 to 17"
"all done"
Having played with it some, it's clear that if a character which matches word[0] comes before the word it causes the console.log(total) to fire once for each match, but I'm not sure why it's doing this.
Edit: explanation makes sense, and here's my ugly solution that uses a for loop and creates a questionable situation with undefined, but it works! If anyone wants to tell me how it would actually be done in a real environment, that'd be appreciated.
function wordFinder(word, text) {
var findStart = text.search(word);
var total = findStart + ' to ' + (findStart += word.length);
var holder = [];
var spacer = " ";
console.log(total);
for(i=0; i + 1 < word.length; i++) {
holder.push(spacer[i]);
if(holder[i] === undefined) {
holder[i] = spacer;
}
}
text = text.replace(word, holder);
if(text.search(word) == -1) {
console.log("all done");
} else {
return wordFinder(word, text);
}
}
wordFinder("abc", "abaabczabcabc");
returns
"3 to 6"
"7 to 10"
"10 to 13"
"all done"
It's because you're taking the first letter and replacing it with a space. So your starting text is hijellohellohello the first time, and ijellohellohello the second time which means that your first instance of hello is still in the same spot. So when you run the recursion the second time around, you get the same result.
Edit: To clarify further, the beginning of the text begins with "h". If word begins with "h" and you do word[0] that will be equal to "h". You're saying replace the first instance of "h" with a space. So it prints out "7 to 12", does the replace, prints it out again, then does another replace, then finds the last instance of "hello"

Categories

Resources