Create a Pokemon battle game with React Native - Part 1: Practice mode

  • Wern Ancheta
November 28th, 2018
You will need Node 8+, Expo and Yarn installed on your machine.

In this tutorial, we’ll be building a Pokemon battle game with React Native and Pusher.

These are the topics that will be covered in this series:

  • Part one: Practice mode

In this part, we’ll be implementing the game’s practice mode. This is where we’ll be implementing the team selection and battle screen (login screen is already pre-coded in the starter project). First, the user logs in and selects six Pokemon that they want to use for the battle. Once the user has confirmed their team, an opponent Pokemon team will be randomly generated. The user gets to battle each Pokemon in the opponent team, but they won’t fight back.

  • Part two: Two-player mode

In part two, we’ll be implementing the two-player mode. This is where we will use Pusher channels, and a Node server to match users who are currently looking for an opponent. Additionally, we’ll also be showing messages to inform both users on the actual attack that was used and its effectiveness (for example, Pikachu used Thunderbolt! It’s super effective).

  • Part three: Animations and sounds

In part three, we’ll be adding animations and sounds to make the game more interactive and fun to play with. Specifically, we’ll animate the health bar when a Pokemon is attacked, animate a couple of attacks (for example, Fire Punch or Ice Punch), and animate when the user switches to a new Pokemon or their current one faints. As for the sounds, we’ll add background music in each of the screens, and play the specific Pokemon cry as they get switched to or when they faint.

Prerequisites

Basic knowledge of React Native, React Navigation, Redux, and ES6 syntax is required.

We’ll be using the following package versions:

  • Node 8.3.0
  • Yarn 1.7.0
  • Expo CLI 2.2.0
  • Expo SDK 30.0.0
  • Pusher 4.3.1

It’s always recommended to use the most recent versions available to you, but those versions are there as a reference in case there’s a major change with those packages which causes the code used in this series to not work.

We’ll be using Expo in order to easily test the app on multiple devices. Install Expo on your computer, then download the Expo client app for your iOS or Android device.

App overview

If you’re not familiar with how Pokemon battles are done, there are usually two Pokemon trainers, each has six Pokemon in hand. Each trainer will select one Pokemon to battle the other trainer’s Pokemon. The goal is to make the other Pokemon lose all of its health points (HP) by using different moves (for example, Thunderbolt or Hydro Pump). Once the Pokemon loses all of its HP, they cannot be used again.

The trainer can also switch out their Pokemon. This is usually done to take advantage of type-effectiveness (for example, fire type Pokemon is effective on grass types, but is weak against water types).

In the middle of the battle, the trainer can also bring back the lost HP of their Pokemon by using healing items (for example, potion). There are also items for healing status conditions (for example, sleep or paralysis). These status conditions are invoked by using specific moves like Sleep Powder or Thunder Wave.

The first trainer who loses all of their Pokemon loses the game, while the trainer who still has Pokemon wins.

For this app, we’re going to simplify things a bit by omitting the following features:

  • Status conditions - no conditions such as frozen, burned, and poisoned.
  • Item usage - no items such as full heal, max potion, berries.

Now that you’re familiar with the game mechanics, it’s time for a quick overview of the final output for the whole series:

  1. When the user opens the app, they first have to enter a username:

  1. Next, they will need to select their team, which composed of six Pokemon. Once they have selected all six, a button for confirming their selection will show up:

  1. Next, the app will look for an opponent:

  1. Once an opponent is found, it will show the battle screen. The first turn will go to the user who confirmed their team first.

  2. From the battle screen, the first Pokemon picked by the user is pre-selected to battle the opponent’s first Pokemon:

  1. The user can either pick another Pokemon from their team or use one of the four moves by their current Pokemon:

  1. Once a move is chosen (either attack or switch), the user can no longer make another move until their opponent has made their move. Each user just takes their turns until such time that someone has defeated the whole team of their opponent.

Here’s a gif of the battle screen:

In this part, we won’t be implementing all the features yet. As mentioned in the introduction earlier, the first part will be the practice mode. This is where the user only gets to play the game by themselves.

Clone the starter project

The app that we’re building is pretty huge, that’s why I created a starter project which contains the Pokemon data, UI components, helper functions, and the bare-bones version of each screen. This way, we don’t have to code everything from scratch and we can focus on the more important parts of the app.

