0

Below is a method I wrote that takes a random number and makes sure that a sprite does repeat consecutively at the same position. I want to change it so that every new sprite takes a different position of the other two. I am not really getting it right. Please help.

- (float)randomlyChooseXValue    {
    CGSize s = [[CCDirector sharedDirector] winSize];

    int randX = arc4random() % 3;

    if (oldRandX != randX) {
        if (randX == 0) {
            xPos = xPos1*(s.width/480.0);
        } else if (randX == 1)    {
            xPos = xPos2*(s.width/480.0);
        } else {
            xPos = xPos3*(s.width/480.0);
        }
        oldRandX = randX;
    } else {
        [self randomlyChooseXValue];
    }
    return xPos;
}
4

2 回答 2

0

如果我理解正确,您需要找到 3 个随机值,而第 3 个应该与第 2 个不同。如果这是真的,您需要存储最后 2 个随机值并在第一个if语句中进行比较:

- (float)randomlyChooseXValue    {
    CGSize s = [[CCDirector sharedDirector] winSize];

    int randX = arc4random() % 3;

    if ((oldRandX1 != randX) && (oldRandX2 != randX)) { //check for 2 values
        if (randX == 0) {
            xPos = xPos1*(s.width/480.0);
        } else if (randX == 1)    {
            xPos = xPos2*(s.width/480.0);
        } else {
            xPos = xPos3*(s.width/480.0);
        }
        oldRandX2 = oldRandX1; //store 1st value to 2nd place
        oldRandX1 = randX; //store new value to 1st place
    } else {
        [self randomlyChooseXValue];
    }
    return xPos;
}
于 2013-06-10T09:44:36.140 回答
0

既然你解释说你对序列重复没问题,那么你只需要真正做出两个随机选择:第一个位置和方向。

// somewhere, initialize global oldRandX = -1, dir = -1

- (float)randomlyChooseXValue    {
    CGSize s = [[CCDirector sharedDirector] winSize];

    if (oldRandX < 0) {
        oldRandX = arc4random() % 3;
        dir = arc4random() % 2;
    } else if (dir) {
        oldRandX = (oldRandX + 1) % 3;
    } else {
        oldRandX = (oldRandX + 2) % 3;
    }

    if (randX == 0) {
        xPos = xPos1*(s.width/480.0);
    } else if (randX == 1)    {
        xPos = xPos2*(s.width/480.0);
    } else {
        xPos = xPos3*(s.width/480.0);
    }

    return xPos;
}

这可以生成三个位置的所有可能序列:

  • 0, 1, 2
  • 0, 2, 1
  • 1, 2, 0
  • 1, 0, 2
  • 2, 0, 1
  • 2, 1, 0

并重复它们。

另一个答案将达到相同的结果,但与您的原始方法一样,可能需要多次尝试才能获得它。您的随机函数可以无限次地选择错误的值;当只有一个正确的数字可供选择时,这将成为一个更严重的问题。

于 2013-06-10T16:16:24.523 回答