Language Reference

Axxy v1

A turtle-graphics drawing language for motion, fills, procedures with parameters, variables, arrays, events, multiple axolotls, and sprite stamping — running live in Axxy Studio.

🐾 Turtle graphics 🔁 Loops & conditions đŸ“Ļ Procedures with params đŸŽ¯ Events đŸ–ŧ Sprites & stamps 🐙 Multiple axolotls 🧭 Vectors & objects ⚡ Instant / draw-loop mode
01

Overview

Axxy programs move an axolotl around a canvas, leaving a trail of lines. Commands are one per line. Blocks open with { and close with }.

Coordinate system

The default canvas is 600 × 500 px. X increases right, Y increases downward. The centre is roughly (300, 250). home always returns to the exact pixel centre of whatever canvas size is set.

Heading

0° points right, 90° points down, 180° points left, 270° points up. right increases the heading (clockwise), left decreases it.

â„šī¸
One command per line Axxy parses one command per line. Blank lines and indentation are ignored. Keeping one statement per line gives the most useful error messages.
âš ī¸
Event block placement on start, on key, on click, on broadcast, and on draw must be top-level blocks — never inside loops or other blocks.
comment A complete Axxy program — draws a square
setbgcolor #f0f6ff
setcolor   #2b5fff
setweight  3
home

repeat 4 {
  forward 100
  right   90
}
02

Syntax & Structure

Axxy is whitespace-sensitive at the line level. Each non-blank line is one command — a keyword followed by its arguments separated by spaces.

Comments

The comment keyword ignores everything after it on that line. Double-slash // also works as an inline comment.

comment This draws a triangle
forward 80 // also a comment

Blocks

Block commands (repeat, if, while, proc, events, etc.) open their body with { on the same line and close with } on its own line. Blocks nest freely.

repeat 8 {
  forward 60
  if $count == 4 {
    randomcolor
  }
  right 45
}

Variable declarations in code mode

Variables are declared at the top of a program before procedures and main code. The full syntax is:

var score  number  0
var name   string  "axxy"
var gem    sprite
var pts    array   []

comment Shorthand — type defaults to number
var size 80

comment Array shorthand
array pts

Arithmetic — mathset only

Arithmetic is evaluated exclusively inside mathset. See Math Operators for the full operator list including ^, min, and max.

mathset area   $side * $side
mathset half   $total / 2
mathset power  $base ^ 2
mathset bigger $a max $b
03

Values & Variables

Variables hold numbers, strings, or arrays. Sprite variables are placeholders for uploaded images. Declare with var in source, or create at runtime with define. Read anywhere with a $ prefix.

Reading a variable

forward  $size
setcolor $ink
repeat   $count {
  right 15
}
💡
Scope Variables declared at the top level are globally accessible, including inside procedures. Procedure parameters create a local scope — they shadow global variables of the same name within that proc. See Procedures.

Variable commands

CommandEffectExample
var name valueDeclare a number variable before execution. Type defaults to number.var step 20
var name type valueDeclare with an explicit type: number, string, sprite, array.var msg string "hi"
define name valueCreate or overwrite a variable at runtime.define temp 0
setvar name valueAssign a new value to an existing variable.setvar step 50
changevar name amountAdd amount to the variable (negative to subtract).changevar step -5
mathset name a op bCompute and store an arithmetic result.mathset area $w * $h
showvar nameShow the variable value as a canvas overlay badge.showvar score
hidevar nameRemove the overlay badge.hidevar score

Colours in code mode

Colour commands (setcolor, setfillcolor, setbgcolor) accept either a hex code or three separate RGB values 0–255:

setcolor #ff3366          comment hex
setcolor 255 51 102       comment same colour as RGB
setbgcolor 240 246 255     comment light blue background
04

Procedures

Procedures package reusable drawing logic. Define with proc, call anywhere with call. Procedures can accept named parameters and call each other recursively.

Basic definition

