/*
 * Arena.java
 *
 * Created on 18 July 2002, 15:43
 */

/**
 *
 * @author  gbspashj
 */



import java.awt.*;

public class Arena implements Actor {
    private int GROW_FACTOR = 5; // A nine point yum yum makes a 50 length tail, yum yum.
    private int width; 
    private int height;
    private Snake snake = null;
    private Food  food = null;
    private boolean dead = false;
    private int score = 0;
    
    public Arena(Snake s, int w, int h) {
        snake = s;
        width = w;
        height = h;
        food = new Food( w/2, h/2 );
    }
    
    // Is x,y inside b
    protected boolean checkFoodBounds(Food b, int x, int y) {
        if ( b.x == x && b.y == y )
            return true;
        else
            return false;
    }
    
    protected boolean checkArenaBounds( Snake s ) {
        boolean hit = false;
        
        hit = 
            (s.getX() <= 0) ||
            (s.getY() <= 0) ||
            (s.getY() >= height) ||
            (s.getX() >= width);
        return hit;
    }
    
    public boolean snakeRun( int direction ) {
        if ( !dead ) {
            if ( checkArenaBounds( snake ) ) {
                dead = true;
            } 

            if ( checkFoodBounds( food, snake.getX(), snake.getY() ) ) {
                int nx, ny;
                do { // Remake food coordinated that lie ontop of snake
                    nx = (int)(1+Math.random() * (width-1)); 
                    ny = (int)(1+Math.random() * (height-1));
                } while (snake.checkAnyCollision(nx,ny) == true);
                
                int val = (int)(Math.random() * 9 + 1);
                score += food.value;
                snake.grow(food.value * GROW_FACTOR);
                
                food = new Food( nx, ny, val );
                
            }

            if ( snake.checkHeadCollision() ) {
                dead = true;
            } 
            else
            {
                snake.moveDelta( direction, 1 );
            }
        }
        return dead;
    }
    
    public int getScore() {
        return score;
    }
    
    public int getWidth() {
        return width;
    }
    
    public int getHeight() {
        return height;
    }
    
    public void visit(ActorVisitor av) {
        food.visit(av);
        snake.visit(av);
        av.visitArena(this);
    }
    
}
