hugo
June 12, 2019, 5:16pm
1
hello,
here is my program :
int AM=0;
int R=0;
void setup() {
frameRate(30);
size(480,320);
}
void draw() {
background(255);
stroke(180);
strokeWeight(2);
for (int ix = 64; ix < 315; ix = ix+64) {
line(0, ix, width, ix);
} for (int iy = 96; iy < 475; iy = iy+96) {
line(iy, 0, iy, height);
}
fill(0);
textSize(35);
textAlign(CENTER,CENTER);
for (int i2y = 32; i2y < 289; i2y = i2y + 64) {
for (int i2x = 48; i2x < 433; i2x = i2x + 96) {
text(AM,i2x,i2y);
if (AM<24) {
AM=AM+1;
} else {
AM=0;
i2y = 32;
i2x = 48;
}
}
}
//
}
I would like that when we click on a box the variable R takes the value of this box. But I do not want to rewrite:
if (mousePressed && mouseX<96 && mouseX>0 && mouseY<64 && mouseY>0) {
R=24;
}
25 times for each box.
Is it possible to simplify the code?
Thank you.
2 Likes
Hey There!
Each box has it’s size and co-ordinates so building a class and making 25 objects from with a method that checks collision will have you only write the method once but work for all objects which use that class!
2 Likes
for a solution without class / oop think along these lines:
int AM=0;
int R=0;
void setup() {
size(480, 320);
}
void draw() {
background(255);
stroke(180);
strokeWeight(2);
fill(0);
textSize(35);
textAlign(CENTER, CENTER);
int cellSize=30;
for (int i2y = 0; i2y < 8; i2y = i2y + 1) {
for (int i2x = 0; i2x < 8; i2x = i2x + 1) {
rect( i2x * cellSize, i2y * cellSize, cellSize, cellSize);
}
}
}
void mousePressed() {
int cellSize=30;
fill(255, 0, 0); // RED
for (int i2y = 0; i2y < 8; i2y = i2y + 1) {
for (int i2x = 0; i2x < 8; i2x = i2x + 1) {
if (mouseX > i2x * cellSize
&& mouseX < i2x * cellSize + cellSize
&& mouseY > i2y * cellSize
&& mouseY < i2y * cellSize + cellSize)
rect( i2x * cellSize, i2y * cellSize, cellSize, cellSize);
}
}
}
2 Likes
additionally use a two-dimensional array to store the values for R in
see tutorial:
https://www.processing.org/tutorials/2darray/
2 Likes