proc hexagon {
  repeat 6 {
    forward 60
    right   60
  }
}

call         hexagon   comment error if not defined
callifexists helper   comment silently skips if missing

Procedures with parameters

List parameter names after the procedure name. Each parameter becomes a local variable inside the procedure — it shadows any global with the same name. Pass values when calling with call.

proc polygon sides len {
  var turn 0
  mathset turn 360 / $sides
  repeat $sides {
    forward $len
    right   $turn
  }
}

call polygon 5  70    comment pentagon, side 70
call polygon 6  55    comment hexagon, side 55
call polygon 3  90    comment triangle, side 90
💡
Parameter scope Parameters are local to the procedure call — changing them inside the proc does not affect any global variable of the same name. Non-parameter variables inside a proc read and write the global scope as normal.

Recursion

A procedure can call itself. Always include a base-case if guard. The engine allows up to 256 levels of procedure nesting before throwing an error.

proc branch len {
  if $len > 8 {
    forward  $len
    left     28
    mathset  sub $len * 0.65
    call     branch $sub
    right    56
    call     branch $sub
    left     28
    backward $len
  }
}

penup  goto 300 460  pendown
left   90
call   branch 80
05

Motion

Move and turn the active axolotl. Lines are drawn whenever the pen is down and line weight is greater than 0.

forward distance
motion

Move forward by distance pixels in the current heading. Draws a line if pen is down. Negative distance moves backward.

forward 100
forward $step
forward -30   comment same as backward 30
backward distance
motion

Move in the opposite direction to the current heading. Equivalent to forward -distance.

left angle  /  right angle
motion

Rotate by angle degrees without drawing. right turns clockwise (increases heading); left turns counter-clockwise.

goto x y
motion

Jump to canvas coordinates. If the pen is down a straight line is drawn to the destination. Use penup first to teleport silently. Does not change the heading.

penup
goto 100 400
pendown
setx x  /  sety y
motion

Change only one axis of the position, leaving the other unchanged.

setheading angle
motion

Set the heading to an absolute angle in degrees. Useful for resetting direction precisely without accumulated rounding errors.

setheading 0    comment face right
setheading 270  comment face up
setheading $angle
home
motion

Jump to the canvas centre (canvasW/2, canvasH/2) and reset heading to 0. Pen state is unchanged — if the pen is down a line is drawn back to the centre.

arcleft radius sweep  /  arcright radius sweep
motion

Draw a curved arc. The axolotl moves along an arc of the given radius, turning through sweep degrees. arcright curves clockwise; arcleft curves counter-clockwise. The heading changes by sweep degrees at the end.

comment Full circle using four quarter-arcs
repeat 4 { arcright 50 90 }

comment Petal shape: two facing arcs
arcright 50 80
right    100
arcright 50 80
right    180
06

Pen & Drawing

Control lines, fills, colours, stamps, and the canvas.

penup  /  pendown
pen

Lift or lower the pen. With pen up, movement does not draw. pentoggle up and pentoggle down are also valid.

setcolor color
pen

Set the stroke colour. Accepts a hex code or three separate R G B values (0–255). Also accepts CSS colour names.

setcolor #e8456a
setcolor 232 69 106  comment same as above
setcolor $inkColor
randomcolor          comment random colour
setfillcolor color
pen

Set the fill colour for beginfill / endfill. Same colour format as setcolor.

setweight pixels
pen

Set the line thickness in pixels. Default is 2. Setting weight to 0 disables line drawing entirely (movement still happens).

setopacity 0–100
pen

Set opacity. 100 is fully opaque; 0 is invisible. Applies to both lines and fills. Useful for layering translucent shapes.

beginfill  /  endfill
pen

beginfill starts recording path vertices. Every move command adds vertices. endfill closes the shape and renders it filled with the current fill colour. The stroke is also drawn if weight > 0.

setcolor     #1d4ed8
setfillcolor #60a5fa
beginfill
repeat 6 {
  forward 70
  right   60
}
endfill
stamp
pen

