Source/BoardView.m
author Jens Alfke <jens@mooseyard.com>
Wed Jul 09 17:07:45 2008 -0700 (2008-07-09)
changeset 15 73f8c889f053
parent 14 4585c74d809c
child 16 28392c9a969f
permissions -rw-r--r--
More tweaks, including a "reversed" property for Grids to show the second player's perspective without turning the pieces upside-down.
jens@0
     1
/*  This code is based on Apple's "GeekGameBoard" sample code, version 1.0.
jens@0
     2
    http://developer.apple.com/samplecode/GeekGameBoard/
jens@0
     3
    Copyright © 2007 Apple Inc. Copyright © 2008 Jens Alfke. All Rights Reserved.
jens@0
     4
jens@0
     5
    Redistribution and use in source and binary forms, with or without modification, are permitted
jens@0
     6
    provided that the following conditions are met:
jens@0
     7
jens@0
     8
    * Redistributions of source code must retain the above copyright notice, this list of conditions
jens@0
     9
      and the following disclaimer.
jens@0
    10
    * Redistributions in binary form must reproduce the above copyright notice, this list of
jens@0
    11
      conditions and the following disclaimer in the documentation and/or other materials provided
jens@0
    12
      with the distribution.
jens@0
    13
jens@0
    14
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
jens@0
    15
    IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
jens@0
    16
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRI-
jens@0
    17
    BUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
jens@0
    18
    (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
jens@0
    19
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
jens@0
    20
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 
jens@0
    21
    THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
jens@0
    22
*/
jens@0
    23
#import "BoardView.h"
jens@0
    24
#import "Bit.h"
jens@0
    25
#import "BitHolder.h"
jens@0
    26
#import "Game.h"
jens@12
    27
#import "Turn.h"
jens@10
    28
#import "Player.h"
jens@0
    29
#import "QuartzUtils.h"
jens@0
    30
#import "GGBUtils.h"
jens@0
    31
jens@0
    32
jens@3
    33
@interface BoardView ()
jens@3
    34
- (void) _findDropTarget: (NSPoint)pos;
jens@3
    35
@end
jens@3
    36
jens@3
    37
jens@0
    38
@implementation BoardView
jens@0
    39
jens@0
    40
jens@10
    41
@synthesize gameboard=_gameboard;
jens@0
    42
jens@0
    43
jens@0
    44
- (void) dealloc
jens@0
    45
{
jens@0
    46
    [_game release];
jens@0
    47
    [super dealloc];
jens@0
    48
}
jens@0
    49
jens@0
    50
jens@10
    51
- (void) _removeGameBoard
jens@10
    52
{
jens@10
    53
    if( _gameboard ) {
jens@10
    54
        RemoveImmediately(_gameboard);
jens@10
    55
        _gameboard = nil;
jens@10
    56
    }
jens@10
    57
}
jens@10
    58
jens@10
    59
- (void) createGameBoard
jens@10
    60
{
jens@10
    61
    [self _removeGameBoard];
jens@10
    62
    _gameboard = [[CALayer alloc] init];
jens@10
    63
    _gameboard.frame = [self gameBoardFrame];
jens@10
    64
    _gameboard.autoresizingMask = kCALayerMinXMargin | kCALayerMaxXMargin | kCALayerMinYMargin | kCALayerMaxYMargin;
jens@10
    65
jens@10
    66
    // Tell the game to set up the board:
jens@10
    67
    _game.board = _gameboard;
jens@10
    68
jens@10
    69
    [self.layer addSublayer: _gameboard];
jens@10
    70
    [_gameboard release];
jens@10
    71
}
jens@10
    72
jens@10
    73
jens@10
    74
- (Game*) game
jens@10
    75
{
jens@10
    76
    return _game;
jens@10
    77
}
jens@10
    78
jens@10
    79