Go ahead and clone the repo, switch to the starter branch, and install all the packages we need for this part:

    git clone http://github.com/anchetaWern/RNPokeBattle
    cd RNPokeBattle
    git checkout starter
    yarn install

Overview of the starter project

Before we proceed with writing some code, let’s first do a quick tour of the code we have on the starter branch.

data

The src/data folder contains the pokemon (src/data/pokemon_data.js) and moves data (src/data/moves_data). Open those files so you have an idea of what the data structure looks like. The moves array in each of the Pokemon object in the src/data/pokemon_data.js file contains the ID’s of the moves in the src/data/moves_data.js file. The app will pick four random ID’s from the moves array and get its details from the src/data/moves_data.js file.

assets

The assets folder contains app assets such as images, fonts, and later on, the sound files. We’re using three different images for each Pokemon: sprite, front animated, and back animated. I got the sprites from pokemondb.net, while the front and back gifs are from pokestadium.com.

For the custom font, we’re using Aldrich from Google Fonts.

components

The src/components folder contains all the UI components used in the app:

  • ActionList - for showing the actions that the user can do. In this case, there are only two: attack and switch.
  • HealthBar - for showing the current health of each Pokemon.
  • MovesList - for showing the list of Pokemon moves.
  • PokemonFullSprite - for showing the back and front animated gifs of each Pokemon.
  • PokemonList - for showing a list of Pokemon for the team selection and battle screen.
  • PokemonOption - for showing the individual clickable Pokemon in the PokemonList.
  • CustomText - allows us to use the custom font.

Note that the UI for these components are already written, but we still need to turn a few of them into “connected components” so they can dispatch actions and have access to the app’s global store.

helpers

The src/helpers folder contains the following helper functions:

  • getMoveEffectivenessAndDamage.js - for calculating damage made to a Pokemon based on a specific attack and the attacked Pokemon’s type defenses.
  • randomInt.js - for generating a random integer between a specific range.
  • shuffleArray.js - for sorting arrays in random order. It’s used for sorting the moves data randomly so that random moves can be picked for each Pokemon.
  • uniqid.js - for generating a unique ID for each member of your Pokemon team.

screens

The src/screens folder contains all the screens of the app. Only a placeholder content and the screen’s final styles are pre-written in the starter project. The Login screen is already completed because all it does is pass the username to the team selection screen as a navigation prop. Navigation code is also set up for all the screens, so all you have to do is navigate between the screens.

Lastly, to make it easier to debug the app, the initialization code for Reactotron is also pre-written. All you have to do is update the value for the host with the internal IP address assigned by your router to your computer. This way, Reactotron can find your Expo app. You can find that code in the Root.js file.

Build the app

Now that you know which part of the app is already pre-written, we’re ready to implement the functionality for each screen.

Team selection screen actions

Create a src/actions/types.js file. This is where we will add all the action types that can be performed in the app. First, let’s add the actions that can be performed in the team selection screen:

    export const SELECT_POKEMON = "select_pokemon"; // for marking Pokemon as selected

    export const SET_POKEMON = "set_pokemon"; // for setting a specific Pokemon as the current Pokemon used for battle
    export const SET_TEAM = "set_team"; // for setting a Pokemon team

Next, create a src/actions/index.js file, this is where we will add all the action creators for the whole app. Start by adding the functions that will be dispatched when selecting a Pokemon in the team selection screen, and setting the user’s current Pokemon and Pokemon team:

    import {
      SELECT_POKEMON,
      SET_POKEMON,
      SET_TEAM
    } from "./types";

    export const selectPokemon = (id, pokemon_data, is_selected) => { // accepts the Pokemon ID, Pokemon object, and a boolean representing whether it's selected or not
      return {
        type: SELECT_POKEMON,
        id,
        pokemon_data,
        is_selected
      };
    };

    export const setPokemon = pokemon => { // accepts a single Pokemon object
      return {
        type: SET_POKEMON,
        pokemon
      };
    };

    export const setTeam = team => { // accepts an array of Pokemon object data (same as the ones you find in src/data/pokemon_data.js)
      return {
        type: SET_TEAM,
        team
      };
    };

Team selection screen reducer

