Endless while() loop

Hey everyone!

I've been creating a LCD(20x4) game for a while. In the game I'm controlling a car which has to avoid upcoming blocks. Those blocks y coordinates are picked randomly. In one column are placed 2 blocks. Since the random() function can pick only from 0 to 4, it's an often scenario that y coordinates of 2 blocks are the same, so instead of two blocks i get one. In order to avoid that I had to use while() loop.

This is what I came up with:

void SettingCoordinates(){
    for(int i=0;i<4;i++){
  block_x[i]=19;
  randomSeed(analogRead(0));
  block_y[i]=random(0,4);
  
  while(block_y[1]==block_y[0]){
    randomSeed(analogRead(1));
    block_y[1]=random(0,4);
  }
  while(block_y[3]==block_y[2]){
    randomSeed(analogRead(1));
    block_y[3]=random(0,4);
}
    }
  
}

That worked just perfectly, but that was only 4 blocks on the entire screen (not enough), I needed 8 more. So I could make that by extending the code, but then it would look too clumsy. I thought that I could shrink that code a little bit:

void SettingCoordinates(){
    for(int i=0;i<12;i++){
  block_x[i]=19;
  randomSeed(analogRead(0));
  block_y[i]=random(0,4);
  
  while(i==0||i%2==0&&block_y[i]==block_y[i++]){
    randomSeed(analogRead(0));
    block_y[i]=random(0,4);
  }
    }
  
}

When I uploaded the code the LCD showed nothing( neither blocks were displayed nor the car). There must be something wrong with the while() loop. I believe it is endless, but can't figure out why.

Any help would be appreciated.

You don't need to do a randomSeed() all the time. Once at the beginning will get you to start from a random position in the random generator

You have different ways to deal with this

  • you could decide that if you pick the same, then you take the next slot below modulo number of rows (if if you are on the bottom line, you'll go to the top line). This way there is no lengthy loop if you are unlucky

  • write a function that will give you a random value different than the one you have, here is a simple example

const byte nbLines = 4;

byte getOneButNot(byte exclude)
{
  byte v;
  do {
    v = random(0, nbLines);
  } while (v == exclude);
  return v;
}


void setup() {
  Serial.begin(115200);
  randomSeed(analogRead(A0));

  for (byte i = 0; i < 10; i++) {
    byte y1, y2;
    y1 = random(0, nbLines);
    y2 = getOneButNot(y1);
    Serial.print(i);
    Serial.write('\t');
    Serial.print(y1);
    Serial.write(',');
    Serial.println(y2);
  }
}

void loop() {}