- (void) setGame: (Game*)game
jens@10
    80
{
jens@10
    81
    if( game!=_game ) {
jens@14
    82
        _game.board = nil;
jens@10
    83
        setObj(&_game,game);
jens@10
    84
        [self createGameBoard];
jens@10
    85
    }
jens@10
    86
}
jens@10
    87
jens@0
    88
- (void) startGameNamed: (NSString*)gameClassName
jens@0
    89
{
jens@10
    90
    Class gameClass = NSClassFromString(gameClassName);
jens@10
    91
    Game *game = [[gameClass alloc] init];
jens@10
    92
    if( game ) {
jens@10
    93
        self.game = game;
jens@10
    94
        [game release];
jens@0
    95
    }
jens@10
    96
}
jens@10
    97
jens@10
    98
jens@0
    99
- (CGRect) gameBoardFrame
jens@0
   100
{
jens@0
   101
    return self.layer.bounds;
jens@0
   102
}
jens@0
   103
jens@0
   104
jens@0
   105
- (void)resetCursorRects
jens@0
   106
{
jens@0
   107
    [super resetCursorRects];
jens@15
   108
    if( _game.okToMove )
jens@10
   109
        [self addCursorRect: self.bounds cursor: [NSCursor openHandCursor]];
jens@0
   110
}
jens@0
   111
jens@0
   112
jens@0
   113
- (IBAction) enterFullScreen: (id)sender
jens@0
   114
{
jens@10
   115
    [self _removeGameBoard];
jens@0
   116
    if( self.isInFullScreenMode ) {
jens@0
   117
        [self exitFullScreenModeWithOptions: nil];
jens@0
   118
    } else {
jens@0
   119
        [self enterFullScreenMode: self.window.screen 
jens@0
   120
                      withOptions: nil];
jens@0
   121
    }
jens@10
   122
    [self createGameBoard];
jens@10
   123
}
jens@10
   124
jens@10
   125
jens@10
   126
- (void)viewWillStartLiveResize
jens@10
   127
{
jens@10
   128
    [super viewWillStartLiveResize];
jens@10
   129
    _oldSize = self.frame.size;
jens@10
   130
}
jens@10
   131
jens@10
   132
- (void)setFrameSize:(NSSize)newSize
jens@10
   133
{
jens@10
   134
    [super setFrameSize: newSize];
jens@10
   135
    if( _oldSize.width > 0.0f ) {
jens@10
   136
        CGAffineTransform xform = _gameboard.affineTransform;
jens@10
   137
        xform.a = xform.d = MIN(newSize.width,newSize.height)/MIN(_oldSize.width,_oldSize.height);
jens@10
   138
        _gameboard.affineTransform = xform;
jens@10
   139
    } else
jens@10
   140
        [self createGameBoard];
jens@10
   141
}
jens@10
   142
jens@10
   143
- (void)viewDidEndLiveResize
jens@10
   144
{
jens@10
   145
    [super viewDidEndLiveResize];
jens@10
   146
    _oldSize.width = _oldSize.height = 0.0f;
jens@10
   147
    [self createGameBoard];
jens@0
   148
}
jens@0
   149
jens@0
   150
jens@0
   151
#pragma mark -
jens@0
   152
#pragma mark KEY EVENTS:
jens@0
   153
jens@0
   154
jens@0
   155
- (void) keyDown: (NSEvent*)ev
jens@0
   156
{
jens@0
   157
    if( self.isInFullScreenMode ) {
jens@0
   158
        if( [ev.charactersIgnoringModifiers hasPrefix: @"\033"] )       // Esc key
jens@0
   159
            [self enterFullScreen: self];
jens@0
   160
    }
jens@0
   161
}
jens@0
   162
jens@0
   163
jens@0
   164
#pragma mark -
jens@0
   165
#pragma mark HIT-TESTING:
jens@0
   166
jens@0
   167
jens@5
   168
/** Converts a point from window coords, to this view's root layer's coords. */
jens@5
   169
