#import #import "c4view.h" @interface Connect4View (Private) -(int) getCellSize; @end @implementation Connect4View -(id) initWithModel:(Connect4Model*)m withHuman:(int)i { [super init]; model = [m retain]; // TODO: release when window goes away humanPlayer = i; // make first move for computer if appropriate if (humanPlayer == 1) { [model makeMoveAtCol:[model monteCarloMoveWithVariations:100 andMaxTurns:20]]; } return self; } -(void) drawRect:(NSRect) rect { // figure out which dimension is the limiting one int cellSize = [self getCellSize]; // draw the grid for (int r = 0; r < [model getHeight]; r++) { for (int c = 0; c < [model getWidth]; c++) { int x = c * cellSize; int y = ([model getHeight] - r - 1) * cellSize; NSBezierPath* outline = [NSBezierPath bezierPathWithRect: NSMakeRect(x, y, cellSize - 1, cellSize - 1)]; [[NSColor blueColor] set]; [outline stroke]; int mark = [model getPieceAtRow:r andCol:c]; if (mark != -1) { NSBezierPath *piece = [NSBezierPath bezierPathWithOvalInRect: NSMakeRect(x + 1, y + 1, cellSize - 2, cellSize - 2)]; if (mark == 0) { [[NSColor blackColor] set]; } else { [[NSColor redColor] set]; } [piece fill]; } } } } -(void) dealloc { [model release]; [super dealloc]; } -(void) mouseDown:(NSEvent*) event { // get location of click and convert from window's coords to this view's NSPoint loc = [self convertPoint:[event locationInWindow] fromView:nil]; // compute grid location that was clicked on (only col really matters // for connect 4) int cellSize = [self getCellSize]; int row = [model getHeight] - 1 - loc.y / cellSize; int col = loc.x / cellSize; if (row >= 0 && row < [model getHeight] && col >= 0 && col < [model getWidth] && [model isLegalMove:col]) { // update model with human's move [model makeMoveAtCol:col]; // make computer's move if ([model getWinner] == 0 && ![model allFull]) { [model makeMoveAtCol:[model monteCarloMoveWithVariations:100 andMaxTurns:20]]; } // request redraw [self setNeedsDisplay:YES]; } } @end @implementation Connect4View (Private) -(int) getCellSize { int width = [self bounds].size.width; int height = [self bounds].size.height; int cellW = width / [model getWidth]; int cellH = height / [model getHeight]; return (cellW < cellH ? cellW : cellH); } @end