Skip to content

Latest commit

 

History

History
68 lines (47 loc) · 2.15 KB

init.md

File metadata and controls

68 lines (47 loc) · 2.15 KB

Chapter 4: Init Function

Our contract will create random pokemons with which a trainer can battle with. So, we need a list of pokemon names from which we will select a random pokemon for battle.

We need a way to store a list of pokemon names once when we initialize our contract. For this purpose, we will use the __init__ function.

The __init__ Function

__init__ is a special initialization function that may only be called at the time of deploying a contract. It can be used to set initial values for storage variables. A common use case is to set an owner variable with the creator the contract:

owner: address

@internal
def __init__():
    self.owner = msg.sender

You cannot call to other contract functions from the __init__ function.

Put it to the test

We will add a list of 20 pokemons in the __init__ function.

  1. Define the __init__ function.

  2. Add @internal decorator to the __init__ function.

  3. Add the following code in the __init__ function body:

    self.pokemonNames[0] = "Bulbasaur"
    self.pokemonNames[1] = "Charmander"
    self.pokemonNames[2] = "Charizard"
    self.pokemonNames[3] = "Squirtle"
    self.pokemonNames[4] = "Blastoise"
    self.pokemonNames[5] = "Pidgey"
    self.pokemonNames[6] = "Raticate"
    self.pokemonNames[7] = "Pikachu"
    self.pokemonNames[8] = "Raichu"
    self.pokemonNames[9] = "Venomoth"
    self.pokemonNames[10] = "Arcanine"
    self.pokemonNames[11] = "Abra"
    self.pokemonNames[12] = "Machop"
    self.pokemonNames[13] = "Golem"
    self.pokemonNames[14] = "Onix"
    self.pokemonNames[15] = "Hypno"
    self.pokemonNames[16] = "Rhydon"
    self.pokemonNames[17] = "Kangaskhan"
    self.pokemonNames[18] = "Scyther"
    self.pokemonNames[19] = "Mewtwo"

** Template **

embedded-code

** Solution **

embedded-code-final

** Previous Chapter Solution **

embedded-code-previous