My React Native Journey - 11 - Creating a master list of words for the Wordle game.

Creating a master list words for the game

So far, we have worked with the code to work with one word "hello". Now, we will arrange it so that the game is able to select random words from a list. Vadim's tutorial selects a daily word, going by the day, between 1 and 366. So there would be 366 words in his list, and if there are more, they will never be selected.

I have kept the same approach, except for a slight deviation that he maintains the list of words in the App.js code itself, I chose to move it to another file.

I created a data folder in the root directory, and initially played with trying to read a text file (words.txt) or CSV file (words.csv). It seems there is no easy way of doing this, and honestly, I didn't try very hard. So, I created a words.js file, which exports the list of words, like so. Note that there are 366 words in this list.

export const words_list = ['amaze,'amuse,'abyss'....366 words];

So, here is the code in the App.js file:

import {word_list} from './data/words';

Notice that I import word_list and not words_list that  I exported from the words.js file?

This will give an error - TypeError: undefined is not an object (evaluating '_words.word_list[dayOfTheYear]')

Solve the error by replacing the term 'word_list' in App.js with 'words_list'.

How to select the word?

There are 365 days in an year, (366 for a leap year). What we want to do is that if current day is day 186 of the year, we will pick the 186th word from the words list. 

Now, There is no given function that will return the day number of the year, so we have to calculate it on our own. (Refer solution here)

const getDayOfTheYear = () => {
      const now = new Date();
      const start = new Date(now.getFullYear(), 0, 0);
      const diff = now - start;
      const oneDay = 1000 * 60 * 60 * 24;
      const day = Math.floor(diff / oneDay);
      console.log('Day of year: ' + day);
      return day;
  }
  const dayOfTheYear = getDayOfTheYear();
  const word = words_list[dayOfTheYear];

This will fetch the word from the words_list array from the current day number position and populate the 'word' with it.

Next, we will wrap up the code and tie up some loose ends.


Comments

Popular posts from this blog

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

React Hooks - useState Vs useRef (An explanation)