Stamp the current stamp image at the axolotl's position, rotated to match the heading. The stamp is coloured with the current pen colour. Configure with setstamp or usesprite.

setstamp mode shape size
pen

Configure the stamp. mode is one of: turtleSprite (the axolotl image), uploadedSprite (the currently uploaded sprite file), shape (a built-in shape). When mode is shape, available shapes are: triangle, square, circle, diamond, star.

setstamp shape        star     28
setstamp shape        circle   20
setstamp turtleSprite triangle 32  comment axolotl image
cleardrawing
pen

Erase everything on the drawing layer. Position, heading, and pen settings are unchanged.

setbgcolor color
pen

Change the canvas background colour and clear the drawing layer. Accepts hex or RGB values like setcolor.

showaxolotl  /  hideaxolotl
pen

Show or hide the axolotl cursor sprite. Hiding is useful for clean geometric art. Aliases: showturtle / hideturtle.

07

Control Flow

Loops, waits, and flow interruptions. All loops have a safety limit of 10,000 iterations; the engine throws an error if exceeded.

repeat times { â€Ļ }
control

Run the body exactly times iterations. Inside the body, $count is the 1-based iteration number and $index is 0-based.

repeat 36 {
  forward 80
  right   10
}
for varName start end step { â€Ļ }
control

Loop with a named counter from start to end (inclusive), incrementing by step each iteration. The counter is readable as $varName inside the body. If step is 0, the engine automatically uses 1 when start ≤ end, or -1 when start > end.

comment Growing arc spiral
for r 5 120 6 {
  arcright $r 50
}

comment Count down
for i 10 1 -1 {
  forward $i
  right   36
}
while condition { â€Ļ }
control

Loop while the condition is true. Condition is checked before each iteration. If false on the first check the body never runs.

var d 200
while $d > 10 {
  repeat 4 { forward $d  right 90 }
  right   13
  mathset d $d * 0.85
}
repeatuntil condition { â€Ļ }
control

Loop until the condition becomes true. The body runs at least once; condition is checked after each iteration.

forever { â€Ļ }
control

Loop continuously. Include a wait or a tick yield to avoid locking the engine. Use break to exit, or click the Stop button. Safety stop fires after 10,000 iterations without a wait tick.

forever {
  right   3
  forward 4
  wait    16
}
wait milliseconds
control

Pause execution for the specified milliseconds. 1000 ms = 1 second. Also yields a frame, allowing the canvas to update and the safety stop to reset.

waituntil condition
control

Pause execution until the condition becomes true. The engine polls up to 20,000 times before throwing a safety error. Useful for waiting on a variable set by an event handler.

break
control

Exit the innermost loop immediately. Execution resumes after the loop's closing }.

return
control

Exit the current procedure immediately. Has no effect at the top level.

08

Conditions

Conditions appear inside if, ifelse, while, repeatuntil, and waituntil. A condition is either a comparison, a compound condition, or the literal true / false.

if condition { â€Ļ }
logic

Run the body only when the condition is true.

if $x > 400 { right 90 }

comment compound: and / or
if $count == 6 and $y < 300 { randomcolor }
if $n < 0 or $n > 100    { break }

comment negation
if not $score == 0 { forward 20 }
ifelse condition { â€Ļ } else { â€Ļ }
logic

Run the first body if the condition is true, otherwise run the else body.

ifelse $heading > 180 {
  setcolor #3b82f6
} else {
  setcolor #ef4444
}

Comparison operators

OperatorMeaningExample
==Equal$n == 0
!=Not equal$n != 5
>Greater than$x > 300
<Less than$y < 100
>=Greater than or equal$n >= 10
<=Less than or equal$count <= 5

Condition modes

SyntaxMeaning
$a op $bSimple comparison (default)
$a op $b and $c op $dBoth conditions must be true
$a op $b or $c op $dAt least one must be true
not $a op $bCondition must be false
trueAlways true (runs the block unconditionally)
falseAlways false (skips the block unconditionally)
09

