Controlling number, location, color of randomly-generated shapes
in
Programming Questions
•
1 year ago
Hello, I'm new to the forum and this very useful program.
I'm happy to hear any help and bit of advice from anyone,
My goal is drawing a shape randomly-formed by 12 square, in a 6x6 grid. The squares should be of three different colours: 6 of a colour, 4 of another and 2 of a third colour. My problem is the way I am thinking of it.
The way I started doing it is by generating squares in random positions of the grid, then using
switch
(
)
to choose between four colours (or cases, case 0 being a white square: apparent absence of colour).
- int[][] grid;
- int cols = 6;
- int rows = 6;
- int cellSize = 40;
- void setup() {
- size(240, 240);
- frameRate(1);
- grid = new int[cols][rows];
- for (int x = 0; x < cols; x++ ) {
- for (int y = 0; y < rows; y++ ) {
- grid[x][y] = 0;
- }
- }
- }
- void draw() {
- upd();
- background(255);
- for (int x = 0; x < cols; x++ ) {
- for (int y = 0; y < rows; y++ ) {
- switch(grid[x][y]) {
- case 0: // empty - fill with white
- fill(255);
- break;
- case 1: // fill with pinkish colour
- fill(255, 160, 160);
- break;
- case 2: // fill with yellowish colour
- fill(220, 215, 165);
- break;
- case 3: // fill with greenish colour
- fill(125, 200, 175);
- break;
- }
- stroke(255);
- rect(x*cellSize, y*cellSize, cellSize, cellSize);
- }
- }
- }
- void upd() {
- for (int x = 0; x < cols; x++ ) {
- for (int y = 0; y < rows; y++ ) {
- grid[x][y] = int(random(0, 4));
- }
- }
- }
• Step 2 would be to increase the number of white squares to 24, decrease the pink ones to 6, the greenish ones to 4 and the yellowish ones to 2. Therefore
case 0 should execute 24 times out of 36,
case 1 6 times out of 36 and so on.
• Step 3 would be to somehow get the similarly-coloured squares closer together, thus creating some kind of coherent shape. I am really lost here.
I think what I am doing wrong is generating rectangle and filling them with white to
simulate absence of colour. Also I feel the way I am thinking is wrong. Should I randomly generate squares? Or rather draw
one square and draw another one close to it (according to its original x,y) then fill it with the same colour... Repeat 11 times..?
I'm happy to hear any help and bit of advice from anyone,
Thanks in advance for your time and knowledge
1