0

我已经建立了一个专门的卡片应用程序。它的作用是允许用户“绘制”一张卡片,然后查看卡片,并将其放回牌组中的随机位置。我遇到的唯一问题是,通常情况下,卡片被放在牌堆的顶部。

这是 .h 文件的内容:

@class _Card;

@interface _Deck : NSObject

@property (readonly) NSString *deckData;
@property (readonly) NSUInteger count;
@property (readonly) NSUInteger deckCount;
@property (readonly) BOOL needsReset;
@property (readonly) NSArray *cards;

- (id)initWithArray:(NSArray *)array;
- (id)initWithContentsOfFile:(NSString *)filePath;

- (void)shuffle;
- (NSArray *)draw;
- (void)reset;
- (void)changeEdition;

@end

现在,这是我的抽牌方法,它会抽一张牌(如果牌有指定,则多张牌),然后将这张牌放回牌组,如果允许的话:

- (NSArray *)draw {

    // first, we create an array that can be returned, populated with the
    // cards that we drew
    NSMutableArray *drawArray = [[[NSMutableArray alloc] init] autorelease];

    // next, we get the top card, which is actually located in the 
    // indexArray (I use this for shuffling, pulling cards, etc.)
    NSNumber *index = [[[indexArray objectAtIndex:0] retain] autorelease];

    // now we get the card that the index corresponds to
    // from the cards array
    _Card *card = [cards objectAtIndex:[index integerValue]];

    // now I remove the index that we 
    // got from the indexArray...don't worry,
    // it might be put back in
    [indexArray removeObject:index];

    // if the card is supposed to discard after
    // draw, we leave it out
    if(!card.discard) {

        int insertIndex = arc4random_uniform(indexArray.count);

        // then I insert the card into the deck using the random, random 
        // number
        [indexArray insertObject:index atIndex:insertIndex];
    }

    _Card *cardCopy = [card copy];

    // we add the card to the array 
    // that we will return
    [drawArray addObject:cardCopy];

    // next, if the card is not the final card...
    if(!card.final) {

        // ...and the card has an 
        // additional draw specified...
        if(card.force) {

            // we keep drawing until we need to stop
            [drawArray addObjectsFromArray:[self draw]];
        }
    }

    return drawArray;
}

有什么我可能做错了吗?如果您需要更多信息,请告诉我。提前感谢您提供的任何帮助。

4

2 回答 2

0

如果我理解正确,问题是它在 indexArray 的索引 0 处插入卡?

好的,你有没有尝试过这样的事情:

(暂时不要使用这条线[indexArray removeObject:index];

if(!card.discard)
{
    int insertIndex = arc4random_uniform(indexArray.count);
    id obj = [indexArray objectAtIndex:index];
    [indexArray removeObjectAtIndex:index];
    [indexArray insertObject:obj atIndex:insertIndex];
NSLog(@"insertIndex is %i and obj is %@", insertIndex, obj);
}
else
{
    [indexArray removeObjectAtIndex:index];
}

您的代码似乎没问题,我猜它只是不喜欢删除对象之前...我添加了日志只是为了让您可以查看它是否真的每次都将其插入顶部。给我一个更新 - 如果这不起作用,我可以看看你的项目文件。

于 2012-07-18T17:49:01.097 回答
0

“经常”是什么意思?

你在这里展示的看起来很完美......

请记住,这是随机的,很有可能(尽管很少见)连续 10 次获得特定数字。 从长远来看,你应该得到一个均匀的分布。

运行此例程 10,000,000 次左右,并检查您获得每个数字的次数(确保每次在牌堆中拥有相同数量的卡片),然后再确定有问题。

另外,您确定您的 indexArray 包含正确的值并且您没有在其中复制 0 吗?

于 2012-07-18T18:52:08.790 回答