防止随机数重复

时间:2014-01-26 05:50:33

标签: objective-c random numbers duplicates repeat

我是一名相对较新的程序员,正在为Xcode上的纸牌游戏应用程序工作,截至目前,我生成一个随机数,以确定首先处理哪张卡。我很好奇我怎么能防止同一个数字不止一次弹出。让我们说发电机选择52和黑桃王牌被处理,当它与下一个玩家交易时,发电机仍有可能选择52,这是不行的,因为黑桃王牌已经离开了牌组。

下面是我的代码示例........

(随机数从27到52,因为到目前为止我只有黑桃和红心)

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

//Dealing Random Cards ------------------------------------------------------------------------------------------------------

self.FirstCard = arc4random() % 26+27;
NSLog(@"Random Number: %i", self.FirstCard);

//Deal First Card --------------------------------------------------------------------
if (self.FirstCard == 52) {
    SKAction *DealFirstCard = [SKAction moveToY:40 duration:0.25];
    SKAction *DealFirstCard2 = [SKAction moveToX:130 duration:0.25];
    SKAction *DealSequence = [SKAction sequence:@[DealFirstCard,DealFirstCard2]];
    [self.ASpade runAction:DealSequence];
}
if (self.FirstCard == 51) {
    SKAction *DealFirstCard = [SKAction moveToY:40 duration:0.25];
    SKAction *DealFirstCard2 = [SKAction moveToX:130 duration:0.25];
    SKAction *DealSequence = [SKAction sequence:@[DealFirstCard,DealFirstCard2]];
    [self.TwoSpade runAction:DealSequence];
}
if (self.FirstCard == 50) {
    SKAction *DealFirstCard = [SKAction moveToY:40 duration:0.25];
    SKAction *DealFirstCard2 = [SKAction moveToX:130 duration:0.25];
    SKAction *DealSequence = [SKAction sequence:@[DealFirstCard,DealFirstCard2]];
    [self.ThreeSpade runAction:DealSequence];
}

2 个答案:

答案 0 :(得分:1)

您需要在列表中保留以前的数字列表。每次生成一个数字时,您都需要确保该数字不在您的列表中。

答案 1 :(得分:0)

你应该shuffle牌组,然后迭代它。