- (CGPoint) _convertPointFromWindowToLayer: (NSPoint)locationInWindow
jens@5
   170
{
jens@5
   171
    NSPoint where = [self convertPoint: locationInWindow fromView: nil];    // convert to view coords
jens@5
   172
    return NSPointToCGPoint( [self convertPointToBase: where] );            // then to layer coords
jens@5
   173
}
jens@5
   174
jens@5
   175
jens@0
   176
// Hit-testing callbacks (to identify which layers caller is interested in):
jens@0
   177
typedef BOOL (*LayerMatchCallback)(CALayer*);
jens@0
   178
jens@0
   179
static BOOL layerIsBit( CALayer* layer )        {return [layer isKindOfClass: [Bit class]];}
jens@0
   180
static BOOL layerIsBitHolder( CALayer* layer )  {return [layer conformsToProtocol: @protocol(BitHolder)];}
jens@0
   181
static BOOL layerIsDropTarget( CALayer* layer ) {return [layer respondsToSelector: @selector(draggingEntered:)];}
jens@0
   182
jens@0
   183
jens@0
   184
/** Locates the layer at a given point in window coords.
jens@0
   185
    If the leaf layer doesn't pass the layer-match callback, the nearest ancestor that does is returned.
jens@0
   186
    If outOffset is provided, the point's position relative to the layer is stored into it. */
jens@0
   187
- (CALayer*) hitTestPoint: (NSPoint)locationInWindow
jens@0
   188
         forLayerMatching: (LayerMatchCallback)match
jens@0
   189
                   offset: (CGPoint*)outOffset
jens@0
   190
{
jens@5
   191
    CGPoint where = [self _convertPointFromWindowToLayer: locationInWindow ];
jens@0
   192
    CALayer *layer = [_gameboard hitTest: where];
jens@0
   193
    while( layer ) {
jens@0
   194
        if( match(layer) ) {
jens@0
   195
            CGPoint bitPos = [self.layer convertPoint: layer.position 
jens@0
   196
                              fromLayer: layer.superlayer];
jens@0
   197
            if( outOffset )
jens@0
   198
                *outOffset = CGPointMake( bitPos.x-where.x, bitPos.y-where.y);
jens@0
   199
            return layer;
jens@0
   200
        } else
jens@0
   201
            layer = layer.superlayer;
jens@0
   202
    }
jens@0
   203
    return nil;
jens@0
   204
}
jens@0
   205
jens@0
   206
jens@0
   207
#pragma mark -
jens@0
   208
#pragma mark MOUSE CLICKS & DRAGS:
jens@0
   209
jens@0
   210
jens@0
   211
