Chapter 4c - Objects and iterating
Records with dictionariesβ
A dictionary stores named fields β useful for items, enemies, and save data without writing a full class yet.
var slime = {"name": "Slime", "hp": 30, "atk": 5}
print(slime["name"])
print(slime.hp) # same field, dot form
slime.hp -= 10
print(slime.hp)
π§ͺ Try a dict mob
Classes β fields and methodsβ
A class groups data and functions that belong together. Methods are functions on the instance; they use self implicitly for fields.
class Hero extends RefCounted:
var name: String = "Ada"
var hp: int = 20
func take_hit(dmg: int) -> int:
hp = maxi(0, hp - dmg)
return hp
var h = Hero.new()
h.take_hit(7)
print(h.hp) # 13
π§ͺ Try a class
Hero.new() creates one instance. Two heroes do not share hp β each object has its own fields.
Mini quiz β objectsβ
Objects
1 / 3How do you create an instance of class Hero?
Pick an answer to see if you are right.
Iterating over collectionsβ
Combine for with arrays of dicts or objects. Each pass binds one element.
var party = [
{"name": "Ada", "hp": 12},
{"name": "Lin", "hp": 0},
{"name": "Sam", "hp": 8},
]
var alive = 0
for member in party:
if member.hp > 0:
alive += 1
print(alive) # 2
π§ͺ Count the living
With class instances the loop looks the same β for hero in heroes: then hero.hp.
Challenge: party HP totalβ
Write total_hp(party) so it returns the sum of every member's hp.
Each member is a dictionary with an "hp" field. Use a loop β do not hard-code a single sum.
Hidden tests send space-separated HP values; the wrap builds the party dicts for you.
Indent with 4 spaces. Click Reset if an old draft looks flat.
Exercisesβ
Build a dict, give a class a method, then filter while iterating.
Create a dictionary with "name" set to "potion" and "qty" set to 3. Print name, then qty, each on its own line.
potion
3