//
//  DominionGame.m
//  Gridlock
//
//  Created by Brian on 9/23/04.
//  Copyright 2004 __MyCompanyName__. All rights reserved.
//

#import "DominionGame.h"

static int ROW_DIRECTIONS[] = {+1,+1,+1, 0, 0,-1,-1,-1};
static int COL_DIRECTIONS[] = {+1, 0,-1,+1,-1,+1, 0,-1};

@implementation DominionGame

-(int)numberOfPositionsCapturedByMoveAtPosition:(id)pos movingByRow:(int)dr column:(int)dc forPlayer:(int)pnum {
  int myCellValue  = pnum;
  int oppCellValue = [self playerNumberMovingAfterPlayer:pnum];
  int r = [pos row]+dr;
  int c = [pos column]+dc;
  int count = 0;
  int good = 0; // set to true if we hit one of our cells
  int bad  = 0; // set to true if we hit a empty or barrier cell
                // using grid ivar is >10% faster
  while (!bad && !good && [grid isValidRow:r column:c]) {
    int value = [grid valueAtRow:r column:c];
    if (value==myCellValue) {
      good = 1;
    }
    else if (value==oppCellValue) {
      count++;
    }
    else {
      bad = 1;
    }
    r+=dr; c+=dc;
  }
  return (good && !bad) ? count : 0;
}


-(BOOL)prepareMoveSequence:(NSArray *)positions {
  int pnum = [self currentPlayerNumber];
  id pos = [positions lastObject];
  int i;
  // superclass does Ataxx captures
  [super prepareMoveSequence:positions];
  // then do Reversi captures
  for(i=0; i<8; i++) {
    int count = [self numberOfPositionsCapturedByMoveAtPosition:pos
                                                    movingByRow:ROW_DIRECTIONS[i]
                                                         column:COL_DIRECTIONS[i]
                                                      forPlayer:pnum];
    int j;
    for(j=1; j<=count; j++) {
      [[self futureGrid] setValue:pnum 
                            atRow:[pos row]+j*ROW_DIRECTIONS[i] 
                           column:[pos column]+j*COL_DIRECTIONS[i]];
    }
  }
  return YES;
}

@end
