0

The state gets hydrated by a function that randomly creates an array of numbers (+ 0) as follows:

[[3, 0], [6, 0], [8, 0], [2, 0].....]

and that's the app's state at the moment. [3, 0] is an example of a tile containing number 3 and being invisible (0) Once I click on a tile, it dispatches an action and the 0 of the corresponding element changes to 1 and based on that the tile uncovers displaying the number (3)

So if I clicked on the first tile, the state would change to: [[3, 1], [6, 0], [8, 0], [2, 0].....]

Now, I want to add the following:

  • track how many tiles are uncovered (ie. have 1s as the second element) at any time.

  • limit the number of uncovered tiles to 2 (if the 2nd tile's number does not match the first one, both get covered again - many memory games have similar functionality)

  • if I uncover one tile and then the second and the numbers match, I'd like them to remain permanently uncovered, and we add +1 to the score.

Should I design it as a different part of main state (using a different reducer and then combineReducers)? or should I redesign the first part of the state to include it as follows:

initialState = {
  grid: [[3,0], [4,0],...],
  score: 0,
  number_of_uncovered_tiles: 0
}

Now to change the values of score and number_of_uncovered_tiles - am I correct that I should not be using actions but selectors as both will just be automatically calculated based on the state of the grid array element values?

Wasteland
  • 4,889
  • 14
  • 45
  • 91

1 Answers1

1

Generally it is suggested to keep your state as flat as possible, avoiding deeply nested hierarchies operated by single reducer.

In your case I would split grid reducer and uncoveredTiles reducer. This will give you better control on uncovering tiles without the need to to run over array of tiles over and over again.

{
  grid: [ 3, 4, 9, ...],
  score: 0,
  uncoveredTiles: [ 0, 2 ],
}

This way closing tiles when two are opened is just matter of updating grid[uncoveredTiles[0]] and grid[uncoveredTiles[1]] and reseting uncoveredTiles to [].

In case your tile data will get more complex (e.g. you'll swap numbers with images) only grid reducer will have to change, while uncoveredTiles will stay the same.

Also I would consider introducing separate reducer for scores not to mess different logical concerns in single place.

fkulikov
  • 3,169
  • 13
  • 24