Easier way to write if else statement

Hey, I was just wondering if there exists an easier way to write the following code?

    if (lives == 3) { //
      image(heart, heartX1, heartY, heartWH, heartWH);
      image(heart, heartX2, heartY, heartWH, heartWH);
      image(heart, heartX3, heartY, heartWH, heartWH);
    } else if (lives == 2) {
      image(heart, heartX1, heartY, heartWH, heartWH);
      image(heart, heartX2, heartY, heartWH, heartWH);
    } else if (lives == 1) {
      image(heart, heartX1, heartY, heartWH, heartWH);
    }
1 Like

Processing.org/reference/switch.html

2 Likes

Hello,

and welcome to the forum! Nice to have you here!

The command if() can be replaced with switch() (in this case).

Approach with a For-loop

In this case: You could also use a for-loop

for(int i=0; i<=lives; i++) 
    image(heart, (heartX1-15) + i*(heartWH+12) , heartY , heartWH, heartWH);

This for-loop

  • uses lives as upper bound (i<=lives), so that the number of loops is determined by the variable lives (how many hearts we see)
  • uses i to calculate the x position for each heart: (heartX1-15) + i*(heartWH+12). This can be simplified.

Remark

I would recommend to use image only with 3, not with 5 parameters. This slows things down. Avoid this everywhere in your game!

Instead apply resize() command once to “heart” in setup().

Chrisir

3 Likes

Thank you it was the for loop approach i was looking for

1 Like

Tried the resize function for my graphic, unfortunately it seems to apply anti-aliasing even though no smooth is on

Oh, I didn’t know that.
Still image() with 5 parameters is much slower.

Maybe you can copy images and change in external graphics program

Hello,

Welcome to the Processing forum.

This is my first pass at this:

int [] x = {100, 200, 300};
int [] y = {300, 200, 100};

int lives = 3;
 
 for (int i = 0; i < lives; i++)
    {
    xl = x[i];
    yl = y[i];
    image(image1, xl, yl);
    }

(xl, yl) can be anything you want; I put data into an array for testing only.

Update: I did not realize I was answering this so late; I do not always look at other posts as this influences my “first pass” coding efforts. I will leave it…

2 Likes