我已經建立了一個專門的卡應用程序。它的功能是允許用戶「畫」一張卡片,然後查看該卡片,並將其放回卡座中的隨機位置。我遇到的唯一問題是,卡通常放在甲板的頂部。不能完全得到隨機化
這裏是.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;
}
有什麼我可能做錯了嗎?如果您需要更多信息,請告訴我。預先感謝您提供的任何幫助。
那麼,我正在做的是我有兩個'NSMutableArray'對象。第一個(卡片)按照它們在plist文件中指定的順序保存所有_Card對象。第二個(indexArray)包含一組代表卡片'索引'編號的'NSNumber'對象。我使用Fisher-Yates算法隨機化'indexArray'數組。然後我拉出最頂端的'索引'(模擬頂部卡的拉動)。然後,我嘗試將該索引隨機放回'indexArray'中。希望這有助於理解這個問題 – 2012-07-18 18:05:51
我這樣做,並建議什麼測試,現在似乎給人的牌很好的隨機化。仍然一遍又一遍地拉同一張牌,但以更可接受的方式。謝謝 – 2012-07-18 19:36:23