I’m working on an assignment to make a “higher or lower” guessing game. I finished it all early and I wanted to get some practice in with arrays… I’d like to have a random comment depending on the given condition. I’ve tried using the math.Random method but it only generates one comment from the list every time.
This is the code for the HTML part of things. The comment should replace “lets go”.
let higherComment = [
"the magic number is higher than your guess.",
"more than that. i can count to 100.",
"add more numbers to that integer. maybe like 2 or 47 more?",
"that's not enough tinned fi - sorry i meant numbers. higher.",
"your number isn't high enough. quit fooling around."];
let randomHigherComment = higherComment[Math.floor(Math.random() * higherComment.length)]
I believe the issue might lie in that you are generating a random number once and using that as the index so it’s always the same comment, to get a random comment each time you submit the form you would need to generate the random number every time so the index varies
Edit: I also noticed your switch statement uses higherComment[randomHigherComment] , you might need to check if randomHigherComment returns an integer to be used as an index
As wendel.t.c noted, pick a new index inside guessNumber each time the form is submitted. In the higher branch, for example:
const index = Math.floor(Math.random() * higherComment.length);
document.querySelector('#sealSpeaking p').textContent = higherComment[index];
Your original randomHigherComment is already a string, not an index, so don’t use it inside higherComment[...]. As ILM suggested, a complete runnable example would help if the issue persists.
Whoops. randomWinComment should have been replaced with randomHigherComment. I’ll remove that right now - I overlooked it yesterday while rewriting the code. Edit: Updated.
ideally yes, but right now, when does it get a new value?
you need to have the line let randomHigherComment = higherComment[Math.floor(Math.random() * higherComment.length)] in the place that makes it so, what is the scope that is run at every click?