Create a src/reducers/TeamReducer.js file. This reducer is responsible for specifying how the store will change when the action for selecting a Pokemon is dispatched. Specifically, it describes how the selected_pokemon array changes when it receives the SELECT_POKEMON action. It only processes the request further if less than six Pokemon are currently selected. From there, it pushes the selected Pokemon into the selected_pokemon array, and removes it if it’s deselected (when action.is_selected is false):

    import { SELECT_POKEMON } from "../actions/types";

    import pokemon_data from "../data/pokemon_data";

    const INITIAL_STATE = {
      pokemon: pokemon_data,
      selected_pokemon: [] // stores the currently selected Pokemon
    };

    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case SELECT_POKEMON:
          let pokemon = [...state.pokemon];
          let selected_pokemon = [...state.selected_pokemon];

          const is_selected = action.is_selected;

          if (state.selected_pokemon.length < 6 || is_selected) { // there should only be six selected Pokemon
            pokemon = pokemon.map(item => {
              if (item.id == action.id) { // only modify the Pokemon specified in the action
                item.is_selected = !is_selected; // flip the current is_selected value 
              }
              return item;
            });

            if (is_selected) {
              const index_to_remove = selected_pokemon.findIndex(
                item => item.id == action.id
              );
              selected_pokemon.splice(index_to_remove, 1);
            } else {
              selected_pokemon.push(action.pokemon_data);
            }
          }

          return { ...state, pokemon, selected_pokemon };

        default:
          return state;
      }
    };

As you noticed in the code above, we’re only processing the SELECT_POKEMON action type. This is because SET_POKEMON and SET_TEAM will be processed in the reducer for the battle screen related actions which we’ll add it shortly. We only added them in the action types and action creators file because they’re needed in the team selection screen.

Battle screen reducers for Team selection screen

Create a src/reducers/BattleReducer.js file, and add the reducers responsible for setting the user’s Pokemon team and current Pokemon:

    import {
      SET_TEAM,
      SET_POKEMON
    } from "../actions/types";

    const INITIAL_STATE = {
      team: [], // the user's Pokemon team
      pokemon: null // currently selected pokemon by user (the one being shown in the UI)
    };

    export default (state = INITIAL_STATE, action) => {
      switch (action.type) {
        case SET_TEAM:
          const { team } = action;
          return { ...state, team };

        case SET_POKEMON:
          const pokemon = action.pokemon;
          return { ...state, pokemon };

        default:
          return state;
      }
    };

Bringing all the reducers together

Create a src/reducers/index.js file, and combine the two reducer files we created earlier. This allows us to import only this file when we need to include all the reducers that we need:

    import { combineReducers } from "redux";
    import TeamReducer from "./TeamReducer";
    import BattleReducer from "./BattleReducer";

    export default combineReducers({
      team_selection: TeamReducer,
      battle: BattleReducer
    });

Add the store to the app

At this point, we’re now ready to add the global app store:

    // Root.js
    import { Provider } from "react-redux";
    import { compose, createStore } from "redux";
    import reducers from "./src/reducers";

To make debugging the store easier, you may also add Reactotron Redux to your existing Reactotron configuration:

    import { reactotronRedux } from "reactotron-redux";
    Reactotron.configure({ host: "IP_ADDRESS_ASSIGNED_BY_YOUR_ROUTER" })
      .useReactNative()
      .use(reactotronRedux()) // add this
      .connect();

Don’t forget to add Reactotron Redux as your dev dependency:

    yarn add --dev reactotron-redux

Lastly, update the render function so it wraps everything in the Provider component which uses the store:

    // Root.js
    render() {
      return (
        <Provider store={store}>
          <RootStack />
        </Provider>
      );
    }

Team selection screen

The team selection screen is where the user gets to pick the Pokemon they want to use to battle their opponent. Start by importing the action creators for setting the team and current Pokemon:

    // src/screens/TeamSelectionScreen.js
    import { connect } from "react-redux";

    import { setTeam, setPokemon } from "../actions";
    import moves_data from "../data/moves_data";

Next, scroll down to the part where the component is exported and add the function for mapping specific values in the store as props for this component. In this case, we only need values from the team reducer (src/reducers/TeamReducer.js). We gave it a name of team_selection in the src/reducers/index.js file, so that’s what we’re extracting:

    const mapStateToProps = ({ team_selection }) => {
      const { pokemon, selected_pokemon } = team_selection;

      // return pokemon and selected_pokemon as props for this component
      return {
        pokemon, // all the Pokemon available for selection (a copy of src/data/pokemon_data.js)
        selected_pokemon // array of selected Pokemon
      };
    };

    // next: add mapDispatchToProps

