/*
 * Snake.java
 *
 * Created on 18 July 2002, 10:02
 */



/**
 *
 * @author  gbspashj
 */
import java.awt.*;

public class Snake implements Actor {
    protected Head    head;
    protected Tail    tail;
    private int length;
    private int lastDir = -1;
    private int grow = 0;
    
    int c = 0;
    
    public Snake( int x, int y, int len ) {
        head = new Head( x, y );
        length = len;
        tail = new Tail( x - len, y );
        head.setNext( tail );
        head.setLast( null );
        tail.setLast( head );
        tail.setNext( null );
    }
    
    
    public void moveDelta( int dir, int dist )  {
        // Turning? add corner
        if ( lastDir != dir ) {
            // New turningpoint
            TurningPoint tp = new TurningPoint( head.getX(), head.getY() );
            Part l = head.getNext();
            head.setNext(tp);
            tp.setNext(l);
            tp.setLast(head);
            l.setLast(tp);
        }
      
        lastDir = dir;
        // Move head 
        head.moveDelta( dir, dist );
     
        
        if ( grow > 0 )
        {
            grow--;
            length++;
        } else {
            // Move tail towards next body part
            tail.moveDelta( dir, dist);
        }
        
    }
    
    // Check for a collision with any part of snake at all
    public boolean checkAnyCollision(int x, int y) {
        boolean collision = false;
        
        for(Part p = head; p != null; p = p.getNext()) {
            if ( p.contains(x, y) ) {
                collision = true;
            }
        }
        return collision;
    
    }
    
    // Check head colliding with rest of snake
    public boolean checkHeadCollision() {
        boolean eaten_self = false;
        
        // Start from second turningpoint, becuase a straight snake can't eat itself
        for(Part p = head.getNext().getNext(); p != null; p = p.getNext()) {
            if ( p.contains(head.getX(), head.getY()) ) {
                eaten_self = true;
            }
        }
        return eaten_self;
    }
    
    public int getX() {
        return head.getX();
    }
    
    public int getY() {
        return head.getY();
    }
    
    public void grow(int g) {
        grow = g;
    }
    
    public void visit(ActorVisitor av) {
        Part p = head;
         while ( p != null ) {
           ((Actor)p).visit(av);
            p = p.getNext();
        } 
    }    
   
}
