/* Gridlock
Copyright (c) 2002-2003 by Brian Nenninger. All rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#import "ReversiGame.h"

static NSArray *EMPTY_ARRAY;

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 ReversiGame

+(void)load {
  EMPTY_ARRAY = [[NSArray alloc] init];
}

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


// "private" methods

// precondition: pos is currently empty
-(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;
}

-(NSArray *)positionsCapturedByMoveAtPosition:(DCHypergridPosition *)pos forPlayer:(int)pnum {
  NSMutableArray *array = nil;
  int i;
  for(i=0; i<8; i++) {
    int count = [self numberOfPositionsCapturedByMoveAtPosition:pos
                                                    movingByRow:ROW_DIRECTIONS[i]
                                                         column:COL_DIRECTIONS[i]
                                                      forPlayer:pnum];
    if (count>0) {
      int j;
      if (!array) array = [NSMutableArray array];
      for(j=1; j<=count; j++) {
        [array addObject:[DCHypergridPosition positionWithRow:([pos row]+j*ROW_DIRECTIONS[i])
                                                       column:([pos column]+j*COL_DIRECTIONS[i])]];
      }
    }
  }
  return (array ? array : EMPTY_ARRAY);
}

-(BOOL)areAnyPositionsCapturedByMoveAtPosition:(DCHypergridPosition *)pos forPlayer:(int)pnum {
  int i;
  for(i=0; i<8; i++) {
    int nump = [self numberOfPositionsCapturedByMoveAtPosition:pos
                                                   movingByRow:ROW_DIRECTIONS[i]
                                                        column:COL_DIRECTIONS[i]
                                                     forPlayer:pnum];
    if (nump>0) return YES;
  }
  return NO;
}


// end private methods

-(NSArray *)allValidMoveSequences {
  NSMutableArray *moves = [NSMutableArray array];
  int pnum = [self currentPlayerNumber];
  NSEnumerator *pe = [[self grid] enumeratorForPositionsWithValue:0];
  id pos;
  while (pos=[pe nextObject]) {
    if ([[self positionsCapturedByMoveAtPosition:pos forPlayer:pnum] count]>0) {
      [moves addObject:[pos arrayWithSelf_]];
    }
  }
  if ([moves count]==0) [moves addObject:[NSArray array]];
  return moves;
}


-(BOOL)prepareMoveSequence:(NSArray *)positions {
  int pnum = [self currentPlayerNumber];
  [self resetFutureGrid];

  if ([positions count]==0) return YES;
  if ([positions count]!=1) return NO;
  else {
    id pos = [positions lastObject];
    NSArray *capturedPositions = [self positionsCapturedByMoveAtPosition:pos forPlayer:pnum];
    if ([capturedPositions count]>0) {
      [[self futureGrid] setValue:pnum atPosition:pos];
      [[self futureGrid] setValue:pnum atPositions:capturedPositions];
      return YES;
    }
    else return NO;
  }
}

-(BOOL)isGameOver {
  // see if either player can move
  NSEnumerator *pe = [grid positionEnumerator];
  id pos;
  int maxp = [self numberOfPlayers];
  while (pos=[pe nextObject]) {
    if ([grid valueAtPosition:pos]==0) {
      int p;
      for(p=1; p<=maxp; p++) {
        if ([self areAnyPositionsCapturedByMoveAtPosition:pos forPlayer:p]) return NO;
      }
    }
  }
  return YES;
}

-(BOOL)showScores {
  return YES;
}

@end