Since we want to set the team and current Pokemon from this screen, we create the function that allows us to dispatch the setTeam and setPokemon actions. This allows us to update the store with a new team and pokemon data by executing the similarly named setTeam and setPokemon functions returned from this function. Note that you don’t need to use the same name we used for the action creators. If it makes sense to use a different name, then do it (for example, if you get confused whether a specific function is referring to the function returned from mapDispatchToProps or the action creator itself):

    const mapDispatchToProps = dispatch => {
      // for updating the value of team and pokemon in src/reducers/BattleReducer.js
      return {
        setTeam: team => {
          dispatch(setTeam(team));
        },
        setPokemon: pokemon => {
          dispatch(setPokemon(pokemon));
        }
      };
    };

    // next: convert component into a connected one

Next, convert the component into a connected component. This gives us access to the specific values we returned earlier on mapStateToProps as props, and call the functions we returned in mapDispatchToProps earlier:

    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(TeamSelectionScreen);

At this point, we’re now ready to update the render method of the team selection screen. By default, we only display the PokemonList. As mentioned in the overview of the starter project section earlier, the PokemonList function is responsible for rendering a list of Pokemon. All you have to do is supply an array of Pokemon data to its data prop. The pokemon data is available in the store and it’s made available as a prop via the mapStateToProps function. The same is true of the selected_pokemon. We’re using it to determine whether to show the button to confirm the team. Once the user clicks on it, the ActivityIndicator will be shown to indicate that the app is looking for an opponent:

    render() {
      const { selected_pokemon } = this.props;
      return (
        <View style={styles.container}>
          <CustomText styles={[styles.headerText]}>Select your team</CustomText>

          {selected_pokemon.length == 6 && (
            <View>
              {this.state.is_loading && (
                <View style={styles.loadingContainer}>
                  <ActivityIndicator size="large" color="#ffbf5a" />
                  <CustomText styles={styles.messageText}>
                    Waiting for opponent..
                  </CustomText>
                </View>
              )}

              {!this.state.is_loading && (
                <TouchableOpacity
                  style={styles.confirmButton}
                  onPress={this.confirmTeam}
                >
                  <CustomText>Confirm Selection</CustomText>
                </TouchableOpacity>
              )}
            </View>
          )}
          <PokemonList
            data={this.props.pokemon}
            numColumns={1}
            action_type={"select-pokemon"}
          />
        </View>
      );
    }

    // next: add confirmTeam function

Next, add the code for the function that gets executed when the button for confirming the team is clicked. This adds some of the required data for the battle screen. This includes the health points, the unique team member ID, and the random Pokemon moves data for each Pokemon in the team:

    // src/screens/TeamSelectionScreen.js

    confirmTeam = () => {
      const { selected_pokemon, setTeam, setPokemon, navigation } = this.props;

      let team = [...selected_pokemon]; // the array which stores the data for the Pokemon team selected by the user

      team = team.map(item => {
        let hp = 500; // the total health points given to each Pokemon

        let shuffled_moves = shuffleArray(item.moves);
        let selected_moves = shuffled_moves.slice(0, 4);

        let moves = moves_data.filter(item => {
          return selected_moves.indexOf(item.id) !== -1;
        });

        let member_id = uniqid();

        return {
          ...item,
          team_member_id: member_id, // unique ID for identifying each Pokemon in the team
          current_hp: hp, // current HP. This gets updated when an opponent Pokemon attacks
          total_hp: hp,
          moves: moves,
          is_selected: false // no longer needed
        };
      });

      // update the store with the new team and Pokemon data
      setTeam(team);
      setPokemon(team[0]);

      // next: set is_loading to true in state and navigate to Battle screen
    };

Next, we want to emulate that the app is actually trying to find an opponent for the user, so we’ll trigger the ActivityIndicator to be visible for 2.5 seconds before we navigate to the battle screen:

    this.setState({
      is_loading: true // show activity indicator
    });

    setTimeout(() => {
      const username = navigation.getParam("username");

      this.setState({
        is_loading: false
      });

      navigation.navigate("Battle", {
        username: username
      });
    }, 2500); // 2.5 seconds

We will update the above code in part two, so it actually tries to find a real opponent for the user.

Dispatch the action for selecting a Pokemon

