/* 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 "AbstractLineGame.h"


@implementation AbstractLineGame

-(int)winningLength {
  return -1;
}

-(id)init {
  if (self = [super init]) {
    _cachedThreatDicts = [[NSMutableDictionary alloc] init];
  }
  return self;
}

idAccessor(preparedMove, setPreparedMove)

-(void)dealloc {
  [_cachedThreatDicts release];
  [self setPreparedMove:nil];
  [super dealloc];
}

-(void)reset {
  [super reset];
  [self setGrid:[DCHypergrid gridWithRows:[[[self configurationInfo] objectForKey:@"rows"] intValue]
                                  columns:[[[self configurationInfo] objectForKey:@"cols"] intValue]]];
  [_cachedThreatDicts removeAllObjects];
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  [self setPreparedMove:[positions lastObject]];
  return YES;
}

-(NSArray *)positionsOfAllChangingCells {
  return [[self preparedMove] arrayWithSelf_];
}

-(int)futureValueAtPosition:(DCHypergridPosition *)pos {
  if ([pos isEqual:[self preparedMove]]) return [self currentPlayerNumber];
  else return [self valueAtPosition:pos];
}

-(void)didMakeMove:(NSArray *)positions {
  [super didMakeMove:positions];
  [self setPreparedMove:nil];
  [_cachedThreatDicts removeAllObjects];
}

-(BOOL)isGameOver {
  if ([self hasPlayerWon:1] || [self hasPlayerWon:2]) return YES;
  else {
    // game is over if all cells are filled
    return ![[self grid] hasCellWithValue:0];
  }
}

-(BOOL)hasPlayerWon:(int)pnum {
  NSArray *threats = [self threatsForPlayer:pnum];
  NSEnumerator *te = [threats objectEnumerator];
  NSDictionary *threat;
  while (threat=[te nextObject]) {
    int length = [[threat objectForKey:@"length"] intValue];
    if (length>=[self winningLength]) return YES;
  }
  return NO;
}

-(int)winningPlayer {
  int pcount = [self numberOfPlayers];
  int i;
  for(i=1; i<=pcount; i++) {
    if ([self hasPlayerWon:i]) return i;
  }
  return 0;
}

-(NSArray *)positionsOfWinningPieces {
  int wpnum = [self winningPlayer];
  if (wpnum>=1 && wpnum<=[self numberOfPlayers]) {
    NSArray *threats = [self threatsForPlayer:wpnum];
    NSEnumerator *te = [threats objectEnumerator];
    NSDictionary *threat;
    while (threat=[te nextObject]) {
      int length = [[threat objectForKey:@"length"] intValue];
      if (length>=[self winningLength]) {
        NSMutableArray *positions = [NSMutableArray array];
        int i=0;
        DCHypergridPosition *pos = [threat objectForKey:@"position"];
        DCHypergridPosition *dir = [threat objectForKey:@"direction"];
        while (i<[self winningLength]) {
          [positions addObject:pos];
          pos = [pos positionByAddingPosition:dir];
          i++;
        }
        return positions;
      }
    }
  }
  return nil;
}

/** Returns an array of NSDictionary objects, each of which describes a threat line. The keys and values
of each dictionary are as follows:
"position"  - DCHypergridPosition, starting position of the threat line
"direction" - DCHypergridPosition, direction of the threat line relative to position
"length" - number of cells in the threat line
"openBefore" - number of empty cells "behind" the threat line (relative to direction)
"openAfter" - number of empty cells in front of the threat line
*/
-(NSArray *)threatsForPlayer:(int)pnum {
  NSNumber *num = [NSNumber numberWithInt:pnum];
  NSArray *result = [_cachedThreatDicts objectForKey:num];
  if (!result) {
    [_cachedThreatDicts setObject:(result=[self _threatsForPlayer:pnum]) forKey:num];
  }
  return result;
}

-(NSArray *)_threatsForPlayer:(int)pnum {
  NSMutableArray *threats = [NSMutableArray array];
  NSEnumerator *ge = [grid positionEnumerator];
  DCHypergridPosition *pos;
  while (pos=[ge nextObject]) {
    // does the player own this cell?
    if ([self valueAtPosition:pos]==pnum) {
      // only look in the "forward" directions
      int deltas[8] = {0,1, 1,-1, 1,0, 1,1};
      int i;
      for(i=0; i<4; i++) {
        int dr = deltas[2*i];
        int dc = deltas[2*i+1];
        if ([pos row]+dr<[self numberOfRows] &&
            [pos column]+dc>=0 && [pos column]+dc<[self numberOfColumns]) {
          id diff = [DCHypergridPosition positionWithRow:dr column:dc];
          // make sure the player does not own the cell going backwards
          id temppos = [pos positionBySubtractingPosition:diff];
          int backval = -1;
          if (![grid isValidPosition:temppos] || (backval=[self valueAtPosition:temppos])!=pnum) {
            int backopen = 0;
            int fwdopen = 0;
            int length = 1;
            BOOL done = NO;
            // walk forward, incrementing length while we keep hitting cells we own, then fwdopen
            BOOL threatFinished = NO;
            temppos=[pos positionByAddingPosition:diff];
            while (!done) {
              if ([grid isValidPosition:temppos]) {
                int value = [grid valueAtPosition:temppos];
                if (!threatFinished) {
                  if (value==pnum) ++length;
                  else threatFinished = YES;
                }
                if (threatFinished) {
                  if (value==pnum || value==0) ++fwdopen;
                  else done = YES;
                }
              }
              else done = YES;
              if (!done) temppos = [temppos positionByAddingPosition:diff];
            }
            // walk backward, incrementing backopen
            done = 0;
            temppos = [pos positionBySubtractingPosition:diff];
            while (!done) {
              if ([grid isValidPosition:temppos]) {
                int value = [grid valueAtPosition:temppos];
                if (value==pnum || value==0) ++backopen;
                else done = YES;
              }
              else done = YES;
              if (!done) temppos = [temppos positionBySubtractingPosition:diff];
            }

            // create threat dictionary
            {
              int totallen = length+backopen+fwdopen;
              // can't be a winning threat unless totallen>=winningLength
              if (length>1 && totallen>=[self winningLength]) {
                NSMutableDictionary *threatDict = [NSMutableDictionary dictionary];
                [threatDict setObject:pos forKey:@"position"];
                [threatDict setObject:diff forKey:@"direction"];
                [threatDict setObject:[NSNumber numberWithInt:length] forKey:@"length"];
                [threatDict setObject:[NSNumber numberWithInt:fwdopen] forKey:@"openAfter"];
                [threatDict setObject:[NSNumber numberWithInt:backopen] forKey:@"openBefore"];
                [threats addObject:threatDict];                
              }
            }

          }
        }
      }
    }
  }
  return threats;
}

@end
