Using an if statement within loops? - Processing

processing else if
processing reference
processing if while
while loop examples processing
processing functions
processing methods
processing resources
processing help

Lets say I have to use an if statement within a for loop and the for loop fires at a certain condition and the if statement only fires when the for loop has reached a certain stage.

For example, the condition is a counter that counts up when a certain thing happens such as a ball falling down the screen. circles are drawn one by one everytime the ball crosses the screen. When the circles in the first row have reached the end of the screen, the circles start appearing on the second row below the first one. However the second row isnt working for me, which I have implemented with the if statement.

float BallY = 50; // y value of the ball
float BallX = 260; // x value of the ball
float ScoreX = 52;
float ScoreY = 40;
int counter;


void setup()
{
  size(512, 348); //width and height of screen
  counter = 0;
}

void draw()
{
  frameRate(600);
  background(255);
  fill(0);
  ellipse(BallX, BallY, 15, 15); //ball that will fall 
  BallY++; //ball's y value increases each frame
  if (BallY > height) //if ball's y value is greater than the screen
  {
    BallY = 0; //reset the y value of the ball back to 0
    counter++;
  }

  for (int i = 0; i < counter; i++) { 
    ellipse(ScoreX + i * 80, 40, 40, 40); // draw circles in the first row one by one

     if( ScoreX + i * 80 > width) // if the circles cross the width
     {
     i = 0; //reset i to be 0
     ellipse(ScoreX + i * 80, 80, 40, 40); // draw circles in the second row
     }
  }}

The if statement is meant to fire only when the balls on the first row are crossing the width, however the whole game just stops instead of firing that row, what seems to be the issue?

First advice: learn the proper Java coding convention, learn how to indent your code, and learn to name your variable.

A slight rewrite on your code should make a readable fix:

int scoreStartX = 52;
int scoreStartY = 40;
int scoreBallSize = 40;
// scorePosX/Y means the position the score-ball should be drawn
scorePosX = scoreStartX;  // scoreStartX/Y = starting position of score balls 
scorePosY = scoreStartY;

for (int i = 0; i < score; i++) { 
    ellipse(scorePosX , scorePosY , scoreBallSize , scoreBallSize);

    // increment the positions, and wrap to next col if over screen width
    scorePosX += scoreBallSize ;


   if( scorePosX  > screenWidth) { // next score ball position is beyond the screen
       scorePosX = scoreStartX;
       scorePosY += scoreBallSize;
   }
}

Further refactoring the code to make use of something like Point to represent coordinate

Point scoreStartPos = new Point(52, 40);
int scoreBallSize = 40;
Point scorePos = new Point(scoreStartPos );

for (int i = 0; i < score; i++) { 
   drawCircle(scorePos, scoreBallSize); // a little helper method makes your code easier to read

    // increment the positions, and wrap to next col if over screen width
    scorePos.translate( +scoreBallSize, 0);


   if( scorePos.getX() > screenWidth) { // next score ball position is beyond the screen
       scorePos.setLocation(scoreStartPoint.getX(),
                            scorePos.getY() + scoreBallSize);
   }
}

The loop, Nested for() loops can be used to // generate two-dimensional patterns for (int i If the test is false, jump to step 6. In the init statement, the value i is created and set to zero. i is less than 40, This variable name will be assigned to each element of the array in turn as the for moves through the entire array. Using if-else statements within for loops Now that we’ve learned about if-else statements and for loops in R, we can take things to the next level and use if-else statements within our for loops to give us the results of multiple matches.

This statement

i = 0; //reset i to be 0

resets the loop index and is therefore likely to cause an infinite loop.

else \ Language (API) \ Processing 3+, It specifies a block of code to execute when the expression in if is false. Syntax, if (expression) { statements } else { statements } if (expression)  The loop continues until the test evaluates to false. When a for structure is executed, the following sequence of events occurs: 1. The init statement is run. 2. The test is evaluated to be true or false. 3. If the test is true, jump to step 4. If the test is false, jump to step 6. 4. Run the statements within the block. 5.

You are setting i to 0 every time ScoreX + i * 80 > width, right? There are no changes to ScoreX or width, meaning that the loop will simply count back up to whatever value of i makes that condition true, putting you in an infinite loop.

