Numbers are the most common values in a game — a score, an x position, a countdown. They can be whole (7) or have decimals (3.5), and you do maths on them with a handful of symbols.
1. The arithmetic operators
+add —2 + 3is5.-subtract —10 - 4is6.multiply —53is15./divide —12 / 4is3.%remainder (modulo) —7 % 3is1, what is left over after dividing.
See them run:
function draw() {
cls(1);
print('2 + 3 = ' + (2 + 3), 8, 8, 7);
print('5 * 3 = ' + (5 * 3), 8, 20, 7);
print('12 / 4 = ' + (12 / 4), 8, 32, 7);
print('7 % 3 = ' + (7 % 3), 8, 44, 7);
}💡
Wrap the maths in parentheses inside a print, like above. The + between the label and the parentheses joins text, while the + inside the parentheses adds. Without the parentheses the number would be glued on as text instead of added.
2. Build on a variable
Mix numbers with variables to compute things. % is especially handy for wrapping a value back to 0 — here a counter that cycles 0, 1, 2, 3, 0, 1, …:
let tick = 0;
function update() {
tick = tick + 1;
}
function draw() {
cls(1);
print('tick: ' + tick, 8, 8, 7);
print('cycles 0-3: ' + (tick % 4), 8, 20, 11);
}3. Handy number helpers
GameSpark gives you helpers for common number jobs:
flr(3.7)rounds down to3(floor).rnd(5)gives a random number from 0 up to (not including) 5.abs(-4)is4— the distance from zero.min(a, b)/max(a, b)pick the smaller / larger.
function draw() {
cls(1);
print('flr(3.7) = ' + flr(3.7), 8, 8, 7);
print('abs(-4) = ' + abs(-4), 8, 20, 7);
print('max(2, 9) = ' + max(2, 9), 8, 32, 7);
}🎯
Try it: show 10 - score. Roll a dice with flr(rnd(6)) + 1 (1–6). Move a dot that wraps around with x = (x + 1) % 128.
What you learned
- Numbers can be whole or decimal; do maths with
+ - * / %. %is the remainder — great for cycling a value back to 0.- Parenthesise maths inside
printso+adds instead of joining text. - Helpers like
flr,rnd,abs,min,maxcover common number jobs.