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
battleResultisTrue- Increase the number of
matchesfor the trainer's pokemon by1(use+=arithmetic operator to keep the code clean). To access the trainer's pokemon, usetrainerToPokemonmapping with first key asmsg.senderand second key aspokemonIndex. - Increase the number of
winsfor the trainer's pokemon by1(use+=arithmetic operator to keep the code clean). - Create a new variable named
newPokemonof typePokemonand assign its value to a new Pokemon created using thePokemonstruct and use the following parameters:- name:
newPokemonName - dna:
newPokemonDNA - HP:
newPokemonHP - matches:
1(as the wild pokemon just had a match) - wins:
0
- name:
- Add this
newPokemonto thepokemonListmapping using the keytotalPokemonCount. - Increase the
totalPokemonCountby1. - Add the
newPokemontotrainerToPokemonmapping using the first key asmsg.senderand the second key astrainerPokemonCount[msg.sender]. - Increment
trainerPokemonCount[msg.sender]by1using+=arithmetic operator. - Fire the
NewPokemonCreatedevent with following parameters:newPokemonName,newPokemonDNA,newPokemonHP.
- Increase the number of
-
If
battleResultisFalseIncrease the number ofmatchesfor 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!