Making a Semi-Looping Method

Hello Community! I am trying to create a gameboard for a small game I started making, but I hav encountered a problem, I couldn't solve yet. The gameboard ground consists of rectangles, filled with images ( 38x21 ). I want each rectangle to be filled with a randomized image, which is then saved and the same board redrawn in the methode draw() . So far it is always filling the rectangles with always new randomized images, which makes the gameboard look all weird (constant color changes). Here is the code I use to draw it:

draw() {
    for (int j = 0; j < 21; j ++) {
        squarePositionY[j] = squarePositionYVariable;
        squarePositionYVariable = squarePositionYVariable + 48;
        squarePositionXVariable = 48;
        for (int i = 0; i < 38; i++) {
            squarePositionX[i] = squarePositionXVariable;
            squarePositionXVariable = squarePositionXVariable + 48;
            groundimagerandom = random(0, 100);
            if ( groundimagerandom > 40) {
                image(groundLevelOne, squarePositionX[i], squarePositionY[j]);
            } else if ( groundimagerandom < 41) {
                image(groundLevelOneRotten, squarePositionX[i], squarePositionY[j]);
            }
        }
    }
}

Thanks for a short answer!

Answers

  • The draw method draws a single frame. So in your draw method you are creating a random number with

    groundimagerandom = random(0, 100);

    EVERY frame.

    groundimagerandom should be calculated once in setup.

    See this topic for more info on setup and draw

  • If I have groundimagerandom = random(0, 100); calculated only once in setup(), the ground will not look weird, but only have one colour and not different ones, like it is supposed to (see my code).

  • edited June 2015

    Then you will need to remember more than one number! In fact, you will need to remember which image each grid rectangle is using. Here is a simple example of how to do this using different colors:

    color[] colors = { 
      color(255, 0, 0), color(0, 255, 0), color(0, 0, 255), color(0), color(255), color(255, 255, 0), color(255, 0, 255), color(0, 255, 255)
    };
    int[][] which_color = new int[4][4];
    
    void setup() {
      size(200, 200);
      for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
          which_color[i][j] = int(random(colors.length));
        }
      }
    }
    
    void draw() {
      for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 4; j++) {
          fill(colors[which_color[i][j]]);
          rect(i*50, j*50, 50, 50);
        }
      }
    }
    
  • you will have to store the random value for each tile.

    alternatively, keep a count, incrementing it in the inner loop and use randomSeed(count) before each call to random(0, 100);

Sign In or Register to comment.