package pdp.scrabble.ihm;
import java.awt.Dimension;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
import pdp.scrabble.game.Board;
import pdp.scrabble.game.BoardCase;
import pdp.scrabble.game.GameEnvironment;
import pdp.scrabble.ihm.action.BoardAction;
import pdp.scrabble.ihm.action.impl.BoardActionImpl;
import static pdp.scrabble.game.Board.*;
import static pdp.scrabble.game.BoardCase.*;
import static pdp.scrabble.game.BoardCaseState.NEW;
/** This is where is drawn the game board.
*/
public class BoardPanel extends JPanel {
private static final long serialVersionUID = 1L;
/** Selected case color. */
private static final Color SELECTED_CASE_COLOR = new Color(0, 0, 0, 160);
/** New case color. */
private static final Color NEW_CASE_COLOR = new Color(32, 212, 64, 144);
/** Board reference. */
private Board board = null;
/** Panel actions. */
private BoardAction action = null;
/** Game reference. */
private GameEnvironment game = null;
/** Create a new board panel.
* @param mainFrame main frame reference.
* @param game game reference.
*/
public BoardPanel(MainFrame mainFrame, GameEnvironment game) {
super();
this.action = new BoardActionImpl(mainFrame, this, game);
this.board = game.board();
this.game = game;
this.setBackground(Color.BLACK);
this.setPreferredSize(new Dimension(600, 600));
this.addMouseListener((MouseListener) this.action);
this.addMouseMotionListener((MouseMotionListener) this.action);
}
/** Create a new board panel.
* @param board board reference.
*/
public BoardPanel(Board board) {
super();
this.board = board;
this.setPreferredSize(new Dimension(600, 600));
}
@Override
public void paintComponent(Graphics g) {
// Display board cases
for (int v = 0; v < VERT_DIM; v++) {
for (int h = 0; h < HORI_DIM; h++) {
BoardCase boardCase = this.board.getCase(v, h);
boardCase.render(g, h * CASE_SIZE, v * CASE_SIZE);
// Color new cases only
if (boardCase.getState() == NEW) {
g.setColor(NEW_CASE_COLOR);
g.fill3DRect(h * CASE_SIZE, v * CASE_SIZE,
CASE_SIZE, CASE_SIZE, true);
}
}
}
// Get mouse data
if (this.action != null && this.game.engine().getPlayerTurn() != -1) {
int mx = this.action.getMouseX();
int my = this.action.getMouseY();
int dragOffsetX = this.action.getDragOffsetX();
int dragOffsetY = this.action.getDragOffsetY();
int dragV = this.action.getDragV();
int dragH = this.action.getDragH();
// Display selected case
if (mx > 0 && my > 0
&& mx < this.getWidth() - 1 && my < this.getHeight() - 1) {
int x = (mx / CASE_SIZE) * CASE_SIZE;
int y = (my / CASE_SIZE) * CASE_SIZE;
g.setColor(SELECTED_CASE_COLOR);
g.fill3DRect(x, y, CASE_SIZE, CASE_SIZE, true);
}
// Display dragging letter
if (this.action.isDragging()) {
BoardCase boardCase = this.board.getCase(dragV, dragH);
if (boardCase.getState() == NEW) {
boardCase.render(g, mx + dragOffsetX, my + dragOffsetY);
}
}
}
}
}