Reducer

Since we have a very limited amount of actions, our reducer will also be fairly simple and will delegate most of the functionality to the sprites helper functions in the src/sprites.js file:

/*** src/reducers/index.js ***/

import {
  sprites,
  moveSprites,
  checkForCollision,
  getUpdatedScore,
  bounceParrot
} from “../sprites";

const initialState = {
  score: 0,
  gameOver: false,
  isStarted: false,
  sprites
};

export default (state = initialState, action) => {
  switch (action.type) {
    case “TICK":
      return {
        ...state,
        sprites: moveSprites(state.sprites, action.elapsedTime),
        gameOver: checkForCollision(state.sprites[0], 
        state.sprites.slice(1)),
        score: getUpdatedScore(state.sprites, state.score)
      };
    case “BOUNCE":
      return {
        ...state,
        sprites: bounceParrot(state.sprites)
      };
    case “START":
      return {
        ...initialState,
        isStarted: true
      };
    default:
      return state;
  }
};

The start() function only needs to set the isStarted flag to true, as the initial state will have it set to false by default. We will reuse this initial state every time the game ends.

bounce() will use the bounceParrot() function from the sprites module to set a new direction for the main character.

The most important changes will happen when the tick() function is triggered, as it needs to calculate the positions of all moving elements (through the moveSprites() function), detect if the parrot has collided with any static elements (through the checkForCollision() function), and update the score in the store (through the getUpdatedScore() function).

As we can see, most of the game's functionality is delegated to the helper functions inside the sprites module, so let's take a deeper look into the src/sprites.js file.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181