Skip to main content

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​

Quiz

Variables

1 / 3

Which declares an integer variable?

var n: int = 3

Pick an answer to see if you are right.

Common types​

TypeExample
int42
float3.14
booltrue / 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).

Indentation

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.

Activity: HP line

Create var hp: int = 12 and print HP=12 (use the variable; do not only print the literal string).

HP=12