import javax.swing.* ;
import java.awt.Color ;
import java.awt.Graphics ;
import java.awt.Point ;
import java.awt.event.* ;

public class Timer extends JFrame implements KeyListener, Runnable
{
  public enum MoveDirection
  {
    UP, DOWN, LEFT, RIGHT, INITIAL
  }

  public boolean isRunnung = true ;
  public Point head = new Point( 100, 100 ) ;
  public Point tail = new Point( 100, 100 ) ;
  public MoveDirection currentDirection = MoveDirection.INITIAL ;
  public static final int RECT_SIZE = 20 ;
  public static final int SLEEP_SEC = 500 ;

  Thread thread = null ;

  public Timer()
  {
    thread = new Thread( this ) ;
    thread.start() ;
    setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE ) ;
    setSize( 500, 500 ) ;
    SnackPanel snack = new SnackPanel() ;
    snack.setBackground( Color.white ) ;
    add( snack ) ;
    addKeyListener( this ) ;
    setVisible( true ) ;
  }

  public static void main( String[] args )
  {
    new Timer() ;
  }

  public class SnackPanel extends JPanel
  {
    @Override
    public void paintComponent( Graphics graphics )
    {
      
      super.paintComponent( graphics ) ;
      graphics.clearRect( head.x, head.y, RECT_SIZE, RECT_SIZE ) ;

      if ( currentDirection == MoveDirection.UP )
        head.setLocation( head.x, head.y - RECT_SIZE ) ;
      else if ( currentDirection == MoveDirection.DOWN )
        head.setLocation( head.x, head.y + RECT_SIZE ) ;
      else if ( currentDirection == MoveDirection.LEFT )
        head.setLocation( head.x - RECT_SIZE, head.y ) ;
      else if ( currentDirection == MoveDirection.RIGHT )
        head.setLocation( head.x + RECT_SIZE, head.y ) ;

      graphics.fillRect( head.x, head.y, RECT_SIZE, RECT_SIZE ) ;
    }
  }

  @Override
  public void keyPressed( KeyEvent e )
  {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyReleased( KeyEvent e )
  {
    // TODO Auto-generated method stub

  }

  @Override
  public void keyTyped( KeyEvent e )
  {
    isRunnung = false ;
    MoveDirection nextDirection = NextDirection( e ) ;
    if ( nextDirection != null )
    {
      if ( currentDirection != nextDirection )
      {
        currentDirection = nextDirection ;
        repaint() ;
      }
    }

    isRunnung = true ;
  }

  public MoveDirection NextDirection( KeyEvent e )
  {

    if ( e.getKeyChar() == '5' )
      return MoveDirection.UP ;
    else if ( e.getKeyChar() == '2' )
      return MoveDirection.DOWN ;
    else if ( e.getKeyChar() == '1' )
      return MoveDirection.LEFT ;
    else if ( e.getKeyChar() == '3' )
      return MoveDirection.RIGHT ;
    else
      return null ;

  }

  @Override
  public void run()
  {
    while ( true )
    {
      if ( isRunnung )
        repaint() ;

      try
      {
        thread.sleep( SLEEP_SEC ) ;
      }
      catch ( InterruptedException e )
      {
        e.printStackTrace() ;
      }
    }
  }
}