In the previous chapter we called the battle
function of the wild pokemon contract from the trainer contract.
We handled multiple return values from the battle
function using a tuple. Now we will use the tuple variables alter the state of the trainer contract.
As we discussed in previous chapters, if a trainer's pokemon wins a battle with a wild pokemon, the trainer captures the wild pokemon. If the trainer's pokemon loses, trainer gets nothing.
As we discussed we have 2 conditions based on the battleResult
variable. If battleResult
is True
that means the trainer's pokemon has won, otherwise (in case of False
) the trainer's pokemon loses.
-
Create an if/else statement with the condition as
battleResult
. -
If
battleResult
isTrue
- Increase the number of
matches
for the trainer's pokemon by1
(use+=
arithmetic operator to keep the code clean). To access the trainer's pokemon, usetrainerToPokemon
mapping with first key asmsg.sender
and second key aspokemonIndex
. - Increase the number of
wins
for the trainer's pokemon by1
(use+=
arithmetic operator to keep the code clean). - Create a new variable named
newPokemon
of typePokemon
and assign its value to a new Pokemon created using thePokemon
struct and use the following paramters:- name:
newPokemonName
- dna:
newPokemonDNA
- HP:
newPokemonHP
- matches:
1
(as the wild pokemon just had a match) - wins:
0
- name:
- Add this
newPokemon
to thepokemonList
mapping using the keytotalPokemonCount
. - Increase the
totalPokemonCount
by1
. - Add the
newPokemon
totrainerToPokemon
mapping using the first key asmsg.sender
and the second key astrainerPokemonCount[msg.sender]
. - Increment
trainerPokemonCount[msg.sender]
by1
using+=
arithmetic operator. - Fire the
NewPokemonCreated
event with following parameters:newPokemonName
,newPokemonDNA
,newPokemonHP
.
- Increase the number of
-
If
battleResult
isFalse
Increase the number ofmatches
for the trainer's pokemon by1
(use+=
arithmetic operator to keep the code clean).
Congratulations 🎉
You have completed the Chapter 2 and the trainers can battle and capture wild pokemons ⚔️
Tweet about it to share your amazing feat!