We haven’t actually added the code that actually selects or deselects a specific Pokemon to be added to the team, so let’s go ahead and add it. If you open the src/components/PokemonList/PokemonList.js file, you will see that it uses the PokemonOption component to render each of the Pokemon items that you see in the team selection screen. We’re not really passing any functions in there so the actual function should be declared in the PokemonOption itself. Start by importing the action for selecting a Pokemon:

    // src/components/PokemonOption/PokemonOption.js

    import { connect } from "react-redux";

    import { selectPokemon } from "../../actions";

Next, use mapDispatchToProps so you can dispatch the action via a togglePokemon function which you can call inside the component’s body. This expects the id of the Pokemon, an object containing the Pokemon data, and a boolean that indicates whether it’s currently selected or not:

    const mapDispatchToProps = dispatch => {
      return {
        togglePokemon: (id, pokemon_data, is_selected) => {
          dispatch(selectPokemon(id, pokemon_data, is_selected));
        }
      };
    };

    export default connect(
      null,
      mapDispatchToProps
    )(PokemonOption);

Next, extract the togglePokemon function from the props:

    const PokemonOption = ({
       // previously added code here..

      // add this:
      togglePokemon
    }) => {
      // existing code here...
    });

When the user clicks on the component, the action_type is first determined. This component is used for both team selection and Pokemon selection (in the battle screen later), so we need to determine the context in which it was called. An action_type of select-pokemon means that it was called from the team selection screen, thus we call the togglePokemon function to select or deselect it. The action_type prop is passed to the PokemonList component and down to the PokemonOption:

    onPress={() => {
      if (action_type == "select-pokemon") {
        togglePokemon(id, pokemon_data, is_selected);
      } 
    }}

Battle screen actions

Now that we’ve implemented the team selection screen, let’s proceed with adding the code for the battle screen. Start by updating the action types file to include the actions that can be performed in the battle screen:

    // src/actions/types.js

    // existing code here...

    // add these:
    export const SET_OPPONENT_TEAM = "set_opponent_team";

    export const SET_MOVE = "set_move";

    export const SET_OPPONENT_POKEMON = "set_opponent_pokemon";
    export const SET_OPPONENT_POKEMON_HEALTH = "set_opponent_pokemon_health";

    export const REMOVE_POKEMON_FROM_OPPONENT_TEAM =
      "remove_pokemon_from_opponent_team";

Next, create an action creator for the action types we just added:

    // src/actions/index.js

    import {
      // existing action types here...

      // add these:
      SET_OPPONENT_TEAM,
      SET_MOVE,
      SET_OPPONENT_POKEMON,
      SET_OPPONENT_POKEMON_HEALTH,
      REMOVE_POKEMON_FROM_OPPONENT_TEAM
    } from "./types";

    // add these after the last function:
    export const setOpponentTeam = team => { // accepts an array that contains the Pokemon data of the team selected by the user
      return {
        type: SET_OPPONENT_TEAM,
        team 
      };
    };

    export const setMove = move => { // accepts an object containing the move data (same as what you see in src/data/moves_data.js)
      return {
        type: SET_MOVE,
        move
      };
    };

    export const setOpponentPokemon = pokemon => { // accepts an object containing the data of the Pokemon selected by the opponent
      return {
        type: SET_OPPONENT_POKEMON,
        pokemon
      };
    };

    export const setOpponentPokemonHealth = (team_member_id, health) => { // accepts the team_member_id of the opponent's Pokemon, and the new health points to be assigned
      return {
        type: SET_OPPONENT_POKEMON_HEALTH,
        team_member_id,
        health
      };
    };

    export const removePokemonFromOpponentTeam = team_member_id => { // accepts the team_member_id of the Pokemon to be removed from the opponent's team
      return {
        type: REMOVE_POKEMON_FROM_OPPONENT_TEAM,
        team_member_id
      };
    };

Battle screen reducers for Battle screen

Next, let’s add the reducers for the Battle screen:

    // src/reducers/BattleReducer.js

    import {
      // existing code here...

      // add these:
      SET_OPPONENT_TEAM,
      SET_MOVE,
      SET_OPPONENT_POKEMON,
      SET_OPPONENT_POKEMON_HEALTH,
      REMOVE_POKEMON_FROM_OPPONENT_TEAM
    } from "../actions/types";

