'#
'# Ball-Chase demo by Parabellum (2002)
'#
'# Entry #2 for the 40 lines demo competition, and winner
'# in the 2D category.
'#
'# Indented version (same code as the squeezed entry)
'#
'# Use UP and DOWN to adjust the overall brightness.
'# Press X to hide the ball.
'#

M=1 rem luminosity
dim P(13)
dim H(13)
dim Z(13)
S=0.055

bz=2
bzs=-0.005

dim S(1440):dim C(1440)
for i=0 to 1440
  S(i)=sin(i*PI/720):C(i)=cos(i*PI/720)
next

open window 640,512:window origin "cc"

for i=0 to 12 
  H(i) = AND(i,1)
  gosub init
  Z(i) = 0.65*(13-i)+1
next

LABEL LOOP

setdrawbuf DB : DB=1-DB
setdispbuf DB : clear window

if (bz<1.76 or bz>4) bzs=-bzs
bz=bz+bzs

K=peek("port1")
if K<>0 M=min(4,max(.1,M+.01*(and(K,16)/16-and(K,64)/64)))
K=and(K,16384)

i=I-1
for ii=1 to 13
  i=mod(i+1,13)
  z = Z(i)
  Fz=1/z
  if bz>z and K=0 then
    K=1
    brz=125/bz

    bxs=(bx-dx)/bz
    bys=(by-dy)/bz

    c=1.75/bz*M
    rg=39*c
    setrgb 1,rg,rg,25*c
    setrgb 2,rg,rg,25*c
    setrgb 3,130*c,130*c,80*c

    bx2=2*bxs
    by2=2*bys

    bxc=bxs-0.0021875*brz*bxs
    x=bxs+brz
    byc=bys-0.0027344*brz*bys
    y=bys

    for d=40 to 360 step 40
      x1=bxs+brz*C(d)
      y1=bys+brz*S(d)
      gtriangle x,y to x1,y1 to bxc,byc
      gtriangle bx2-x,by2-y to bx2-x1,by2-y1 to bxc,byc
      gtriangle x,by2-y to x1,by2-y1 to bxc,byc
      gtriangle bx2-x,y to bx2-x1,y1 to bxc,byc
      x=x1
      y=y1
    next d

  fi
  c1 = 17 *Fz *M
  c2 = 217 *Fz *M
  Z(i) = Z(i)-S
  d = 60*Fz
  for p=-2 to 2
    if H(i)=1 then
      p2 = (P(i)-dy+632*p) * Fz
    else
      p2 = (P(i)-dx+760*p) * Fz
    fi
    p1 = p2 - d
    p3 = p2 + d
    setrgb 1,c1,c1,c1
    setrgb 2,c1,c1,c1
    setrgb 3,c2,c2,c2
    if H(i)=1 then
      lH=i
      if z>bz lBH=i
      gtriangle -320,p1 to 320,p1 to 320,p2
      gtriangle -320,p3 to 320,p3 to -320,p2
      setrgb 2,c2,c2,c2
      gtriangle -320,p1 to -320,p2 to 320,p2
      gtriangle 320,p3  to -320,p2 to 320,p2
    else
      lV=i
      if z>bz lBV=i
      gtriangle p1,-256 to p1,256 to p2,256
      gtriangle p3,-256 to p3,256 to p2,-256
      setrgb 2,c2,c2,c2
      gtriangle p1,-256 to p2,-256 to p2,256
      gtriangle p3,256  to p2,-256 to p2,256
    fi
  next
next

REM *** Move the "camera"

p=P(lV)
o=p-sig(p)*380   rem 380=320+D
d = Z(lV)-1
if d>.01 dx=dx+(o-dx)/d*S

p=P(lH)
o=p-sig(p)*316   rem 316=256+D
d = Z(lH)-1
if d>.01 dy=dy+(o-dy)/d*S

REM *** Move the ball

p=P(lBV)
o=p-sig(p)*380   rem 380=320+D
d = Z(lBV)-bz
if d>.01 bx=bx+(o-bx)/d*S

p=P(lBH)
o=p-sig(p)*316   rem 316=256+D
d = Z(lBH)-bz
if d>.01 by=by+(o-by)/d*S

REM *** Append a new bar to the background, as necessary.

if (Z(i) < 1) then
  H(i) = 1-H(I)
  I = i
  gosub init
  Z(i) = 9.45  rem 1+0.65*13
fi

GOTO LOOP


LABEL init
  if H(i)=1 then  P(i) = ran(640)-320
            else  P(i) = ran(512)-256  fi
RETURN



