Lesson: Introduction to SmartPy

Ask Question

Chapter 11

Tinkering with maps in SmartPy


Let us quickly understand how maps are handled under the hood in SmartPy!

In the later half of the chapter, you will adding the ability to shoot as well as the ability to record alien kills!


Study Time:


Maps are containers that store elements formed by a combination of a key and a mapped value. An example:

{“a”: 1, “b”: 2} 

You might recognize the familiarity with Python’s dictionaries.

Maps are represented by type sp.TMap(key, value) in SmartPy.

## record_alien_kills is a variable that 
## records your kill count for various types of aliens. 
            record_alien_kills = {
                    "simple_alien": sp.nat(0), 
                    "boss_alien": sp.nat(0)

## Update simple_alien_kill_count by 1. 
self.data.record_alien_kills["simple_alien"] += 1  

## You can also explicitly give map type by doing the following:
self.init(record_alien_kills = sp.map({...}) )


  1. Since we know beforehand that kill counts cannot be negative, kill counts are given the type sp.TNat using sp.nat
  2. As you can see, map is a container data type that can hold simple data types like strings, int, boolean etc.
  3. By that logic, the inferred type of record_alien_kills is sp.TMap(sp.TString, sp.TNat)
  4. You can read more in depth about how SmartPy handles maps here.

#buidl-ing time:

New Feature request:

Your Cryptobot seems to be missing it’s most important ability: the ability to kill!

Without it your cryptobot is as good as dead 💀

Let’s also add the ability to record alien kills. This is going to be important to analyze how your Cryptobot is fairing in respect to other Cryptobot’s in the world.

Step-by-step walkthrough:

  1. Add plasma_bullet_count to our contract’s storage and initialize with 5 bullets.

  2. Add record_alien_kills to our contract’s storage and initialize with:

    • key simple_alien and it’s value as 0 of type sp.TNat

    • key boss_alien and it’s value as 0 of type sp.TNat

  3. Complete the shoot_alien function’s code by adding code:

    • to reduce plasma_bullet_count by 1.
    • use alien_type argument as key to access it’s value in record_alien_kills map and increase it by 1.

Testing our code:

Let us test our shoot_alien function by shoot 2 plasma bullets, 1 aimed at simple alien and 1 aimed towards boss alien respectively:

  1. Call shoot_alien and pass it the value of “simple_alien”
  2. Call shoot_alien and pass it the value of “boss_alien”

When you’re finished:

  1. Click on “Check” to check your submission with the correct answer.
  2. Click on “Show Answer” in case you get stuck.

You can also tinker around with the final code on SmartPy’s online IDE. Try running the test by clicking on the ▶️ button!