I’m building a hangman game in JavaScript. React actually. I got it all working except I was to support multiple words. Meaning, the spaces must exist but not be considered in the logic to determine completion of the game.
The snippet below is how I am getting the answer
which is a prop passed based on the keyboard hits and splitting it to get the characters. Then, I map the letters and inside the map function I make a ternary evaluation against a correctedLetters
prop value which contains the real word they’re guessing.
{answer.split('').map((letter, index) => {
const l = letter.toUpperCase();
return (
<Text key={index} style={[{color: activeColors.textcolor}, styles.text]}>
{correctLetters.includes(l) ? l : '-'}
</Text>
)
})}
What I would like to do is show two or more sets of dashes depending on whether the answer is one word or two. See the image to see what I mean. That dash in the middle is just a space. Technically, I should’ve won here
Kind of like a Wheel of Fortune actually.
2
Answers
Because of this code
correctLetters.includes(l) ? l : '-'
, any space will be converted to a dash, thus, if the answer contains two words the user will never win because I think you are checking for the dashes to decide if a user won or lost.You have to check first if
letter
is a real letter or it’s just a whitespace, hence, if it’s" "
you’ll add a space else add a letter/dash.Building on MHD Alaa Alhaj‘s answer, you need to determine if the current character in your loop is a space, however, if you don’t plan on using the result of
map
you can forgo it and use a traditional for loop and a simple ternary operator.You can also use the ternary operator inside the second
<Text />
element (in theOR
part of the ternary operator) to maintain the same style for each character including spaces. Please note that in this version, the key (index) is preserved for all characters including spaces.Good luck.