我已经建立了专门的卡片应用程序。它的作用是允许用户“绘制”一张卡片,然后查看该卡片,并将其放回到卡片中的随机位置。我遇到的唯一问题是,卡片通常放在卡座的顶部。
以下是.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;
}
有什么我可能做错了吗?如果您需要更多信息,请告诉我。提前感谢您提供的任何帮助。
答案 0 :(得分: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];
}
你的代码似乎没问题,我猜它只是不喜欢删除对象之前...我添加了日志,所以你可以看到它是否真的每次都插入顶部。给我一个更新 - 如果这不起作用,我可以看看你的项目文件。
答案 1 :(得分:0)
“通常不是”意味着什么?
你在这里展示的东西看起来很完美....
请记住,这是随机,并且很可能(尽管很少见)连续10次获得特定数字。 从长远来看,你应该得到均匀分布。
运行此例行程序10,000,000次左右,并检查每个号码的次数(确保每次在牌组中有相同数量的牌),然后才能确定出现问题。
另外,你确定你的indexArray包含正确的值,并且你没有在那里复制0吗?