#include "theseus.h"

void Theseus::Solve( Labyrinth& lbr, int x_, int y_  ){

	x = x_;
	y = y_;

    PointStack st;  // create the stack to keep the path
    st.Push( MakePoint(x,y) );

    // Moves are tried in this order:
    //   East:  x+1, y
    //   South: x,   y+1
    //   West:  x-1, y
    //   North: x, y-1
    // The first direction in which there are free (and unmarked 
    // with thread) cells is tried.

    while( ! lbr.Contains(x,y,GOAL) && ! st.isEmpty() ){

	  lbr.Put(x,y,THREAD);      // mark current position
		
	  if( lbr.isFree( x+1, y ) ){
		st.Push( MakePoint(x,y) ); // push current position
		x = x+1;
      }
      else if( lbr.isFree( x, y+1 ) ){
		st.Push( MakePoint(x,y) ); // push current position
		y = y+1;
      }
      else if( lbr.isFree( x-1, y ) ){
		st.Push( MakePoint(x,y) ); // push current position
		x = x-1;
      }
      else if( lbr.isFree( x, y-1 ) ){
		st.Push( MakePoint(x,y) ); // push current position
		y = y-1;
      }
      else { // no move, back up one step
		Point p;
		p = st.Top();
		st.Pop();
		x = p.h;
		y = p.v;
      }
      lbr.Draw(x,y,THESEUS);
      Delay( 5 );
      // DEBUG:
      //Point dummy;
      //GetClickPoint(dummy);

    } // end while
    
    // why we exited?
    if( st.isEmpty() )
      cout << "No way! Not fair!\n";
    else
      cout << "Found it! Hurray!\n";

  }