GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 2

Numbers

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

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:

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