- (void) mouseDown: (NSEvent*)ev
jens@0
   212
{
jens@15
   213
    if( ! _game.okToMove ) {
jens@10
   214
        NSBeep();
jens@10
   215
        return;
jens@10
   216
    }
jens@10
   217
    
jens@3
   218
    BOOL placing = NO;
jens@0
   219
    _dragStartPos = ev.locationInWindow;
jens@0
   220
    _dragBit = (Bit*) [self hitTestPoint: _dragStartPos
jens@0
   221
                        forLayerMatching: layerIsBit 
jens@0
   222
                                  offset: &_dragOffset];
jens@3
   223
    
jens@3
   224
    if( ! _dragBit ) {
jens@3
   225
        // If no bit was clicked, see if it's a BitHolder the game will let the user add a Bit to:
jens@3
   226
        id<BitHolder> holder = (id<BitHolder>) [self hitTestPoint: _dragStartPos
jens@3
   227
                                                 forLayerMatching: layerIsBitHolder
jens@3
   228
                                                           offset: NULL];
jens@3
   229
        if( holder ) {
jens@3
   230
            _dragBit = [_game bitToPlaceInHolder: holder];
jens@3
   231
            if( _dragBit ) {
jens@3
   232
                _dragOffset.x = _dragOffset.y = 0;
jens@3
   233
                if( _dragBit.superlayer==nil )
jens@5
   234
                    _dragBit.position = [self _convertPointFromWindowToLayer: _dragStartPos];
jens@3
   235
                placing = YES;
jens@3
   236
            }
jens@3
   237
        }
jens@3
   238
    }
jens@3
   239
    
jens@3
   240
    if( ! _dragBit ) {
jens@3
   241
        Beep();
jens@3
   242
        return;
jens@3
   243
    }
jens@3
   244
    
jens@3
   245
    // Clicked on a Bit:
jens@3
   246
    _dragMoved = NO;
jens@3
   247
    _dropTarget = nil;
jens@3
   248
    _oldHolder = _dragBit.holder;
jens@3
   249
    // Ask holder's and game's permission before dragging:
jens@3
   250
    if( _oldHolder ) {
jens@3
   251
        _dragBit = [_oldHolder canDragBit: _dragBit];
jens@0
   252
        if( _dragBit && ! [_game canBit: _dragBit moveFrom: _oldHolder] ) {
jens@0
   253
            [_oldHolder cancelDragBit: _dragBit];
jens@0
   254
            _dragBit = nil;
jens@0
   255
        }
jens@0
   256
        if( ! _dragBit ) {
jens@0
   257
            _oldHolder = nil;
jens@0
   258
            NSBeep();
jens@0
   259
            return;
jens@0
   260
        }
jens@3
   261
    }
jens@3
   262
    
jens@3
   263
    // Start dragging:
jens@3
   264
    _oldSuperlayer = _dragBit.superlayer;
jens@3
   265
    _oldLayerIndex = [_oldSuperlayer.sublayers indexOfObjectIdenticalTo: _dragBit];
jens@3
   266
    _oldPos = _dragBit.position;
jens@3
   267
    ChangeSuperlayer(_dragBit, self.layer, self.layer.sublayers.count);
jens@3
   268
    _dragBit.pickedUp = YES;
jens@3
   269
    [[NSCursor closedHandCursor] push];
jens@3
   270
    
jens@3
   271
    if( placing ) {
jens@3
   272
        if( _oldSuperlayer )
jens@5
   273
            _dragBit.position = [self _convertPointFromWindowToLayer: _dragStartPos];
jens@3
   274
        _dragMoved = YES;
jens@3
   275
        [self _findDropTarget: _dragStartPos];
jens@3
   276
    }
jens@0
   277
}
jens@0
   278
jens@3
   279
jens@0
   280
- (void) mouseDragged: (NSEvent*)ev
jens@0
   281
{
jens@0
   282
    if( _dragBit ) {
jens@0
   283
        // Get the mouse position, and see if we've moved 3 pixels since the mouseDown:
jens@0
   284
        NSPoint pos = ev.locationInWindow;
jens@0
   285
        if( fabs(pos.x-_dragStartPos.x)>=3 || fabs(pos.y-_dragStartPos.y)>=3 )
jens@0
   286
            _dragMoved = YES;
jens@0
   287
        
jens@0
   288
        // Move the _dragBit (without animation -- it's unnecessary and slows down responsiveness):
jens@5
   289
        CGPoint where = [self _convertPointFromWindowToLayer: pos];
jens@0
   290
        where.x += _dragOffset.x;
jens@0
   291
        where.y += _dragOffset.y;
jens@0
   292
        
jens@5
   293
        CGPoint newPos = [_dragBit.superlayer convertPoint: where fromLayer: self.layer];
jens@0
   294
jens@0
   295
        [CATransaction flush];
jens@0
   296
        [CATransaction begin];
jens@0
   297
        [CATransaction setValue:(id)kCFBooleanTrue
jens@0
   298
                         forKey:kCATransactionDisableActions];
jens@0
   299
        _dragBit.position = newPos;
jens@0
   300
        [CATransaction commit];
jens@0
   301
jens@0
   302
        // Find what it's over:
jens@3
   303
        [self _findDropTarget: pos];
jens@3
   304
    }
jens@3
   305
}
jens@3
   306