Next, include the additional state that we will manage in this reducer. This includes the user’s current move. It controls what the user sees in the bottom part of the screen. By default, it’s set to select-move, this allows the user to either attack with their current Pokemon or switch to another one from their team. The user also needs to access the data for their opponent’s team so we have the opponent_team and opponent_pokemon (the opponent’s current Pokemon) as well:

    const move_display_text = {
      "select-move": "Select your move", // main menu (choose whether to attack or switch)
      "select-pokemon": "Which Pokemon will you use?", // choose another Pokemon from team
      "select-pokemon-move": "Which attack will you use?" // choose a move by their current Pokemon
    };

    const default_move = "select-move";

    const INITIAL_STATE = {
      // existing code here..

      // add these:
      move: default_move,
      move_display_text: move_display_text[default_move],
      opponent_team: [],
      opponent_pokemon: null // currently selected pokemon by opponent 
    };

Next, add the reducers that will process the actions. Add these before the default condition of the switch statement:

    case SET_OPPONENT_TEAM: // for setting the opponent's team
      return { ...state, opponent_team: action.team };

    case SET_MOVE: // for setting the controls currently displayed in the user's screen
      const { move } = action; 
      return { ...state, move, move_display_text: move_display_text[move] };

    case SET_OPPONENT_POKEMON: // for setting the opponent's current Pokemon
      const opponent_pokemon = action.pokemon
        ? action.pokemon
        : state.opponent_team[0]; // if the action didn't pass a Pokemon, use the first Pokemon in the opponent's team instead
      return { ...state, opponent_pokemon };

    case SET_OPPONENT_POKEMON_HEALTH: // for updating the opponent's current Pokemon's health
      let opponent_team = [...state.opponent_team];
      opponent_team = opponent_team.map(item => {
        if (item.team_member_id == action.team_member_id) {
          item.current_hp = action.health;
        }
        return item;
      });

      return { ...state, opponent_team };

    case REMOVE_POKEMON_FROM_OPPONENT_TEAM: // for removing a specific Pokemon from opponent's team after it faints (when its HP goes below 1)
      const diminished_opponent_team = [...state.opponent_team].filter(item => {
        return item.team_member_id != action.team_member_id;
      });

      return { ...state, opponent_team: diminished_opponent_team };

Battle screen

The battle screen is where the user battles a random opponent. As mentioned earlier, we’re only going to generate a random Pokemon team and let the user attack each Pokemon in the opponent team one by one. Start by importing all the necessary packages, data, actions, and helper functions:

    // src/screens/BattleScreen.js

    import { connect } from "react-redux";
    import pokemon_data from "../data/pokemon_data.js";
    import moves_data from "../data/moves_data";

    import uniqid from "../helpers/uniqid";
    import randomInt from "../helpers/randomInt";
    import shuffleArray from "../helpers/shuffleArray";

    import { setOpponentTeam, setOpponentPokemon, setMove } from "../actions";

Next, scroll down to the part where the component class is exported and add the following code before it. These are the data from the store that we’re going to need:

    const mapStateToProps = ({ battle }) => {
      const {
        team,
        move,
        move_display_text,
        pokemon,
        opponent_team,
        opponent_pokemon
      } = battle;
      return {
        team,
        move,
        move_display_text,
        pokemon,
        opponent_team,
        opponent_pokemon
      };
    };

Next, add the functions that will dispatch the actions for setting what the user sees in their controls UI, setting the opponent team, and setting the opponent Pokemon:

    const mapDispatchToProps = dispatch => {
      return {
        backToMove: () => {
          dispatch(setMove("select-move"));
        },
        setOpponentTeam: team => {
          dispatch(setOpponentTeam(team));
        },
        setOpponentPokemon: pokemon => {
          dispatch(setOpponentPokemon(pokemon));
        }
      };
    };

Don’t forget to pass those functions when exporting the component:

    export default connect(
      mapStateToProps,
      mapDispatchToProps
    )(BattleScreen);

Once the component is mounted, this is where we generate the data for the random team:

    componentDidMount() {

      const { setOpponentTeam, setOpponentPokemon } = this.props;

      let random_pokemon_ids = [];
      for (let x = 0; x <= 5; x++) {
        random_pokemon_ids.push(randomInt(1, 54));
      }

      let opposing_team = pokemon_data.filter(item => {
        return random_pokemon_ids.indexOf(item.id) !== -1;
      });

      opposing_team = opposing_team.map(item => {
        let hp = 500;

        let shuffled_moves = shuffleArray(item.moves);
        let selected_moves = shuffled_moves.slice(0, 4);

        let moves = moves_data.filter(item => {
          return selected_moves.indexOf(item.id) !== -1;
        });

        let member_id = uniqid();

        return {
          ...item,
          team_member_id: member_id,
          current_hp: hp,
          total_hp: hp,
          moves: moves,
          is_selected: false
        };
      });

      // update the store with the opponent team and current opponent Pokemon
      setOpponentTeam(opposing_team);
      setOpponentPokemon(opposing_team[0]);

    }

