Select Git revision
gradle-wrapper.properties
-
Will Billingsley authoredWill Billingsley authored
DotsAndBoxesUI.java 6.55 KiB
package dotsandboxes;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.util.ArrayList;
public class DotsAndBoxesUI {
static final int lineLength = 32;
static final int margin = 10;
static final int gap = 0;
static final int dotDiameter = 6;
// The coordinate of the top or left of a the painting area for this row/col
private static int corner(int col) {
return margin + col * (gap + lineLength + gap + dotDiameter);
}
/** Colours for the different players. Only goes up to 5. */
static final Color[] playerColours = { Color.WHITE, Color.RED, Color.BLUE, Color.GREEN, Color.PINK, Color.ORANGE };
final DotsAndBoxesGrid grid;
final JPanel anchorPane;
final Canvas canvas;
final JLabel label;
private void updateLabel() {
label.setForeground(playerColours[grid.getPlayer()]);
label.setText(String.format("Player %d's turn", grid.getPlayer()));
}
public DotsAndBoxesUI(final DotsAndBoxesGrid grid) {
this.grid = grid;
anchorPane = new JPanel(new BorderLayout());
label = new JLabel("");
updateLabel();
canvas = new DABCanvas();
anchorPane.add(canvas, BorderLayout.CENTER);
anchorPane.add(label, BorderLayout.NORTH);
grid.addConsumer((g) -> {
updateLabel();
canvas.repaint();
});
}
/** A component that paints and handles clicks on the game */
class DABCanvas extends Canvas {
final ArrayList<Horizontal> horizontals = new ArrayList<>();
final ArrayList<Vertical> verticals = new ArrayList<>();
final ArrayList<Box> boxes = new ArrayList<>();
/** Represents a horizontal line. */
record Horizontal(int col, int row) {
Rectangle rect() {
int x = corner(col) + dotDiameter + gap;
int y = corner(row);
return new Rectangle(x, y, lineLength, dotDiameter);
}
/** Whether or not this line contains this point */
boolean contains(int x, int y) {
return rect().contains(x, y);
}