jens@3
   307
jens@3
   308
- (void) _findDropTarget: (NSPoint)locationInWindow
jens@3
   309
{
jens@3
   310
    locationInWindow.x += _dragOffset.x;
jens@3
   311
    locationInWindow.y += _dragOffset.y;
jens@3
   312
    id<BitHolder> target = (id<BitHolder>) [self hitTestPoint: locationInWindow
jens@3
   313
                                             forLayerMatching: layerIsBitHolder
jens@3
   314
                                                       offset: NULL];
jens@3
   315
    if( target == _oldHolder )
jens@3
   316
        target = nil;
jens@3
   317
    if( target != _dropTarget ) {
jens@3
   318
        [_dropTarget willNotDropBit: _dragBit];
jens@3
   319
        _dropTarget.highlighted = NO;
jens@3
   320
        _dropTarget = nil;
jens@3
   321
    }
jens@3
   322
    if( target ) {
jens@3
   323
        CGPoint targetPos = [(CALayer*)target convertPoint: _dragBit.position
jens@3
   324
                                                 fromLayer: _dragBit.superlayer];
jens@3
   325
        if( [target canDropBit: _dragBit atPoint: targetPos]
jens@3
   326
           && [_game canBit: _dragBit moveFrom: _oldHolder to: target] ) {
jens@3
   327
            _dropTarget = target;
jens@3
   328
            _dropTarget.highlighted = YES;
jens@0
   329
        }
jens@0
   330
    }
jens@0
   331
}
jens@0
   332
jens@3
   333
jens@0
   334
- (void) mouseUp: (NSEvent*)ev
jens@0
   335
{
jens@0
   336
    if( _dragBit ) {
jens@0
   337
        if( _dragMoved ) {
jens@0
   338
            // Update the drag tracking to the final mouse position:
jens@0
   339
            [self mouseDragged: ev];
jens@0
   340
            _dropTarget.highlighted = NO;
jens@0
   341
            _dragBit.pickedUp = NO;
jens@0
   342
jens@0
   343
            // Is the move legal?
jens@0
   344
            if( _dropTarget && [_dropTarget dropBit: _dragBit
jens@0
   345
                                            atPoint: [(CALayer*)_dropTarget convertPoint: _dragBit.position 
jens@0
   346
                                                                            fromLayer: _dragBit.superlayer]] ) {
jens@0
   347
                // Yes, notify the interested parties:
jens@0
   348
                [_oldHolder draggedBit: _dragBit to: _dropTarget];
jens@0
   349
                [_game bit: _dragBit movedFrom: _oldHolder to: _dropTarget];
jens@0
   350
            } else {
jens@0
   351
                // Nope, cancel:
jens@0
   352
                [_dropTarget willNotDropBit: _dragBit];
jens@3
   353
                if( _oldSuperlayer ) {
jens@3
   354
                    ChangeSuperlayer(_dragBit, _oldSuperlayer, _oldLayerIndex);
jens@3
   355
                    _dragBit.position = _oldPos;
jens@3
   356
                    [_oldHolder cancelDragBit: _dragBit];
jens@3
   357
                } else {
jens@3
   358
                    [_dragBit removeFromSuperlayer];
jens@3
   359
                }
jens@0
   360
            }
jens@0
   361
        } else {
jens@0
   362
            // Just a click, without a drag:
jens@0
   363
            _dropTarget.highlighted = NO;
jens@0
   364
            _dragBit.pickedUp = NO;
jens@0
   365
            ChangeSuperlayer(_dragBit, _oldSuperlayer, _oldLayerIndex);
jens@0
   366
            [_oldHolder cancelDragBit: _dragBit];
jens@0
   367
            if( ! [_game clickedBit: _dragBit] )
jens@0
   368
                NSBeep();
jens@0
   369
        }
jens@9
   370
jens@0
   371
        _dropTarget = nil;
jens@0
   372
        _dragBit = nil;
jens@0
   373
        [NSCursor pop];
jens@0
   374
    }
jens@0
   375
}
jens@0
   376
