public
Created

Deck Files

  • Download Gist
Deck.h
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
//
// Deck.h
// colonists
//
// Created by Nader Hendawi on 2/3/13.
// Copyright (c) 2013 Nader Hendawi. All rights reserved.
//
 
#import <Foundation/Foundation.h>
@class Tile;
 
@interface Deck : NSObject <NSCoding>
 
@property (nonatomic) NSArray *tiles;
@property int tilesRemaining;
 
- (void)shuffle;
- (void)setUpTiles;
- (Tile *)draw;
- (int)tilesRemaining;
 
@end
Deck.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
//
// Deck.m
// colonists
//
// Created by Nader Hendawi on 2/3/13.
// Copyright (c) 2013 Nader Hendawi. All rights reserved.
//
 
#import "Deck.h"
#import "Tile.h"
 
@implementation Deck {
NSMutableArray *_tiles;
 
}
 
- (id)init {
if ((self = [super init])) {
_tiles = [NSMutableArray arrayWithCapacity:20];
NSMutableArray *numberArray = [[NSMutableArray alloc] initWithObjects:@"2",@"3", @"3", @"4", @"4", @"5", @"5", @"6", @"6", @"7", @"8", @"8", @"9", @"9", @"10", @"10", @"11", @"11", @"12", @"13", nil];
for (Resource resource = ResourceBrick; resource <= ResourceOre; ++resource) {
for (int rcount = 0; rcount <= 3; ++rcount) {
int i = arc4random() % [numberArray count];
NSString *newValue = [numberArray objectAtIndex:i];
Tile *tile = [[Tile alloc] initWithResource:resource value:[newValue intValue]];
[_tiles addObject:tile];
[numberArray removeObjectAtIndex:i];
}
}
}
return self;
}
 
-(NSArray *)tiles {
return _tiles;
}
 
- (int)tilesRemaining {
return[_tiles count];
}
 
- (void)shuffle {
NSUInteger count = [_tiles count];
NSMutableArray *shuffled = [NSMutableArray arrayWithCapacity:count];
for (int t=0; t < count; ++t) {
int i = arc4random() % [self tilesRemaining];
Tile *tile = [_tiles objectAtIndex:i];
[shuffled addObject:tile];
[_tiles removeObjectAtIndex:i];
}
NSAssert([self tilesRemaining] == 0, @"Original deck should now be empty");
_tiles = shuffled;
}
 
- (Tile *)draw {
NSAssert([self tilesRemaining] > 0, @"No more tiles in the deck");
Tile *tile = [_tiles lastObject];
[_tiles removeLastObject];
return tile;
}
 
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.tilesRemaining = [aDecoder decodeIntForKey:@"tilesRemaining"];
}
}
 
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInteger:self.tilesRemaining forKey:@"tilesRemaining"];
}
 
@end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.