/**
 *  Implements a board for the "Chomp" applet
 */
import java.awt.*;
import javax.swing.*;

public class ChompBoard extends JPanel
{
  private final int ROWS = 4, COLS = 7;      // board dimensions
  private final int CELLSIZE = 40;
  private final Color chocolate = new Color(110, 70, 50);

  private int tentativeRow, tentativeCol, displayCount;

  /**
   *  Constructor
   */
  public ChompBoard()
  {
    setPreferredSize(new Dimension(COLS * CELLSIZE, ROWS * CELLSIZE));
    setBackground(Color.lightGray);
  }

  /**
   *  Returns the number of rows in the board
   */
  public int numRows()
  {
    return ROWS;
  }

  /**
   *  Returns the number of columns in the board
   */
  public int numCols()
  {
    return COLS;
  }

  /**
   *  Returns the position that corresponds to the x,y-coordinates
   *  of the mouse click on the board
   */
  public Position getPos(int x, int y)
  {
    return new Position(y / CELLSIZE, x / CELLSIZE);
  }

  /**
   *  Sets position for the expected move at row, col
   *  (to provide visual feedback, e.g. flashing the changed squares)
   */
  public void setMove(int row, int col)
  {
    tentativeRow = row;
    tentativeCol = col;
  }

  /**
   *  Sets count for visual feedback, e.g. flashing the changed squares
   */
  public void setDisplayCount(int count)
  {
    displayCount = count;
  }

  private ChompGame game;

  /**
   *  Repaints the board after the move at row, col
   */
  public void update(ChompGame game)
  {
    this.game = game;
    repaint();
  }

  /**
   *  Redefined the method for the base class -- displays the board
   *  after a repain request
   */
  public void paintComponent(Graphics g)
  {
    int r, c, x, y;
    Color color;

    super.paintComponent(g);

    if (game == null)
      return;

    for (r = 0; r < ROWS; r++)
    {
      for (c = 0; c < COLS; c++)
      {
        if (game.isEmpty(r, c))
          color = Color.lightGray;
        else if (displayCount % 2 != 0 && r >= tentativeRow && c >= tentativeCol)
          color = Color.red;
        else
          color = chocolate;
        g.setColor(color);
        x = c * CELLSIZE;
        y = r * CELLSIZE;
        g.fillRect(x, y, CELLSIZE, CELLSIZE);
        g.setColor(Color.black);
        g.drawRect(x, y, CELLSIZE, CELLSIZE);
        g.drawRect(x+1, y+1, CELLSIZE-2, CELLSIZE-2);
        if (r == 0 && c == 0)
        {
          g.setColor(Color.yellow);
          g.drawLine(x+3, y+3, x + CELLSIZE - 6, y + CELLSIZE - 6);
          g.drawLine(x+3, y + CELLSIZE - 6, x + CELLSIZE - 6, y+3);
        }
      }
    }

    if (displayCount > 0)
      displayCount--;
  }
}