Next, we render the UI for the battle screen. Start by extracting all the data and functions that we need from the store:

    render() {
      const {
        team,
        move,
        move_display_text,
        pokemon,
        opponent_pokemon,
        backToMove
      } = this.props;

      // next: add code for returning the Battle screen UI
    }

Next, return the UI. The battle screen is divided into two sections: battleground and controls:

    return (
      <View style={styles.container}>
        <CustomText styles={[styles.headerText]}>Fight!</CustomText>

        <View style={styles.battleGround}>
          // next: render Pokemon and opponent Pokemon UI
        </View>

        <View style={styles.controls}>
          // next: add battle controls UI
        </View>
      </View>
    );

The battleground section displays both the user’s and their opponent’s current Pokemon, along with their health points. This uses the pre-created HealthBar and PokemonFullSprite components:

    {opponent_pokemon && (
      <View style={styles.opponent}>
        <HealthBar
          currentHealth={opponent_pokemon.current_hp}
          totalHealth={opponent_pokemon.total_hp}
          label={opponent_pokemon.label}
        />
        <PokemonFullSprite
          pokemon={opponent_pokemon.label}
          spriteFront={opponent_pokemon.front}
          spriteBack={opponent_pokemon.back}
          orientation={"front"}
        />
      </View>
    )}

    {pokemon && (
      <View style={styles.currentPlayer}>
        <HealthBar
          currentHealth={pokemon.current_hp}
          totalHealth={pokemon.total_hp}
          label={pokemon.label}
        />

        <PokemonFullSprite
          pokemon={pokemon.label}
          spriteFront={pokemon.front}
          spriteBack={pokemon.back}
          orientation={"back"}
        />
      </View>
    )}

The controls section displays the options that the user can select to control what their move is going to be (either attack with their current Pokemon or switch to another one from their team). These are the default controls that the user is going to see. As you’ve seen in the battle reducer file earlier, this is controlled by the current value of move. By default, it is set to select-move which renders the main menu. If the user chose to attack, the value of move is updated to select-pokemon-move, thus displaying the MovesList component. On the other hand, if the user chose to switch Pokemon, the value of move is updated to select-pokemon, which displays the PokemonList component. Lastly, if move is either select-pokemon or select-pokemon-move, a back button is displayed. If the user clicks on it, it calls the backToMove function which dispatches an action to update the value of move back to select-move. This basically brings the user back to the control UI’s main menu:

    <View style={styles.controlsHeader}>
      {(move == "select-pokemon" || move == "select-pokemon-move") && (
        <TouchableOpacity
          style={styles.backButton}
          onPress={() => {
            backToMove();
          }}
        >
          <Ionicons name="md-arrow-round-back" size={20} color="#333" />
        </TouchableOpacity>
      )}

      <CustomText styles={styles.controlsHeaderText}>
        {move_display_text}
      </CustomText>
    </View>

    {move == "select-move" && <ActionList />}

    {move == "select-pokemon" && (
      <PokemonList
        data={team}
        scrollEnabled={false}
        numColumns={2}
        action_type={"switch-pokemon"}
      />
    )}

    {pokemon &&
      move == "select-pokemon-move" && (
        <MovesList moves={pokemon.moves} />
      )}

Dispatch actions for fighting and switching Pokemon

Next, we need to update the ActionList component so it dispatches the relevant actions that will update the controls UI. Start by importing connect from react-redux and the setMove action:

    // src/components/ActionList/ActionList.js

    import { connect } from "react-redux";
    import { setMove } from "../../actions";

Next, add the setMove function so you can dispatch the similarly named action:

    const mapDispatchToProps = dispatch => {
      return {
        setMove: move => {
          dispatch(setMove(move));
        }
      };
    };

    export default connect(
      null,
      mapDispatchToProps
    )(ActionList);

