My React Native Journey - 9 - Implementing Wordle Game Won or Lost Logic

 Handling the Game Won or Lost State

 If all the letters in the previous row are the same as that in the selected word, the game ends with a message "You have won!". 

else, if there are no more tries left, the game ends with the message "Try again tomorrow".

Everytime the row changes, the app looks in the previous row, and for each element in the row, it validates it against the letter positions in the selected word. We use the useEffect hook for the purpose.

useEffect(() =>{
    if (curRow > 0) {
      checkGameState();
    }
  }, [curRow])
 
const checkGameState = () => {
     if (checkifWon()) {
      Alert.alert('Hurraayy', 'You won')
     } else if (checkifLost()) {
      Alert.alert("Meh", "Try again tomorrow")
     }
  };

 const checkifWon = () => {
     const row = rows[curRow - 1];
     return row.every((letter,i) => letter === letters[i])
  }
 
  const checkifLost = () => {
    return curRow === rows.length;
  }

useEffect - A brief overview

useEffect is the hook that manages side effects. 
In general, useEffect is executed everytime the view renders. However, you can control when it gets executed (A good explanation here.by defining dependencies, ([curRow]) in our case. So it will get executed when curRow gets updated.

So everytime curRow changes, we execute the checkGameState function, which in return executes the checkifWon and checkifLost functions.

return row.every((letter,i) => letter === letters[i])

The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. 
For example,

[12, 5, 8, 130, 44].every(x => x >= 10);   // false
[12, 54, 18, 130, 44].every(x => x >= 10); // true

so, our checkifWon says return true if all elements and their positions (indexes) are the same as that in the original word (defined as array in the variable 'letters'), else execute function checkifLost, where you only check if the max tries have exceeded. If yes, the user has lost the game.

Next activity is to allow the user to share his success by selecting the colored board like the regular wordle users do.





Comments

Popular posts from this blog

Reading a pre-populated sqlite database using react native with expo..

React Hooks - useState Vs useRef (An explanation)