#import "GameBoard.h" @implementation GameBoard //designated initializer for superclass - (id) initWithFrame:(NSRect) frame { if (self = [super initWithFrame: frame]) { //set up player colors playerColors[PLAYER_1] = [NSColor redColor]; playerColors[PLAYER_2] = [NSColor blackColor]; //set up board colors boardColors[0] = [NSColor lightGrayColor]; boardColors[1] = [NSColor darkGrayColor]; //initialize board int i; int j; for (i=0; i< DIMENSION; i++) for (j=0; j 0) { r.origin.x += 2; r.origin.y += 2; r.size.width -= 4; r.size.height -= 4; texture = [NSBezierPath bezierPathWithOvalInRect:r]; [[NSColor whiteColor] set]; [texture stroke]; } return path; } //based on a mouse click, determine the corresponding board coordinate -(NSPoint)boardCoordForClickPoint:(NSPoint)p { int x=-1; int y=-1; while (p.x > 0) { p.x -= squareDim; x++; } while (p.y > 0) { p.y -= squareDim; y++; } return NSMakePoint(x,y); } //used for moving - (void)movePieceFromCoord:(NSPoint)p1 toCoord:(NSPoint)p2 { NSLog(@"Attempting to move piece from (%f,%f) to (%f,%f)", p1.x,p1.y,p2.x,p2.y); //make sure move isn't in place if (p1.x == p2.x && p1.y == p2.y) return; //make sure there is a piece at p1 if (board[(int)p1.x][(int)p1.y] == EMPTY) return; //update the board int player = board[(int)p1.x][(int)p1.y]; board[(int)p1.x][(int)p1.y] = EMPTY; board[(int)p2.x][(int)p2.y] = player; [self setNeedsDisplay:YES]; } - (void)mouseMoved:(NSEvent *)event { // get the mouse position in view coordinates NSPoint mouse; mouse = [self convertPoint: [event locationInWindow] fromView: nil]; //no need to redraw anything in this case, the piece is still highlighted if (hoveredCoord.x != NIL_POINT.x && hoveredCoord.y != NIL_POINT.y && [piecesPaths[(int)hoveredCoord.x][(int)hoveredCoord.y] containsPoint: mouse]) return; //otherwise, check to see if a piece is being moused over int i; int j; for (i = 0; i < DIMENSION; i++) for (j = 0; j < DIMENSION; j++) if (board[i][j] != EMPTY) if ([piecesPaths[i][j] containsPoint: mouse]) { hoveredCoord = NSMakePoint(i,j); [self setNeedsDisplay:YES]; return; } //no pieces were being moused over. no need to redraw unless we neeed //to un-highlight a piece if (hoveredCoord.x != NIL_POINT.x && hoveredCoord.y != NIL_POINT.y) { [self setNeedsDisplay:YES]; hoveredCoord = NIL_POINT; } } - (void)mouseDown:(NSEvent*)event { //get the mouse position in view coordinates NSPoint mouse; mouse = [self convertPoint: [event locationInWindow] fromView: nil]; //if there was a previous click, save it NSPoint previousPoint = NIL_POINT; if (selectedCoord.x != NIL_POINT.x && selectedCoord.y != NIL_POINT.y) previousPoint = selectedCoord; //get the new board square that was clicked in. selectedCoord = [self boardCoordForClickPoint:mouse]; if (previousPoint.x != NIL_POINT.x && previousPoint.y != NIL_POINT.y) { [self movePieceFromCoord:previousPoint toCoord:selectedCoord]; selectedCoord = NIL_POINT; } } @end