This code works fine but it would be too long if the score is 50 or over. Is there any way to make it shorter and quicker? I tried to use for loop statement but it didn't work well.

  background(backgroundChange);
  if (score >= 5 && score < 10)
    backgroundChange-=0.8;
  else if (score >= 10 && score < 15)
    backgroundChange+=0.8;
  else if (score >= 15 && score < 20)
    backgroundChange-=0.8;

Dani AI

Generated

posted a repeating 5-point pattern (5–9, 10–14, 15–19, …) and was right to point toward using arithmetic instead of many if/else branches. A compact, scalable approach is to compute the 5-point block index (integer division by 5) and use the block parity to pick +0.8 or -0.8. The same logic works for any score value and is easy to tune by changing the block size or delta.

int range = 5;                // size of each block (5 points)
double delta = 0.8;           // amount to change
if (score >= range) {
    int block = score / range;          // 1 => 5-9, 2 => 10-14, 3 => 15-19, ...
    backgroundChange += ( (block & 1) == 0 ? delta : -delta );
}

Notes and cautions: block parity maps odd blocks (1,3,5,...) to subtract and even blocks to add, matching the original sequence. To start with a +0.8 for 5–9 instead, flip the conditional or negate the result. For negative scores use Math.floorDiv(score, range) to get consistent floor behavior; for non-integer ranges keep range as double and compute a floor-based block. Keep the update to backgroundChange tied to the event that changes score (rather than every frame) to avoid repeated application. This method is simple, fast, and keeps the intent clear while avoiding long chains of else/if.

Recommended Answers

All 3 Replies

Does that pattern repeat, eg score 35-40 change -=.8, score 40-45 change +=.8 etc ?

Yes that's right.

OK, you could use the % operator to take the remainder after dividing score by 10.
Now all your values are 0-9 and you have only one test (>= 5) in a single if/then/else

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.