Charting Randomness

Do this on pencilcode.net

1. Make three new turtles using new Turtle(), and slide each one to the right like this:

new Turtle(red).slide(30)
new Turtle(2).slide(50)
new Turtle(3).slide(70)

We have asked the first new turtle to color itself red by writing new Turtle(red), and the second and third turtles are drawn as numbers using new Turtle(2) and new Turtle(3).

2. Make 15 new Turtles, numbered 0 to 14, by using a loop:

g = for n in [0..14]
  new Turtle(n).slide(n * 30 - 210)

g[5].fd 20


The code repeats the indented line once for every value of n from zero to 14. Once all the turtles are created, they are saved in an array called g.

An array is just a sequence of values: g is a sequence of turtles! The nth turtle in the array g can be accessed using g[n]. For example, turtle #5 can be slided forward by writing g[5].fd 20.

3. Now that we have 15 turtles, we can put them to work. Here is a program that generates two random numbers in the range [1..6] and then adds them together. It then asks the turtle corresponding to the sum to draw a dot and slide forward. It repeats this 20 times.






g = for n in [0..14]
  new Turtle(n).slide(n * 30 - 210)

for [1..20]              # Repeat 20 times...
  q = random [1..6]      # q is one dice-roll.
  r = random [1..6]      # r is another.
  s = q + r              # s is the sum.
  g[s].dot red           # tell Turtle #s to draw a dot.
  g[s].fd 10             # then tell it to slide forward.
  await done defer()     # wait for animation to finish before going on.

20 dice rolls is not very many. Try repeating more times than 20.

4. Here is a more elaborate program that lets you reason about the randomness, illustrating the dice rolls with a matrix of sums.

m = new table 7, 7      # this code fills in a table
for n in [1..6]
  m.cell(0, n).text(n).css { background: silver }
  m.cell(n, 0).text(n).css { background: silver }
for x in [1..6]
  for y in [1..6]
    m.cell(x, y).text(x + y)

speed 100

g = for n in [0..14]    # back up turtles by 200
  new Turtle(n).slide(n * 30 - 210, -200)

for [1..20]
  r = random [1..6]
  q = random [1..6]
  s = r + q
  slideto m.cell(r, q)  # draw on the table
  dot rgba(255,0,0,0.2), 20
  g[s].dot red
  g[s].fd 10
  await done defer()











Some explanations of the tools used in this example: