1
+ // variables
2
+ int numRows = 10 ;
3
+ int numColumns = 10 ;
4
+ int tileSize;
5
+
6
+
7
+ // processing setup
8
+ void setup () {
9
+ // initial setup
10
+ background (0 ); // set the background to black
11
+ size (400 , 400 ); // set the dimension of the canvas
12
+
13
+ drawGrid(); // call the method once to draw the grid
14
+ }
15
+
16
+ void draw () {
17
+ // nothing is needed here
18
+ }
19
+
20
+
21
+ // processing event handlers
22
+ void mousePressed () {
23
+ // obtain the ratio of the mouse position versus the x and y axies
24
+ // the float() method is called to cast (force)
25
+ // the integer variables into floating point numbers
26
+ // so that the division work
27
+ float ratioX = float (mouseX ) / float (width );
28
+ float ratioY = float (mouseY ) / float (height );
29
+
30
+ // calculate the position of the tile to color
31
+ // by getting at which tile index the mouse is located
32
+ // and then multiply the index by the tile size
33
+ // to get the coordinates to draw a colored tiled
34
+ int tileX = floor (ratioX * numColumns) * tileSize;
35
+ int tileY = floor (ratioY * numRows) * tileSize;
36
+
37
+ // set random rgb values to the fill
38
+ fill (
39
+ floor (random (255 )), // get random red
40
+ floor (random (255 )), // get random green
41
+ floor (random (255 )) // get random blue
42
+ );
43
+
44
+ // draw the rectangle
45
+ rect (
46
+ tileX, tileY, // coordinates
47
+ tileSize, tileSize // dimensions
48
+ );
49
+
50
+ // release the fill, so next method calling fill
51
+ // is not stuck with last color set
52
+ noFill ();
53
+ }
54
+
55
+
56
+ // custom methods definitions
57
+ void drawGrid () {
58
+ // get tile size
59
+ tileSize = width / numColumns;
60
+
61
+ // init tile positions
62
+ int tileX = 0 ;
63
+ int tileY = 0 ;
64
+
65
+ // iterate through the columns
66
+ for (int i = 0 ; i < numColumns; i++ ) {
67
+ // draw each column
68
+ for (int j = 0 ; j < numRows; j++ ) {
69
+ // calculate the position of the tile
70
+ tileX = i * tileSize;
71
+ tileY = j * tileSize;
72
+ // draw the tile
73
+ rect (tileX, tileY, tileSize, tileSize);
74
+ }
75
+ }
76
+ }
0 commit comments