An Experiment in Chaos

Do this on pencilcode.net

Our Experiment: First, place three vertices of a triangle on a paper. Then draw a sequence of dots by starting at any point on the paper, picking one of the three vertices at random, and drawing the next dot exactly halfway between the previous dot and the vertex.

1. Make three new sprites using new Sprite(), and move them to corners of a triangle, like this:

new Sprite('red dot').fd(100)
new Sprite('blue dot').rt(120).fd(100)
new Sprite('green dot').lt(120).fd(100)



We have asked the first sprite to draw itself as a red dot; the second one as a blue dot; and so on. By using the commands fd, rt, and lt after a period (.), we send those commands to one sprite.

2. By enclosing these sprites in square brackets, we can store them all in an array. Since they are the vertices of a triangle, let's call the array v (defining the variable with v = [...]):

v = [
  new Sprite('red dot').fd(100)
  new Sprite('blue dot').rt(120).fd(100)
  new Sprite('green dot').lt(120).fd(100)
]
v[0].scale 2

The sprites can be accessed individually by writing v[0] (the red one), v[1] (the blue one), and v[2] (the green one). Here, v[0].scale 2 tells the red dot to turn scale itself by 2×.

3. The following code implements our experiment:

v = [
  new Sprite('red dot').fd(100)
  new Sprite('blue dot').rt(120).fd(100)
  new Sprite('green dot').lt(120).fd(100)
]
moveto random position   # Move to a random position.
for [1..20]              # Repeat 20 times...
  p = random v           # Pick a random sprite in v; call it p.
  turnto p               # Turn towards p.
  fd distance(p) * 0.5   # Move half the distance to p.
  dot black, 2           # Draw a small black dot.
  await done defer()     # Wait for animation.