import java.awt.*;
import javax.swing.JFrame;
import java.util.EventObject;
import java.util.Queue;
import java.util.LinkedList;

public class Snake{
  static int random(int i1,int i2){ return  (int)Math.floor(i1+ (i2+1-i1)*Math.random());   }
  static int dim=40; // size of squares on the board
  static int s(int x){return dim+x*dim;}//row/col to screen coordinate 
  public static void main(String args[]){
     JFrame frame=new JFrame("Snake");
     frame.setSize(600,600);
     frame.setLocation(new Point(100,100));
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     JCanvas canvas=new JCanvas();
     frame.add(canvas);
     frame.setVisible(true);

     JEventQueue events=new JEventQueue();
     events.listenTo(canvas,"canvas");
     Queue<Point> queue=new LinkedList<Point>();

     //position and speed of the snake head
     int x=0,y=0,vx=1,vy=0;
     Point food=null;
     for(;;){
       while(events.hasEvent()){
         EventObject event=events.waitEvent();
         if(events.isKeyPressed(event)){
            String s= events.getKeyText(event); 
            //Check which key was pressed
            if(s.equals("Down")){vy=1;vx=0;}else
            if(s.equals("Up")){vy=-1;vx=0;}else
            if(s.equals("Left")){vy=0;vx=-1;}else
            if(s.equals("Right")){vy=0;vx=1;}
         }
       }
       // 
       int numX=canvas.getWidth()/dim-2;
       int numY=canvas.getHeight()/dim-2;

       x=x+vx;  y=y+vy; 
       Point p1=new Point(x,y);
       if(x>=numX||y>=numY||x<0||y<0||queue.contains(p1))break;

       // if there is no food on the board then place some food at a random location
       if(food==null)food=new Point(random(0,numX-1),random(0,numY-1));
       // if the head hits the food then eat it
       if(p1.equals(food)){
          food=null;
          frame.setTitle("Snake "+(queue.size()+1)); 
       }else 
       if(queue.size()>0)queue.remove();
       if(food!=null&&queue.contains(food))food=null;
       queue.offer(p1);

       canvas.startBuffer();
       canvas.clear();
       canvas.setColor(Color.black);
       // draw the board
       for(int i=0;i<=numX;i++)
         canvas.drawLine(s(i),s(0),s(i),s(numY));
       for(int j=0;j<=numY;j++)
         canvas.drawLine(s(0),s(j),s(numX),s(j));
       // draw the snake
       for(Point p:queue){
         canvas.fill(new Rectangle(s(p.x)+2,s(p.y)+2,dim-3,dim-3)); 
       }     
       // draw the food
       canvas.setColor(Color.red);
       if(food!=null)
         canvas.fill(new Rectangle(s(food.x)+2,s(food.y)+2,dim-3,dim-3)); 
       canvas.endBuffer();
       canvas.sleep(150+queue.size()*3);
     }
     canvas.setColor(Color.blue);
     canvas.setFont(new Font("Arial",Font.BOLD,40));
     canvas.drawString("Result "+(queue.size()+1),50,50);
  }
}
