Chapter 2a - Variables
Variablesβ
Use var to store a value. Type annotations are optional but helpful in game code where hp should stay an int.
var score = 10
var name: String = "Ada"
var ready: bool = true
π§ͺ Try it
You can reassign a var. That is how combat updates HP and inventory changes.
var hp = 20
hp = hp - 5
hp -= 2 # same idea, shorter
π§ͺ Try reassignment
Mini quiz β variablesβ
Variables
1 / 3Which declares an integer variable?
var n: int = 3
Pick an answer to see if you are right.
Common typesβ
| Type | Example |
|---|---|
int | 42 |
float | 3.14 |
bool | true / false |
String | "hello" |
str(x) turns a value into a string. % formatting works like older Python β useful for HUD labels:
var hp = 7
print("HP: %s" % hp)
print("%s has %s coins" % ["Ada", 3])
π§ͺ Try it
You can also build strings with + after converting numbers:
var coins = 15
print("coins=" + str(coins))
Challenge: format a labelβ
Print exactly Player: Neo using a String variable for the name (do not hard-code the whole line as a single literal with no variable).
Indent with 4 spaces. Click Reset if an old draft looks flat.
Constantsβ
const values cannot be reassigned β good for caps like max HP or inventory slots.
const MAX_HP := 100
:= infers the type from the value.
π§ͺ Try const
Exercisesβ
Work these in order: first a single variable, then math on variables, then a multi-field status line.
Create var hp: int = 12 and print HP=12 (use the variable; do not only print the literal string).
HP=12