문제

Hey there, So I'm knocking together a random pattern generation thing.

My code so far:

  int permutes = 100;
  int y = 31;
  int x = 63;

  while (permutes > 0) {
    int rndTurn = random(1, 4);

    if (rndTurn == 1) { y = y - 1; } //go up
    if (rndTurn == 2) { y = y + 1; } //go down
    if (rndTurn == 3) { x = x - 1; } //go right
    if (rndTurn == 4) { x = x + 1; } //go left

    setP(x, y, 1);
    delay(250);
  }

My question is, how would I go about getting the code to not go back on itself?

e.g. The code says "Go Left" but the next loop through it says "Go Right", how can I stop this?

NOTE: setP turns a specific pixel on.

Cheers peoples!

도움이 되었습니까?

해결책

Not sure if this approach will work.

Create a new variable called lastRndTurn as int, and assign this after your if statements. Then add a new while loop after your int rndTurn = random(1, 4).

while (lastRndTurn == rndTurn)
{
    rndTurn = random(1, 4);
}

다른 팁

It depends on what you mean.

If you mean "avoid going back to a step I was most previously on" then you have to remember the direction of the last movement. That is if you move up your next movement can't be down.

If you mean "avoid going back on a spot you've ever been on" then you're going to have to remember every spot you've been on. This can be implemented efficiently with a hash table using a key with a class representing a coordinate with appropriate Equals/HashCode functions.

Since each square corresponds to a pixel, your coordinate space must be finite, so you could keep track of coordinates you've already visited.

If there's a corresponding getP function to determine if a pixel has already been turned on, you could just use that.

You remember the last direction and, using random(1,3), pick either of the remaining three, then store that as the last one.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top