Conditionals1 \ Examples \ Processing.org, They allow a program to decide to take one action if the answer to a question The questions asked within a program are always logical or relational statements​. i += 10) { // If 'i' divides by 20 with no remainder draw // the first line, else draw​  Nested If-else Statements ; Nested Else-if statements ; If statement. It is one of the powerful conditional statement. If statement is responsible for modifying the flow of execution of a program. If statement is always used with a condition. The condition is evaluated first before executing any statement inside the body of If.

Hope you have found the answer to your question. I give you a possible answer which involves object oriented programming.

Your question is a little bit above the basic stuff.

So a possible answer:

float BallY = 50; // y value of the ball
float BallX = 260; // x value of the ball
int counter = 0;

score[] scores; // object oriented programming
int n = 50; // number of objects

void setup() {
  size(512, 348); //width and height of screen
  frameRate(600);

  scores = new score[n]; // object oriented
  float myx = 40;
  float myy = 40;

  for (int i = 0; i < n; i++) {
    // here we create our n score objects
    // here n = 50 so 50 objects are created.
    scores[i] = new score(myx, myy);
    // here we increase the x coordinate
    myx += 40;
    // here we check the boundaries and
    // if we go past we reset myx to 40
    // and we go one line down
    if (myx > width) {
      myx = 40;
      myy += 40;
    }
  }
}

void draw() {
  background(255);

  fill(0);
  ellipse(BallX, BallY, 15, 15); //ball that will fall 
  BallY++; //ball's y value increases each frame
  if (BallY > height) //if ball's y value is greater than the screen
  {
    BallY = 0; //reset the y value of the ball back to 0
    counter++;
  }

  // we set the color
  fill(255/1, 255/1, 255/2);
  for (int i = 0; i < counter; i++) {
    if (counter < n) {
      // we draw the object
      scores[i].score_draw();
    }
  }
}

// OBJECT ORIENTED : THE CLASS
class score {

  float myx, myy;

  score(float x, float y) {
    myx = x;
    myy = y;
  }

  void score_draw() {
    ellipse(myx, myy, 40, 40);
  }
}

This works but it gets slower over time. You will have to find out why.

Hope this helps you carry on your learning of processing and programming in general.

PEACE.

Does this if statement work correctly?, I think that if statement at line 4 or 5 is true, loop starts over. Anyways, in my understanding, this function will only return false when the passed I just want the loop to start over with different i if thisstatementistrue==true. You can't always eliminate an IF-THEN statement, but when you have an IF-THEN/ELSE statement inside a loop, you can usually restructure your program by writing two loops, one for when the IF condition is TRUE, and one for when it is FALSE.

while \ Language (API) \ Processing 3+, If you have a previous version, use the reference included with your software The while structure executes a series of statements continuously the code inside the while loop will not finish until the expression inside while becomes false. Be careful — if used incorrectly, this can lock up your code (and  Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts. Since 2001, Processing has promoted software literacy within the visual arts and visual literacy within technology.

How many conditions can be used inside an if statement , Upon adding this prinln() to the code, the program started crashing processing every time I run it. Can I use nested if statements to solve this or will that not work either? See related discussion of multiple conditions in Java and short results and for loop over them and then test each case separately:  Arrays - A variation on the For Loop example that demonstrates how to use an array. ForLoopIteration - Control multiple LEDs with a for loop. switchCase - How to choose between a discrete number of values. switchCase2 - A second switch-case example, showing how to take different actions based on the characters received in the serial port.

Conditionals2 \ Examples \ Processing.org, Since 2001, Processing has promoted software literacy within the visual arts This allows conditionals to ask two or more sequential questions, each with a 0​) { stroke(255); line(i, 80, i, height/2); // If 'i' divides by 10 with no remainder } else if  This example is for Processing 3+. If you have a previous version, use the examples included with your software. If you see any errors or have suggestions, please let us know . The loop () function causes draw () to execute continuously. If noLoop is called in setup () the draw () is only executed once. In this example click the mouse to

Comments
  • Please don't deface your posts-it's completely without meaning now.
  • Did you ever get this figured out? If so, please mark an answer as accepted.
  • when you say i < score, what is "score" it hasnt been declared
  • it is your original "counter", for which it seems making more sense to call it "score". And this piece of code is for you to read and understand, not for you to blindly copy
  • Actually I would prefer using something like "Point" to represent the coordinate, instead of keeping x and y as separate variables. Further update the example to give you an idea
  • Adrian, this "point" is it a function? I have not seen it and it isn't a function inside the Processing software...
  • It is a class. Could be written by you to represent x-y coordinate of a point. Or you may simply making use Point class in JDK awt etc. The main point here is extracting proper classes and function will make your code more readable.
  • but if i don't reset i, then the circles will be drawn outside the size of the screen..
  • Then you must solve this in some other way (I did not fully understand what you want to achieve). Maybe put a second loop in there with a different loop index?
  • But then this "second loop" you talk about must fire only when the first loop has reached a certain stage.. is there a way to connect two loops in such a way?
  • Im trying to basically fill the screen with circles, every time the ball crosses the screen, circles appear and they fill the first row, then the second and eventually the whole screen
  • "fill the whole screen" sounds like two nested loops. One counting the rows, the other counting the columns.
  • but i is the one that determines the spacing of the circles.. and if i is not set back to 0, the circles will appear outside the size of the screen