jens@0
   377
jens@0
   378
#pragma mark -
jens@0
   379
#pragma mark INCOMING DRAGS:
jens@0
   380
jens@0
   381
jens@0
   382
// subroutine to call the target
jens@0
   383
static int tell( id target, SEL selector, id arg, int defaultValue )
jens@0
   384
{
jens@0
   385
    if( target && [target respondsToSelector: selector] )
jens@0
   386
        return (ssize_t) [target performSelector: selector withObject: arg];
jens@0
   387
    else
jens@0
   388
        return defaultValue;
jens@0
   389
}
jens@0
   390
jens@0
   391
jens@0
   392
- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
jens@0
   393
{
jens@0
   394
    _viewDropTarget = [self hitTestPoint: [sender draggingLocation]
jens@0
   395
                        forLayerMatching: layerIsDropTarget
jens@0
   396
                                  offset: NULL];
jens@0
   397
    _viewDropOp = _viewDropTarget ?[_viewDropTarget draggingEntered: sender] :NSDragOperationNone;
jens@0
   398
    return _viewDropOp;
jens@0
   399
}
jens@0
   400
jens@0
   401
- (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
jens@0
   402
{
jens@0
   403
    CALayer *target = [self hitTestPoint: [sender draggingLocation]
jens@0
   404
                        forLayerMatching: layerIsDropTarget 
jens@0
   405
                                  offset: NULL];
jens@0
   406
    if( target == _viewDropTarget ) {
jens@0
   407
        if( _viewDropTarget )
jens@0
   408
            _viewDropOp = tell(_viewDropTarget,@selector(draggingUpdated:),sender,_viewDropOp);
jens@0
   409
    } else {
jens@0
   410
        tell(_viewDropTarget,@selector(draggingExited:),sender,0);
jens@0
   411
        _viewDropTarget = target;
jens@0
   412
        if( _viewDropTarget )
jens@0
   413
            _viewDropOp = [_viewDropTarget draggingEntered: sender];
jens@0
   414
        else
jens@0
   415
            _viewDropOp = NSDragOperationNone;
jens@0
   416
    }
jens@0
   417
    return _viewDropOp;
jens@0
   418
}
jens@0
   419
jens@0
   420
- (BOOL)wantsPeriodicDraggingUpdates
jens@0
   421
{
jens@0
   422
    return (_viewDropTarget!=nil);
jens@0
   423
}
jens@0
   424
jens@0
   425
- (void)draggingExited:(id <NSDraggingInfo>)sender
jens@0
   426
{
jens@0
   427
    tell(_viewDropTarget,@selector(draggingExited:),sender,0);
jens@0
   428
    _viewDropTarget = nil;
jens@0
   429
}
jens@0
   430
jens@0
   431
- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
jens@0
   432
{
jens@0
   433
    return tell(_viewDropTarget,@selector(prepareForDragOperation:),sender,YES);
jens@0
   434
}
jens@0
   435
jens@0
   436
- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
jens@0
   437
{
jens@0
   438
    return [_viewDropTarget performDragOperation: sender];
jens@0
   439
}
jens@0
   440
jens@0
   441
- (void)concludeDragOperation:(id <NSDraggingInfo>)sender
jens@0
   442
{
jens@0
   443
    tell(_viewDropTarget,@selector(concludeDragOperation:),sender,0);
jens@0
   444
}
jens@0
   445
jens@0
   446
- (void)draggingEnded:(id <NSDraggingInfo>)sender
jens@0
   447
{
jens@0
   448
    tell(_viewDropTarget,@selector(draggingEnded:),sender,0);
jens@0
   449
}
jens@0
   450
jens@0
   451
@end