//
//  AmbivalanceGame.m
//  Gridlock
//
//  Created by Brian on 3/26/05.
//  Copyright 2005 __MyCompanyName__. All rights reserved.
//

#import "AmbivalenceGame.h"


@implementation AmbivalenceGame

-(void)reset {
  [super reset];
  [super createGridFromConfiguration];
}

-(NSArray *)allValidMoveSequences {
  return [[[self grid] allPositionsWithValue:0] valuesByObjectsPerformingSelector:@selector(arrayWithSelf_)];
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  if ([positions count]!=1) return NO;
  [self resetFutureGrid];
  
  id pos = [positions lastObject];
  int r = [pos row];
  int c = [pos column];
  int pnum = [self currentPlayerNumber];
  int oppnum = [self nextPlayerNumber];
  
  [[self futureGrid] setValue:pnum atPosition:pos];

  int dr,dc;
  for(dr=-1; dr<=+1; dr++) {
    for(dc=-1; dc<=+1; dc++) {
      if (dr!=0 || dc!=0) {
        if ([self isValidRow:r+dr column:c+dc] && [self valueAtRow:r+dr column:c+dc]==oppnum) {
          // check for "intrusion" capture, coming in between two opponents kills them both
          // then check for "custodian" capture, trapping an enemy between two allies kills it
          if ([self isValidRow:r-dr column:c-dc] && [self valueAtRow:r-dr column:c-dc]==oppnum) {
            // actually these will get set twice when we check the opposite direction, but that's ok
            [[self futureGrid] setValue:-1 atPosition:[DCHypergridPosition positionWithRow:r+dr column:c+dc]];
            [[self futureGrid] setValue:-1 atPosition:[DCHypergridPosition positionWithRow:r-dr column:c-dc]];
          }
          else if ([self isValidRow:r+2*dr column:c+2*dc] && [self valueAtRow:r+2*dr column:c+2*dc]==pnum) {
            [[self futureGrid] setValue:-1 atPosition:[DCHypergridPosition positionWithRow:r+dr column:c+dc]];
          }
        }
      }
    }
  }
  return YES;
}

-(BOOL)isGameOver {
  return !([[self grid] hasCellWithValue:0]);
}

-(BOOL)showScores {
  return YES;
}

@end
