Chapter 4b - Functions
Why functionsβ
A function packages a piece of work behind a name. Game code calls the same ideas often β damage, healing, formatting a HUD line β so you write them once and reuse them.
func double(n: int) -> int:
return n * 2
print(double(7)) # 14
π§ͺ Try it
Anatomyβ
func name(param: Type) -> ReturnType:
# body
return value
| Piece | Role |
|---|---|
func | Starts a function |
| parameters | Inputs the caller passes in |
-> Type | Optional return type (recommended in lessons) |
return | Sends a result back to the caller |
Call a function with parentheses: double(7). Without (), you only mention the function β you do not run it.
Mini quiz β functionsβ
Functions
1 / 3What does return do?
Pick an answer to see if you are right.
Multiple parameters and defaultsβ
Pass several values, separated by commas. Default arguments fill in when the caller omits them.
func heal(hp: int, amount: int = 5, max_hp: int = 100) -> int:
return mini(max_hp, hp + amount)
print(heal(90)) # 95 β amount defaults to 5
print(heal(90, 20)) # 100 β capped by max_hp
π§ͺ Try defaults
Functions calling functionsβ
Small helpers compose. Keep each function focused β one job is easier to test.
func armor_block(dmg: int, armor: int) -> int:
return maxi(0, dmg - armor)
func apply_hit(hp: int, dmg: int, armor: int) -> int:
return maxi(0, hp - armor_block(dmg, armor))
π§ͺ Try composition
Challenge: apply hitβ
Write apply_hit(hp, dmg, armor) so it:
- Reduces damage by
armor(damage cannot go below0) - Subtracts that from
hp(hpcannot go below0) - Returns the new HP
Example: hp=20, dmg=8, armor=3 β blocked damage is 5 β result 15.
Indent with 4 spaces. Click Reset if an old draft looks flat.
Exercisesβ
Warm up with a pure return, format a status string, then clamp a value into a range.
Write triple(n) so it returns n * 3.
21