// 2011.07.06 # Doj

  // текущее положение выхода
  variable F-x variable F-y
  // новое положение выхода (для внутренних нужд)
  variable new-x variable new-y
  // player - F
  variable delta-x variable delta-y
  // |player - F|
  variable dist-x variable dist-y
  // предыдущая ячейка, в которой выход
  variable last-x variable last-y
  // время, когда выход сменил ячейку
  variable last-time

  :noname  pchar" data\sounds\newlevel.wav" sound ;init
  :noname  2drop ( draw-finish-cell) ;draw_ F
  : draw_# COLOR 2dup GREENS GEN[]2 ^ set-color draw-cell-rect ;
  :noname  COLOR 2dup BROWNS GEN[]2 ^ set-color draw-cell-rect ;draw_ 2
  :noname  2dup passed 32 rrot maze[]! ;enter_ O
  :noname  player-y! player-x! ;oninit_ S
  : cango? maze[]@ dup 32 = swap 83 = or ;
  : new@F! new-x @ F-x ! new-y @ F-y ! ;
  :noname  ." oninit F " dup . new-y ! dup . cr new-x ! new@F! ;oninit_ F
  : +-sign 0< if -1 else 1 then ;
  : sign-x delta-x @ +-sign ;
  : sign-y delta-y @ +-sign ;
  : find-new-pos
      new@F! dist-x @ dist-y @ > if
        sign-x neg F-x @ +
        dup F-y @ cango? if new-x ! exit then drop
        F-y @ sign-y neg + F-x @ over cango? if new-y ! exit then drop 
        F-y @ sign-y neg - F-x @ over cango? if new-y ! exit then drop 
      else
        sign-y neg F-y @ +
        F-x @ over cango? if new-y ! exit then drop
        F-x @ sign-x neg + dup F-y @ cango? if new-x ! exit then drop 
        F-x @ sign-x neg - dup F-y @ cango? if new-x ! exit then drop 
      then
  ;
  : full-delta-time MIN_STEP_DELTA 2 div ;
  : delta-time timer last-time @ - full-delta-time min ;
  : interpolate ( sf) delta-time * swap full-delta-time delta-time - * +
                      full-delta-time div ;
  :noname 
    last-x @ x->global F-x @ x->global interpolate
    last-y @ y->global F-y @ y->global interpolate
    draw-finish-rect
    timer last-time @ - MIN_STEP_DELTA 2 div < if exit then 
    player-x @ F-x @ - dup delta-x ! abs dist-x !
    player-y @ F-y @ - dup delta-y ! abs dist-y !
    dist-x @ dist-y @ max 3 < if
      find-new-pos
      F-x @ new-x @ <> F-y @ new-y @ <> or 
      if timer last-time ! F-x @ last-x ! F-y @ last-y ! then
      32 F-x @ F-y @ maze[]!
      new@F!
      70 F-x @ F-y @ maze[]!
    then
  ;after-update
lab 
###################
#                 #
#                 #
#  ###### ######  #
#  #     F     #  #
#  # ######### #  #
#  # ######### #  #
#  # ######### #  #
#  # ####S#### #  #
#  # #### #### #  #
#  #           #  #
#  #############  #
#                 #
#                 #
###################
\lab
maze!
32 cell-x! 32 cell-y!
centrize
