Bombing JavaScript Fatigue with Minesweeper (Part 2 — Reducers)

Abhi Aiyer
2 min readApr 18, 2016

--

Part 1 here.

Let’s get straight to business.

Let’s think about all the state we want to manage. I’ll make a checklist:

First things first, I like to note down my action types. And think about these first:

1. We definitely need some general game stats.

Like the level of difficulty, how many mines are in the grid, and col/rows numbers.

Alright so we save a bunch of meta data we’re interested in. And when the store receives messages corresponding to our difficulty levels, we’ll update our game stats to Easy, Normal or Hard. This will effect the number of mines, and the row/cols we have.

2. I can flag squares in Minesweeper.

I should probably keep track of adding a flag, and resetting them.

We’ll later right a hook into the UI to update this state as the user places flags on their minesweeper grid.

3. We need a state for when we click on tiles and open up squares on the board:

We’ll later right a hook into the UI to update this state as the user places opens up the bomb-less tiles.

4. Need some state around the actual “State of the Game”.

5. Definitely got to time the whole thing!

6. Root Reducer

From the docs

The combineReducers helper function turns an object whose values are different reducing functions into a single reducing function you can pass to createStore.

The resulting reducer calls every child reducer, and gathers their results into a single state object. The shape of the state object matches the keys of the passed reducers.

WAIT WAIT WAIT.

Doesn’t the reducer for our Game Time look exactly the same as our Open Tiles reducer?

Enter Higher Order Reducers:

To dry out our code we should write a “Higher Order Reducer”. When writing these types of reducers, you need to ask yourself, “How would I describe the state change.

For the case of Game Time and Open Tiles, they both can increment and reset. Essentially we have 2 states that increment by one per dispatch, but we need to use these states to power different parts of our application.

Let’s write a HO Reducer:

Now we can have multiple states with the same state shape without duplicating code.

Let’s update our Root Reducer

Now we have described the state of a Minesweeper app! Next we’ll write our api to update this state. We call these Actions.

Part 3 here.

Full code:

This post is part of a series called Mastering Meteor and Redux. You can read the course syllabus here. Follow me on Twitter @abhiaiyer and I’ll see you for the next chapter.

--

--

Responses (1)