My React Native Journey - 8 - Adding background colors to the Wordle UI
Adding Background Colors to the grid and the keyboard.
Import colors from constants.js (provided by Vadim)
Adding background colors to the grid
Set the background color of the cell, based on the return value of a function getCellBGColor, which takes the letter itself, the current row, and the current column, and returns the color that is expected.
<ScrollView style={styles.map}>
{rows.map((row, i) => (
<View
key = {`row-${i}`}
style = {styles.row}>
{row.map((letter, j) => (
<View
key = {`cell-${i}-${j}`}
style = {[styles.cell,
{borderColor: isCellActive(i, j)
? colors.lightgrey
: colors.darkgrey,
backgroundColor: getCellBGColor(letter,i,j),
},
]}>
<Text style = {styles.cellText}>{letter.toUpperCase()}</Text>
</View>
))}
</View>
))}
</ScrollView>\
The function is provided below.
If we are currently on a new blank row, return the black color.
Else if the letter is in the letters array, and also in the same column as the current column, return primary
color.
Else if the letter is found to be in the letters array, return the secondary color.
Else, return the darkgrey color.
const getCellBGColor = (letter, row, col) => {
if (row >= curRow) {
return colors.black;
}
if (letter === letters[col]) {
return colors.primary;
}
if (letters.includes(letter)) {
return colors.secondary;
}
return colors.darkgrey;
}
Adding background colors to the keyboard
In the Keyboard tag, include the following code.
<Keyboard
onKeyPressed={onKeyPressed}
greenCaps={getAllLettersWithColor(colors.primary)}
yellowCaps={getAllLettersWithColor(colors.secondary)}
greyCaps = {getAllLettersWithColor(colors.darkgrey)}
/>
The function getAllLettersWithColor will take the required color as parameter, and return all the letters
that are part of the array of that color.
const getAllLettersWithColor = (color) => {
return rows.flatMap((row,i) =>
row.filter((cell, j) => getCellBGColor(i,j) === color));
}
greenCaps. yellowCaps and greyCaps, and the code to the keyboard View are all defined in the
keyboard.js component, provided by Vadim.
Next activity is to handle game States - whether we won or lost.
Comments
Post a Comment