Lastly, call the setMove function on each of the action function. Pass the value you want the move to be:

    const data = [
      {
        label: "Fight",
        action: () => { // function to execute when the fight button is clicked
          setMove("select-pokemon-move"); // add this
        }
      },
      {
        label: "Switch",
        action: () => { // function to execute when the switch button is clicked
          setMove("select-pokemon"); // add this
        }
      }
    ];

Dispatch the action for switching to a specific Pokemon

At this point, the user can now view the attacks of the current Pokemon, as well as the list of Pokemon in their team. This time, we need to add the code that will update the UI when an attack is made, or when the user switches to another Pokemon. Start by importing the actions:

    // src/components/PokemonOption/PokemonOption.js

    import { selectPokemon, setPokemon, setMove } from "../../actions";

Next, update mapDispatchToProps to include the functions that will set the current Pokemon, and going back to the initial UI of the controls section:

    const mapDispatchToProps = dispatch => {
      return {
        // existing code here..

        // add these:
        setPokemon: pokemon => {
          dispatch(setPokemon(pokemon)); // for setting the current Pokemon
        },
        backToMove: () => {
          dispatch(setMove("select-move")); // for showing the initial controls UI (the Fight or Switch buttons)
        }
      }
    }

Lastly, update the onPress handler to include the switch-pokemon condition:

    onPress={() => {
      if (action_type == "select-pokemon") {
        // existing code here...
      } else if (action_type == "switch-pokemon") { // add these
        setPokemon(pokemon_data); // use the pokemon data passed from the PokemonList component
        backToMove();
      }
    }}

Dispatch action for updating opponent Pokemon’s health

The final step is for us to update the opponent Pokemon’s health when the user chooses a move to attack with. Import the following actions, and the helper function for getting the move effectiveness and the actual damage:

    // src/components/MovesList/MovesList.js

    import { connect } from "react-redux";
    import {
      setOpponentPokemonHealth, // for setting the current opponent Pokemon's health
      removePokemonFromOpponentTeam, // for removing the current opponent Pokemon from the opponent team
      setOpponentPokemon, // for setting the current opponent Pokemon after the previous one has fainted
      setMove // for going back to the initial controls UI after the opponent Pokemon has fainted
    } from "../../actions";

    import getMoveEffectivenessAndDamage from "../../helpers/getMoveEffectivenessAndDamage";

Next, map the current opponent_pokemon as a prop. This gives us access to the opponent Pokemon’s current health points, type defenses, and team member ID. This allows us to calculate the damage made by the attack by passing those data to the getMoveEffectivenessAndDamage function:

    const mapStateToProps = ({ battle }) => {
      const { opponent_pokemon } = battle;

      return {
        opponent_pokemon
      };
    };

Next, add the functions that will dispatch the actions that we imported earlier:

    const mapDispatchToProps = dispatch => {
      return {
        setOpponentPokemonHealth: (team_member_id, health) => {
          dispatch(setOpponentPokemonHealth(team_member_id, health));
        },

        removePokemonFromOpponentTeam: team_member_id => {
          dispatch(removePokemonFromOpponentTeam(team_member_id));
        },

        setOpponentPokemon: () => {
          dispatch(setOpponentPokemon());
        },
        setMove: move => {
          dispatch(setMove(move));
        }
      };
    };

Finally, update the onPress function so it calculates the damage done by an attack, as well as return a description of how effective the attack is (examples: no effect, not very effective, super effective):

    onPress={() => {
      let { damage } = getMoveEffectivenessAndDamage(
        item,
        opponent_pokemon
      );
      let health = opponent_pokemon.current_hp - damage;

      setOpponentPokemonHealth(opponent_pokemon.team_member_id, health); // update the opponent Pokemon's health

      if (health < 1) { // opponent Pokemon has fainted
        removePokemonFromOpponentTeam(opponent_pokemon.team_member_id);

        setMove("select-move"); // go back to the initial controls UI
        setOpponentPokemon(); // set the opponent Pokemon (if there's still one left)
      }

    }}

Conclusion

In this tutorial, we’ve created a Pokemon battle game app using React Native and Redux. Along the way, you’ve strengthened your basic Redux knowledge by building an app that makes use of all the basic Redux concepts.

Stay tuned for the second part where we will implement the two-player mode, so the users actually get to battle another human.

You can find the full source code of the app on this GitHub repo. The code added to this specific part of the series is on the practice branch.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.