!  Galton box.

SET mode "low8"
OPEN #1: screen .05,.95,.05,.95
SET window -5,27,0,20
DIM count(11)
RANDOMIZE

SET color "red"
PLOT 0,0; 22,0
FOR x = 0 to 22 step 2
    PLOT x,0; x,9
NEXT x

SET color "cyan"
FOR r = 1 to 10
    FOR c = 1 to r
        CALL peg(r,c,0)
    NEXT c
NEXT r

SET color "red"
CALL disk(ball$)
FOR b = 1 to 50
    LET r,c = 1
    CALL ball(r,c,ball$,0)
    FOR t = 1 to 10
        CALL ball(r,c,ball$,-1)
        LET r = r+1
        IF rnd<.5 then LET c=c+1
        IF t=10 then LET count(c)=count(c)+1
        CALL ball(r,c,ball$,count(c))
    NEXT t
NEXT b
END

SUB peg(r,c,cnt)
    CALL convert(r,c,x,y,cnt)
    BOX AREA x-.1,x+.1,y-.1,y+.1
END SUB

SUB ball(r,c,b$,cnt)
    CALL convert(r,c,x,y,cnt)
    IF cnt<0 then
       BOX CLEAR x-.33,x+.33,y+.2,y+.9
    ELSE
       BOX SHOW b$ at x-.33,y+.2 using "or"
    END IF
END SUB

SUB convert(r,c,x,y,cnt)
    IF r<11 then
       LET x = 12-r+2*(c-1)
       LET y = 20-r
    ELSE
       LET x = 2*c-1
       LET y = 1.3*cnt/2-.5
    END IF
END SUB

SUB disk(b$)
    LET x = 11
    LET y = 19.5
    LET r = .32
    SET color "black"
    BOX circle x-r,x+r,y-r,y+r
    ASK FREE MEMORY free
    IF free>32000 then
       SET color "yellow"
       FLOOD x,y
    END IF
    BOX KEEP 10.67,11.33,19.21,19.84 in b$
END SUB
