Skip to content
Snippets Groups Projects
Select Git revision
  • 7cb84e894a61b820be5d3470885b295defa832c6
  • main default protected
  • 1-fix-the-bugs
  • testsfail
4 results

DotsAndBoxesGrid.java

Blame
  • DotsAndBoxesGrid.java 6.44 KiB
    package dotsandboxes;
    
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.function.Consumer;
    
    /**
     * The state of a dots and boxes grid.
     *
     * A (4, 3) dots and boxes grid looks like this:
     *
     * *-*-*-*
     * | | | |
     * *-*-*-*
     * | | | |
     * *-*-*-*
     *
     * Notice that:
     *
     * - for each row, there is one less horizontal than the number of corner dots
     * - for each row, there are as many verticals as there are corner dots
     * - for each row, there is one less box than the number of corner dots
     * - for each column, there is one less vertical than the number of corner dots.
     * - for each column, there are as many horizontals as there are corner dots.
     * - for each column, there is one less box than the number of corner dots
     *
     * For example, in this (4, 3) grid, there are (3, 3) horizontal lines, and (4, 2) vertical lines, and (3, 2) boxes.
     *
     * We number all lines and boxes by their top-left coordinate.
     *
     * In Java 14+, we might use a Record class for this, but we're using 11+ as an LTS version, so we don't have that yet.
     */
    public class DotsAndBoxesGrid {
    
        final int width;
        final int height;
    
        /** The horizontal lines in the grid. True if drawn. */
        private boolean[][] horizontals;
    
        /** The vertical lines in the grid. True if drawn. */
        private boolean[][] verticals;
    
        /** Which owner (if any) claimed any given box. */
        private int[][] boxOwners;
    
        /** A list of functions to notify when there is an update */
        private ArrayList<Consumer<DotsAndBoxesGrid>> watchers = new ArrayList<>();
    
        final int players;
        private int player = 1;
        public int getPlayer() {
            return player;
        }
    
        /** Moves to the next player */
        private void nextPlayer() {
            player++;
            if (player > players) {
                player = 1;
            }
        }
    
        public DotsAndBoxesGrid(int width, int height, int players) {
            this.width = width;
            this.height = height;
            this.players = players;
    
            this.horizontals = new boolean[width - 1][height];