Variables

Quick reference. See Values & Variables and Math Operators for full detail.

CommandDescription
var name valueDeclare a number variable (before execution).
var name type valueDeclare with explicit type: number, string, sprite, array.
array nameDeclare an empty array (shorthand).
define name valueCreate or overwrite at runtime.
setvar name valueAssign a new value to an existing variable.
changevar name amountAdd a value (negative to subtract).
mathset name a op bCompute: + - * / % ^ min max
showvar nameDisplay as canvas overlay.
hidevar nameRemove overlay.
10

Events

Event blocks must be top-level in the program. They register handlers that fire in response to user input or broadcasts. on draw only fires in Instant mode.

on start { â€Ļ }
events

Runs once when the program starts, before the main body. Use for setup: set background, draw title text, initialise variables.

on key keyName { â€Ļ }
events

Fires when the named key is pressed. Common names: space, up, down, left, right, a–z, 0–9, enter, escape. Inside the handler, $keychar holds the key character and $keycode holds the key code.

on key up    { forward  10 }
on key down  { backward 10 }
on key left  { left     15 }
on key right { right    15 }
on key r     { randomcolor }
on key c     { cleardrawing }
on click { â€Ļ }
events

Fires when the canvas is clicked. $eventx and $eventy hold the click coordinates.

on click {
  penup
  goto    $eventx $eventy
  pendown
  stamp
}
on broadcast "message" { â€Ļ }
events

Fires when a matching broadcast is sent. Multiple handlers can listen for the same message.

broadcast "message"
events

Send a broadcast message from anywhere in the program to trigger matching on broadcast handlers.

on draw { â€Ļ }
events

Fires every animation frame (~60 fps). Requires Instant mode to be enabled. Designed for real-time animation. The body runs synchronously so keep it fast — avoid wait inside. Stop with stopdraw.

comment Spinning arm animation — enable Instant mode first
var a 0

on draw {
  cleardrawing
  setbgcolor  #0f172a
  home
  setcolor    #f472b6
  setweight   3
  setheading  $a
  forward     110
  stamp
  changevar   a 2
}
on key space { stopdraw }
stopdraw
events

Stop the on draw frame loop. The canvas keeps its current state.

11

Arrays

Arrays are ordered lists of values. All indices are zero-based. The array itself must exist before commands can use it.

array name  /  var name array
array

Declare an empty array. Both forms are equivalent.

arraypush name value
array

Append value to the end of the array.

arrayset name index value
array

Overwrite the item at zero-based index.

arrayget name index targetVar
array

Read the item at index into targetVar. If the index is out of range the target receives 0.

arraypop name targetVar
array

Remove the last item from the array and store it in targetVar. If the array is empty, target receives 0.

arraylen name targetVar
array

Store the current length of the array in targetVar. Use this before a while loop to iterate over all items.

array     angles
arraypush angles 30
arraypush angles 90
arraypush angles 120
arraypush angles 60

arraylen  angles n
var       i 0
while $i < $n {
  arrayget  angles $i turn
  forward   80
  right     $turn
  changevar i 1
}
12

Multiple Axolotls

Any number of independent axolotls can exist simultaneously, each with its own position, heading, pen colour, fill colour, line weight, opacity, and visibility. The default axolotl is always named main. Aliases newturtle / useturtle also work.

newaxolotl name
turtle

