Source/CheckersGame.m
author Jens Alfke <jens@mooseyard.com>
Mon Jul 07 15:47:42 2008 -0700 (2008-07-07)
changeset 12 4e567e11f45f
parent 11 436cbdf56810
child 15 73f8c889f053
permissions -rw-r--r--
Added new convenience methods for Game implementations.
     1 /*  This code is based on Apple's "GeekGameBoard" sample code, version 1.0.
     2     http://developer.apple.com/samplecode/GeekGameBoard/
     3     Copyright © 2007 Apple Inc. Copyright © 2008 Jens Alfke. All Rights Reserved.
     4 
     5     Redistribution and use in source and binary forms, with or without modification, are permitted
     6     provided that the following conditions are met:
     7 
     8     * Redistributions of source code must retain the above copyright notice, this list of conditions
     9       and the following disclaimer.
    10     * Redistributions in binary form must reproduce the above copyright notice, this list of
    11       conditions and the following disclaimer in the documentation and/or other materials provided
    12       with the distribution.
    13 
    14     THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
    15     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
    16     FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
    17     BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
    18     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
    19     PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
    20     CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
    21     THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    22 */
    23 #import "CheckersGame.h"
    24 #import "Grid.h"
    25 #import "Piece.h"
    26 #import "QuartzUtils.h"
    27 #import "GGBUtils.h"
    28 
    29 
    30 @implementation CheckersGame
    31 
    32 
    33 static NSMutableDictionary *kPieceStyle1, *kPieceStyle2;
    34 
    35 + (void) initialize
    36 {
    37     if( self == [CheckersGame class] ) {
    38         kPieceStyle1 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
    39                         (id)GetCGImageNamed(@"Green.png"), @"contents",
    40                         kCAGravityResizeAspect, @"contentsGravity",
    41                         kCAFilterLinear, @"minificationFilter",
    42                         nil];
    43         kPieceStyle2 = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
    44                         (id)GetCGImageNamed(@"Red.png"), @"contents",
    45                         kCAGravityResizeAspect, @"contentsGravity",
    46                         kCAFilterLinear, @"minificationFilter",
    47                         nil];
    48     }
    49 }
    50 
    51 
    52 - (id) init
    53 {
    54     self = [super init];
    55     if (self != nil) {
    56         [self setNumberOfPlayers: 2];
    57         
    58         PreloadSound(@"Tink");
    59         PreloadSound(@"Funk");
    60         PreloadSound(@"Blow");
    61         PreloadSound(@"Pop");
    62     }
    63     return self;
    64 }
    65 
    66 - (CGImageRef) iconForPlayer: (int)playerNum
    67 {
    68     return GetCGImageNamed( playerNum==0 ?@"Green.png" :@"Red.png" );
    69 }
    70 
    71 - (Piece*) pieceForPlayer: (int)playerNum
    72 {
    73     Piece *p = [[Piece alloc] init];
    74     p.bounds = CGRectMake(0,0,floor(_grid.spacing.width),floor(_grid.spacing.height));
    75     p.style = (playerNum ?kPieceStyle2 :kPieceStyle1);
    76     p.owner = [self.players objectAtIndex: playerNum];
    77     p.name = playerNum ?@"2" :@"1";
    78     return [p autorelease];
    79 }
    80 
    81 - (void) makeKing: (Piece*)piece
    82 {
    83     piece.scale = 1.4;
    84     piece.tag = YES;        // tag property stores the 'king' flag
    85     piece.name = piece.owner.index ?@"4" :@"3";
    86 }
    87 
    88 - (void) setUpBoard
    89 {
    90     RectGrid *grid = [[RectGrid alloc] initWithRows: 8 columns: 8 frame: _board.bounds];
    91     _grid = grid;
    92     [_board addSublayer: _grid];
    93     CGPoint pos = _grid.position;
    94     pos.x = floor((_board.bounds.size.width-grid.frame.size.width)/2);
    95     grid.position = pos;
    96     grid.allowsMoves = YES;
    97     grid.allowsCaptures = NO;
    98     grid.cellColor = CreateGray(0.0, 0.25);
    99     grid.altCellColor = CreateGray(1.0, 0.25);
   100     grid.lineColor = nil;
   101 
   102     for( int i=0; i<32; i++ ) {
   103         int row = i/4;
   104         [_grid addCellAtRow: row column: 2*(i%4) + (row&1)];
   105     }
   106     [_grid release]; // its superlayer still retains it
   107 }
   108 
   109 - (NSString*) initialStateString            {return @"111111111111--------222222222222";}
   110 - (NSString*) stateString                   {return _grid.stateString;}
   111 - (void) setStateString: (NSString*)state   {_grid.stateString = state;}
   112 
   113 - (Piece*) makePieceNamed: (NSString*)name
   114 {
   115     int which = [name characterAtIndex: 0] - '1';
   116     if( which >=0 && which < 4 ) {
   117         Piece *piece = [self pieceForPlayer: (which & 1)];
   118         if( which & 2 ) 
   119             [self makeKing: piece];
   120         return piece;
   121     } else
   122         return nil;
   123 }
   124 
   125 
   126 - (BOOL) canBit: (Bit*)bit moveFrom: (id<BitHolder>)srcHolder to: (id<BitHolder>)dstHolder
   127 {
   128     Square *src=(Square*)srcHolder, *dst=(Square*)dstHolder;
   129     if( bit.tag )
   130         if( dst==src.bl || dst==src.br || dst==src.l || dst==src.r
   131            || (src.bl.bit.unfriendly && dst==src.bl.bl) || (src.br.bit.unfriendly && dst==src.br.br) )
   132             return YES;    
   133     return dst==src.fl || dst==src.fr
   134         || (src.fl.bit.unfriendly && dst==src.fl.fl) || (src.fr.bit.unfriendly && dst==src.fr.fr);
   135 }
   136 
   137 - (void) bit: (Bit*)bit movedFrom: (id<BitHolder>)srcHolder to: (id<BitHolder>)dstHolder
   138 {
   139     Square *src=(Square*)srcHolder, *dst=(Square*)dstHolder;
   140     int playerIndex = self.currentPlayer.index;
   141     
   142     Turn *turn = self.currentTurn;
   143     if( turn.move.length==0 )
   144         [turn addToMove: src.name];
   145     [turn addToMove: @"-"];
   146     [turn addToMove: dst.name];
   147     
   148     BOOL isKing = bit.tag;
   149     PlaySound(isKing ?@"Funk" :@"Tink");
   150 
   151     // "King" a piece that made it to the last row:
   152     if( !isKing && (dst.row == (playerIndex ?0 :7)) ) {
   153         PlaySound(@"Blow");
   154         [self makeKing: (Piece*)bit];
   155         [turn addToMove: @"*"];
   156         // don't set isKing flag - piece can't jump again after being kinged.
   157     }
   158 
   159     // Check for a capture:
   160     NSArray *line = [src lineToCell: dst inclusive: NO];
   161     if( line.count==1 ) {
   162         Square *capture = [line objectAtIndex: 0];
   163         [capture destroyBit];
   164         [turn addToMove: @"!"];
   165         PlaySound(@"Pop");
   166         
   167         // Now check if another capture is possible. If so, don't end the turn:
   168         if( (dst.fl.bit.unfriendly && dst.fl.fl.empty) || (dst.fr.bit.unfriendly && dst.fr.fr.empty) )
   169             return;
   170         if( isKing )
   171             if( (dst.bl.bit.unfriendly && dst.bl.bl.empty) || (dst.br.bit.unfriendly && dst.br.br.empty) )
   172                 return;
   173     }
   174     
   175     [self endTurn];
   176 }
   177 
   178 - (Player*) checkForWinner
   179 {
   180     NSCountedSet *remaining = _grid.countPiecesByPlayer;
   181     if( remaining.count==1 )
   182         return [remaining anyObject];
   183     else
   184         return nil;
   185 }
   186 
   187 
   188 - (BOOL) applyMoveString: (NSString*)move
   189 {
   190     GridCell *src = nil;
   191     for( NSString *ident in [move componentsSeparatedByString: @"-"] ) {
   192         while( [ident hasSuffix: @"!"] || [ident hasSuffix: @"*"] )
   193             ident = [ident substringToIndex: ident.length-1];
   194         GridCell *dst = [_grid cellWithName: ident];
   195         if( dst == nil )
   196             return NO;
   197         if( src && ! [self animateMoveFrom: src to: dst] )
   198             return NO;
   199         src = dst;
   200     }
   201     return YES;
   202 }
   203 
   204 
   205 @end