 Example of a Galton Box at the end of animation.


A   Galton device   Sir Francis Galton's device   is also known as a   bean machine,   a   Galton Board,   or a   quincunx.



Description of operation

In a Galton box, there are a set of pins arranged in a triangular pattern.   A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin.   The ball continues to fall to the left or right of lower pins before arriving at one of the collection points between and to the sides of the bottom row of pins.

Eventually the balls are collected into bins at the bottom   (as shown in the image),   the ball column heights in the bins approximate a   bell curve.   Overlaying   Pascal's triangle   onto the pins shows the number of different paths that can be taken to get to each bin.



Task

Generate an animated simulation of a Galton device.



Task requirements

   The box should have at least 5 pins on the bottom row. 
   A solution can use graphics or ASCII animation. 
   Provide a sample of the output/display such as a screenshot.
   There can be one or more balls in flight at the same time. 
   If multiple balls are in flight, ensure they don't interfere with each other.
   A solution should allow users to specify the number of balls, or it should run until full or a preset limit. 
   Optionally,   display the number of balls.


without js -- clear_screen(), text_color(), position(), sleep(), get_key()...
constant balls = 80
clear_screen()
sequence screen = repeat(repeat(' ',23),12)
                & repeat(join(repeat(':',12)),12)
                & {repeat('.',23)},
         Pxy = repeat({12,1},balls)
for peg=1 to 10 do
    screen[peg+2][13-peg..11+peg] = join(repeat('.',peg))
end for
puts(1,join(screen,"\n"))
text_color(BRIGHT_RED)
bool moved = true
integer top = ' '   -- (new drop every other iteration)
while moved or top!=' ' do
    moved = false
    for i=1 to balls do
        integer {Px,Py} = Pxy[i]
        if Py!=1 or top=' ' then
            integer Dx = 0, Dy = 0
            if screen[Py+1,Px]=' ' then     -- can vertical?
                Dy = 1
            else
                Dx = {-1,+1}[rand(2)]       -- try l;r or r;l
                if screen[Py+1,Px+Dx]!=' ' then Dx = -Dx end if
                if screen[Py+1,Px+Dx]==' ' then 
                    Dy = 1
                end if
            end if
            if Dy then
                position(Py,Px)  puts(1," ")  screen[Py,Px] = ' '
                Px += Dx
                Py += Dy
                position(Py,Px)  puts(1,"o")  screen[Py,Px] = 'o'
                Pxy[i] = {Px,Py}
                moved = true
                if Py=2 then top = 'o' end if
            end if
        end if
    end for
    position(26,1)
    sleep(0.2)
    if get_key()!=-1 then exit end if
    top = screen[2][12]
end while