Create a new axolotl at the canvas centre with default settings (pen down, colour #235390, weight 2). It immediately becomes the active axolotl.

useaxolotl name
turtle

Switch which axolotl is active. All subsequent motion and pen commands apply to it. useaxolotl main returns to the original.

cloneaxolotl newName
turtle

Copy the active axolotl — including its position, heading, and all pen settings — into a new named axolotl. The clone becomes active immediately.

removeaxolotl name
turtle

Remove a named axolotl from the scene. main cannot be removed. The active axolotl does not change automatically — call useaxolotl main if needed.

newaxolotl    a
newaxolotl    b

useaxolotl    a
setcolor      #f95858
penup  goto 180 250  pendown
repeat 36 { forward 80  right 170 }

useaxolotl    b
setcolor      #38a8ff
penup  goto 420 250  pendown
repeat 36 { forward 80  right 170 }

useaxolotl main
13

Sprites

Upload images in the Variables panel by creating a variable with type sprite, then clicking the upload area. Once loaded, reference the sprite by its variable name.

usesprite varName size
sprite

Switch the stamp to a named sprite variable at the given size (pixels). After calling this, stamp will draw that image. The sprite is scaled to fit within a size × size bounding box.

stampwithsprite varName
sprite

Stamp the named sprite at the current position without permanently switching the active stamp mode. The previous stamp configuration is preserved.

comment Requires sprite variable 'gem' in the Variables panel
usesprite gem 48
penup
repeat 12 {
  forward  110
  stamp
  backward 110
  right    30
}
14

Built-in Variables

These variables are always available without declaration. Read them with $. They are read-only — writing to them with setvar will silently do nothing because they are resolved from engine state, not from the variable store.

VariableTypeDescription
$xnumberActive axolotl's current x position.
$ynumberActive axolotl's current y position.
$headingnumberActive axolotl's current heading in degrees.
$indexnumberZero-based loop counter for the innermost repeat or for loop.
$countnumberOne-based loop counter for the innermost repeat or for loop.
$mousexnumberCurrent mouse x position over the canvas. Updates in real time.
$mouseynumberCurrent mouse y position over the canvas.
$mousedown0 or 11 while the primary mouse button is held; 0 otherwise.
$keycodenumberKey code of the last key pressed anywhere in the window.
$keycharstringCharacter text of the key that triggered the current on key handler.
$eventxnumberX coordinate of the click that triggered the current on click handler.
$eventynumberY coordinate of the click that triggered the current on click handler.
$canvaswnumberCanvas width in pixels.
$canvashnumberCanvas height in pixels.
$axolotlcountnumberTotal number of axolotls currently in the scene (including main).
comment Bounce off canvas edges using $x and $canvasw
var speed 3
forever {
  forward $speed
  if $x > $canvasw or $x < 0 {
    mathset speed $speed * -1
  }
  wait 16
}
15

Math Operators

All arithmetic is performed exclusively via mathset. Division by zero returns 0. Modulo by zero also returns 0.

OperatorMeaningExample
+Additionmathset total $a + $b
-Subtractionmathset diff $a - $b
*Multiplicationmathset area $w * $h
/Division (0 if divisor is 0)mathset half $n / 2
%Modulo (remainder)mathset rem $n % 4
^Exponentiation (power)mathset sq $n ^ 2
minSmaller of two valuesmathset low $a min $b
maxLarger of two valuesmathset high $a max $b
comment Hypotenuse of a right triangle
var a 60
var b 80
mathset a2 $a ^ 2
mathset b2 $b ^ 2
mathset sum $a2 + $b2
mathset hyp $sum ^ 0.5   comment square root via x^0.5
forward $hyp
16

Safety Limits

The engine enforces limits to prevent runaway programs from locking the browser.

LimitValueApplies to
Loop iterations10,000while, repeatuntil, forever, for
waitUntil polls20,000waituntil
Procedure nesting256 levelscall
Block nesting64 levelsAny block inside another block
Instant mode steps500,000Full program run in Instant mode
âš ī¸
Forever loop gotcha forever yields a frame between each iteration, which resets the safety counter. But a forever containing many thousands of draw operations per frame can still be slow — use Instant mode and on draw instead for smooth animation.
17

Console & Errors

The console panel below the canvas shows engine messages and your comment notes. Four severity levels.

LevelColourMeaning
errorredParse errors, undeclared procedures, exceeding safety limits. Execution stops.
warnamberInvalid argument values, unknown variables. The command is skipped; execution continues.
infoblueStatus messages (reset, sync, etc.). comment blocks appear here too.
successgreenSuccessful actions such as code sync.
Line 4:  Expected { after repeat
Line 9:  Unknown variable $score — command skipped.
Line 14: Procedure 'drawStar' not found.
18

Advanced Toolkit

Axxy now includes a more advanced graphics and structure layer for bigger projects. These commands are especially useful in Advanced mode, but they still use the same language underneath.

Transform commands

CommandDescriptionExample
pushtransformSave the current drawing transform.pushtransform
poptransformRestore the last saved drawing transform.poptransform
translate x yShift later drawing operations by an offset.translate 120 60
rotate angleRotate later drawing operations.rotate 45
scale x yScale later drawing operations.scale 1.5 1.5
resettransformReturn drawing transforms to normal.resettransform

Vectors

Vectors are stored as named variables with an x and y value. They are excellent for movement, motion systems, particles, steering, and simulation logic.

vector velocity 3 -2
vector position 320 240
vectorscale velocity velocity 0.98
movebyvector velocity
gotovector position
CommandDescription
vector name x yCreate a vector variable.
setvector name x yOverwrite a vector's values.
vectoradd target a bStore a + b in target.
vectorsub target a bStore a - b in target.
vectorscale target source amountScale a vector by a number.
vectormag vectorName targetVarStore the magnitude into a number variable.
vectornormalize target sourceStore a unit-length version of a vector.
vectordot targetVar a bStore the dot product into a number variable.
movebyvector nameMove the active axolotl by the vector amount.
gotovector nameMove the active axolotl to the vector position.

Objects

Objects are a lightweight way to bundle related state together for larger projects. Think of them as named containers with fields.

object player x number 300
object player name string "Axxy"
object player facing vector 1 0
objectset player x 340
objectget player x playerX
CommandDescription
object name field number valueCreate or define a numeric field.
object name field string "text"Create or define a text field.
object name field vector x yCreate or define a vector field.
objectset name field valueWrite a new value into a field.
objectget name field targetVarCopy a field value into a variable.
🧭
Mode note Beginner and Intermediate mode can hide some of these blocks in the studio, but the underlying project format stays compatible. A project made in Advanced mode can still be opened later in simpler modes.
19

Examples

Ready-to-run programs demonstrating common patterns. Each example can now run in place beside its code with play/stop controls, while still keeping a clean Load in Studio and Copy Code workflow.

01

Spiralling Star

A while loop gradually reduces the step length, creating a tightening star spiral with a colour shift on each pass.

setbgcolor #0a0a14
setweight  1.5
home
pendown

var d 240
var hue 0

while $d > 4 {
  setcolor  $hue 200 255
  forward   $d
  right     137.5
  mathset   d   $d - 0.9
  changevar hue 4
  if $hue > 255 { setvar hue 0 }
}
02

Nested Polygons

A procedure with two parameters draws any regular polygon. Nested for loops build a series with increasing rotation offsets.

proc poly sides len {
  var    turn 0
  mathset turn 360 / $sides
  repeat $sides {
    forward $len
    right   $turn
  }
}

setbgcolor #f0f6ff
setweight  1.5
home

for s 3 8 1 {
  setcolor   40 $s 220
  call       poly $s 55
  right      15
}
03

Filled Rose

Polar-style petal shapes using beginfill/endfill and arc commands. Each petal is a separate filled shape drawn at an even rotation.

proc petal sz {
  beginfill
  arcright  $sz 90
  right     90
  arcright  $sz 90
  right     180
  endfill
}

setbgcolor   #1a0630
home

for i 0 11 1 {
  mathset      r  $i * 22
  mathset      g  40 + $r
  setcolor     $r 0 $g
  setfillcolor $r 0 $g
  setopacity   70
  call         petal 55
  right        30
}
04

Recursive Tree

Classic fractal branching using recursion. Each call spawns two sub-branches 0.65× shorter, with different colours at each depth level.

proc branch len {
  if $len < 6 { return }
  if $len > 30 {
    setcolor #6b3a2a
    setweight 3
  }
  if $len <= 30 {
    setcolor #44a86e
    setweight 1.5
  }
  forward   $len
  left      30
  mathset   sub $len * 0.65
  call      branch $sub
  right     60
  call      branch $sub
  left      30
  backward  $len
}

setbgcolor   #f8f3e8
penup  goto  300 460  pendown
setheading   270
call         branch 90
05

Stamp Constellation

Stamps axolotl shapes of varying sizes at random-ish positions using a for loop, no pen lines required.

setbgcolor  #0d1022
setstamp    turtleSprite triangle 20
penup

var px 50
var py 50

for i 0 39 1 {
  comment Pseudo-random positions via stepping math
  mathset   px $px * 1.37
  mathset   px $px % 540
  mathset   py $py + 83
  mathset   py $py % 440
  mathset   sz $i % 4
  mathset   sz $sz * 5
  mathset   sz $sz + 10
  setstamp  turtleSprite triangle $sz
  mathset   bright 120 + $sz
  setcolor  $bright $bright 255
  goto      $px $py
  right     45
  stamp
}
06

Interactive Pen

Arrow keys move the axolotl. r picks a random colour. c clears. Shows how to combine multiple on key events.

setbgcolor   #fafafa
setweight    2.5
setcolor     #6366f1
home

on key up    { forward  12 }
on key down  { backward 12 }
on key left  { left     15 }
on key right { right    15 }
on key r     { randomcolor }
on key u     { penup }
on key d     { pendown }
on key c     { cleardrawing }
on key h     { home }
07

Click-to-Draw Stars

Each canvas click stamps a filled star at the click location. The star size cycles through three values via a counter variable.

var        clicks 0
setbgcolor #1e1b4b
penup

proc filledStar sz {
  setstamp     shape star $sz
  stamp
}

on click {
  goto       $eventx $eventy
  changevar  clicks 1
  mathset    tier  $clicks % 3
  ifelse     $tier == 0 {
    setcolor   #fbbf24
    call       filledStar 40
  } else {
    ifelse     $tier == 1 {
      setcolor   #f472b6
      call       filledStar 24
    } else {
      setcolor   #a5f3fc
      call       filledStar 14
    }
  }
}
08

Broadcast Colour Switcher

Number keys broadcast colour-name messages. Separate on broadcast handlers apply the palette. Demonstrates using broadcasts to decouple input from behaviour.

setbgcolor #f8fafc
setweight  3
home

comment Key bindings broadcast palette names
on key 1 { broadcast "crimson"  }
on key 2 { broadcast "sapphire" }
on key 3 { broadcast "emerald"  }
on key 4 { broadcast "gold"     }

comment Each handler applies its colour
on broadcast "crimson"  { setcolor #dc2626 }
on broadcast "sapphire" { setcolor #2563eb }
on broadcast "emerald"  { setcolor #16a34a }
on broadcast "gold"     { setcolor #d97706 }

on key up    { forward  15 }
on key left  { left     20 }
on key right { right    20 }
09

on draw — Orbiting Circles

The on draw loop re-draws orbiting shapes every frame. Enable Instant mode before running. Two axolotls orbit at different speeds and radii.

comment Enable Instant mode, then Run
var a1 0
var a2 180
newaxolotl orb2

on draw {
  cleardrawing
  setbgcolor   #0f172a

  comment orb 1 — inner, fast
  useaxolotl   main
  mathset      cx  300 + 90 * $a1
  comment approximate cos via modulo trick
  mathset      cy  250 + 90 * $a2
  penup  goto  $cx 250
  setcolor     #38bdf8
  setstamp     shape circle 22
  stamp

  comment orb 2 — same radius, offset
  useaxolotl   orb2
  penup  goto  $cy 250
  setcolor     #f472b6
  stamp

  changevar    a1 3
  changevar    a2 -3
  if $a1 > 90  { setvar a1 -90 }
  if $a2 < -90 { setvar a2 90 }
}
on key space { stopdraw }
10

Array Path Walker

Stores a sequence of angles in an array, then walks the path twice: once to preview in grey, once to paint with a vivid gradient.

array   path
arraypush path 0
arraypush path 72
arraypush path 144
arraypush path 216
arraypush path 288
arraypush path 36
arraypush path 108
arraypush path 180

proc walkPath step {
  arraylen   path n
  var        i 0
  while $i < $n {
    arrayget  path $i ang
    setheading $ang
    forward    $step
    changevar  i 1
  }
}

setbgcolor   #f5f3ff
home

comment First pass: faint preview
setcolor     #c4c4c8
setweight    1
call         walkPath 60

home
comment Second pass: vivid colours per segment
arraylen     path n
var          j 0
while $j < $n {
  arrayget   path $j ang
  mathset    hc  $j * 32
  setcolor   $hc 120 255
  setweight  4
  setheading $ang
  forward    60
  changevar  j 1
}
11

Filled Hex Grid

Nested for loops tile the canvas with filled hexagons, offset on alternating rows. Colour is derived from grid position.

proc hexFill {
  beginfill
  repeat 6 {
    forward 22
    right   60
  }
  endfill
}

setbgcolor   #18181b
setweight    0.5
penup

for row 0 9 1 {
  for col 0 9 1 {
    comment Compute hex centre with row offset
    mathset    ox  $row % 2
    mathset    ox  $ox * 19
    mathset    px  $col * 38
    mathset    px  $px + $ox + 25
    mathset    py  $row * 44
    mathset    py  $py + 30
    goto       $px $py
    setheading 30
    pendown
    comment Colour from position
    mathset    r   $col * 25
    mathset    g   $row * 22
    setcolor   $r 0 180
    setfillcolor 40 $g 120
    call       hexFill
    penup
  }
}
12

Spirograph

A hypotrochoid drawn with arcleft and incremental rotation. Adjust the two angle parameters for radically different output.

setbgcolor   #0e0e14
setweight    1
home

var h 0

repeat 360 {
  mathset   r    $count % 255
  setcolor  $r 100 255
  arcleft   90 59
  right     61
}
13

Two-Axolotl Mirror Drawing

Two axolotls draw simultaneously. Arrow keys move both axolotls at once — one going forward, the other going the same distance but mirrored on the Y axis.

setbgcolor   #f9fafb
newaxolotl   mirror

useaxolotl   main
setcolor     #4f46e5
setweight    2.5
penup  goto  220 250  pendown

useaxolotl   mirror
setcolor     #ec4899
setweight    2.5
penup  goto  380 250  pendown

proc moveBoth dist da {
  useaxolotl main
  right      $da
  forward    $dist
  useaxolotl mirror
  comment Mirror: negate the angle
  mathset    mda $da * -1
  right      $mda
  forward    $dist
}

on key up    { call moveBoth 12  0  }
on key down  { call moveBoth -12 0  }
on key left  { call moveBoth 12  -15 }
on key right { call moveBoth 12  15  }
on key c     { cleardrawing }
14

Generative Snowflake

A Koch-snowflake-style recursive procedure. Each branch is replaced by four sub-branches. Depth limit is controlled by the parameter, and return stops recursion cleanly.

proc kochEdge len depth {
  if $depth == 0 {
    forward $len
    return
  }
  mathset  third  $len / 3
  mathset  dnext  $depth - 1
  call     kochEdge $third $dnext
  left     60
  call     kochEdge $third $dnext
  right    120
  call     kochEdge $third $dnext
  left     60
  call     kochEdge $third $dnext
}

setbgcolor  #dbeafe
setcolor    #1e40af
setweight   1.2
penup  goto 170 380  pendown
setheading  0

comment Three sides of the snowflake
repeat 3 {
  call  kochEdge 270 3
  right 120
}