/* 
        Modul  : TURTLE                                          
        Purpose: The Turtle as modul
        Author : Gerhard Röhner
        Version: 1.0, 21.1.2000
      
      Activation: Save, dont't copy, the file in the library-folder of SWI-Prolog,
      because the filedate has to be up-to-date. Then call ?- make. in SWI-Prolog.
      
*/

:- module(turtle,
     [ turtle_init/0    % Initialize the Turtle.
     , turtle_term/0    % Terminate the Turtle.
     , turtle_drawto/2  % Draw a line to an absolute point P(X/Y).
     , turtle_draw/1    % Draw a line of length L in the current direction.
     , turtle_turn/1    % Turn the direction of the Turtle by W degrees relative.
     , turtle_turnto/1  % Turn the Turtle to the absolute angle W.
     , turtle_move/1    % Move the Turtle a line of length L in the current direction.
     , turtle_moveto/2  % Move the Turtle to a point P(X/Y) without drawing.
     ]).

:- use_module(library(pce)).

turtle_init:-
   % delete old state
   retractall(turtle(_,_,_)),

   % set new state
   B is 400,
   H is 300,
   B1 is B /2,
   H1 is H / 2,
   W1 is 0,
   assert(turtle(B1, H1, W1)),
   
   % close old LOGO-window
   free(@logo),

   % open new LOGO-window
   new(@logo, picture('LOGO', size(B, H))), send(@logo, open).

turtle_term:-
  retractall(logo/3),
  free(@logo).

turtle_drawto(X, Y):-
  retract(turtle(X1, Y1, W)),
  send(@logo, display, new(_, line(X1, Y1, X, Y))),
  assert(turtle(X, Y, W)).

turtle_draw(L):-
  retract(turtle(X1, Y1, W)),
  X2 is X1 + L*cos(W*pi/180),
  Y2 is Y1 - L*sin(W*pi/180),
  send(@logo, display, new(_, line(X1, Y1, X2, Y2))),
  assert(turtle(X2, Y2, W)).

turtle_turn(W):-
  retract(turtle(X, Y, W1)),
  W2 is W1 + W,
  assert(turtle(X, Y, W2)).

turtle_turnto(W):-
  retract(turtle(X, Y, _)),
  assert(turtle(X, Y, W)).

turtle_move(L):-
  retract(turtle(X1, Y1, W)),
  X2 is X1 + L*cos(W*pi/180),
  Y2 is Y1 - L*sin(W*pi/180),
  assert(turtle(X2, Y2, W)).

turtle_moveto(X, Y):-
  retract(turtle(_, _, W)),
  assert(turtle(X, Y, W)).

