import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

import static javafx.scene.paint.Color.*;

/**
 * Each cell of a 3x3 grid is filled with a unique color selected at random from a 
 * small list of possible colors.
 * 
 * @author Drue Coles
 */
public class ColorfulGrid extends Application {

    private static final Color[] colors = {
        DARKSLATEGRAY, DEEPPINK, CRIMSON, GREEN, INDIGO, LIME, MAGENTA, MINTCREAM, 
        ORANGE, PLUM, PURPLE, YELLOW
    };

    @Override
    public void start(Stage primaryStage) {

        Pane root = new Pane();
        final int size = 500; // length and width of scene
        Scene scene = new Scene(root, size, size, BLACK);

        final int gap = 5; // separation between adjacent cells
        int cellsize = (size - 4 * gap) / 3; // size of each cell

        Set<Color> setOfColors = getColors(9);
        Color[] listOfColors = setOfColors.toArray(new Color[]{});

        // draw 3x3 grid of square cells
        final int rows = 3;
        final int cols = 3;
        int indexOfColor = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                
                // top-left corner of cell (i, j)
                int x = gap + j * (gap + cellsize);
                int y = gap + i * (gap + cellsize);
                Rectangle cell = new Rectangle(x, y, cellsize, cellsize);

                cell.setFill(listOfColors[indexOfColor]);
                indexOfColor++;
                root.getChildren().add(cell);
            }
        }

        primaryStage.setTitle("Colorful Grid");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * Returns a set of distinct colors selected at random from the colors
     * array of this class. Returns null if there are not enough colors in
     * the array.
     * 
     * @param n the number of colors in the set to be returned
     */
    private static Set<Color> getColors(int n) {
        if (n > colors.length) {
            return null; // not enough colors
        }
        Set<Color> set = new HashSet<>();
        ThreadLocalRandom rand = ThreadLocalRandom.current();
        while (set.size() < n) {
            int i = rand.nextInt(colors.length);
            set.add(colors[i]);
        }
        return set;
    }

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