/* 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 "AtaxxAI.h"
#import "AtaxxGame.h"

/* AtaxxAI uses a custom enumerator to only generate moves as they are required. This gives a substantial
performance improvement when used with alpha-beta searching, because when a node gets pruned we save time
by not computing all of its moves.

AtaxxAIGoodMoveEnumerator cycles through all the pieces owned by the current player twice; first looking for
non-jump moves and then looking for jumps. It keeps track of where it left off searching in its index and
boolean ivars.
*/

@interface AtaxxAIGoodMoveEnumerator : NSEnumerator {
  Game *game;
  NSMutableArray *startPositions;
  NSMutableSet *nonJumpEndPositions;
  int movesReturned;
  // these ivars store where we are in the process of searching for moves
  int startPositionIndex; // which position we're starting from
  int neighborIndex;      // index of the neighbor (possible ending position) of the start position
  BOOL checkingNonjumps;  // true if we're looking for normal moves
  BOOL checkingJumps;     // true if we're looking for jumps
}

@end

@implementation AtaxxAIGoodMoveEnumerator

-(id)initWithGame:(Game *)g {
  if (self=[super init]) {
    game = [g retain];
    // get start positions, and randomize so that if the utilities are equal the same move won't always be made
    {
      NSEnumerator *pe = [[game grid] enumeratorForPositionsWithValue:[game currentPlayerNumber]];
      id pos;
      startPositions = [[NSMutableArray alloc] init];
      while (pos=[pe nextObject]) {
        [startPositions addObject:pos];
      }
      [startPositions randomizeObjects_];
      nonJumpEndPositions = [[NSMutableSet alloc] init];
      checkingNonjumps = YES;
    }
  }
  return self;
}

/** Advances the ivars to point at the next move to check.
*/
-(void)incrementIndexes {
  neighborIndex++;
  if (checkingNonjumps){
    if (neighborIndex==9) {
      // done with the current starting position (up to 9 cells distance 1 away)
      neighborIndex = 0;
      startPositionIndex++;
      if (startPositionIndex>=[startPositions count]) {
        // done with all non-jumps
        checkingJumps = YES;
        checkingNonjumps = NO;
        startPositionIndex = 0;
      }
    }
  }
  else if (neighborIndex==25) {
    // done with the current starting position (up to 25 cells distance 2 away)
    neighborIndex = 0;
    startPositionIndex++;
    if (startPositionIndex>=[startPositions count]) {
      // done with all jumps
      checkingJumps = NO;
    }
  }
}

/** Get the next valid move, ignoring duplicate non-jump moves to the same destination, and jumps to a
destination where a non-jump is available.
*/
-(id)nextObject {
  // test at indices, then increment
  while (checkingNonjumps) {
    id startpos = [startPositions objectAtIndex:startPositionIndex];
    // neighborIndex goes from 0 to 8, because there are (up to) 9 cells within 1 of the start position
    int r = [startpos row] - 1 + neighborIndex/3;
    int c = [startpos column] - 1 + neighborIndex%3;
    if ([game isValidRow:r column:c]) {
      id endpos = [DCHypergridPosition positionWithRow:r column:c];
      if ([game valueAtRow:r column:c]==0 && ![nonJumpEndPositions containsObject:endpos]) {
        // good move
        [nonJumpEndPositions addObject:endpos];
        [self incrementIndexes];
        ++movesReturned;
        return [endpos arrayWithSelf_];
        //return [NSArray arrayWithObjects:startpos,endpos,nil];
      }
    }
    [self incrementIndexes];
  }
  while (checkingJumps) {
    id startpos = [startPositions objectAtIndex:startPositionIndex];
    // neighborIndex goes from 0 to 24, because there are (up to) 25 cells within 2 of the start position
    int dr = -2 + neighborIndex/5;
    int dc = -2 + neighborIndex%5;
    // we don't want to check neighbors that aren't actually jumps
    if (dr==2 || dr==-2 || dc==2 || dc==-2) {
      int r = [startpos row] + dr;
      int c = [startpos column] + dc;
      if ([game isValidRow:r column:c]) {
        id endpos = [DCHypergridPosition positionWithRow:r column:c];
        if ([game valueAtRow:r column:c]==0 && ![nonJumpEndPositions containsObject:endpos]) {
          // good move
          [self incrementIndexes];
          ++movesReturned;
          return [NSArray arrayWithObjects:startpos,endpos,nil];
        }
      }
    }
    [self incrementIndexes];
  }
  // we're done checking all jumps and nonjumps. If we didn't find anything, return a pass
  if (movesReturned==0) {
    ++movesReturned;
    return [NSArray array];
  }
  return nil;
}

-(void)dealloc {
  [game release];
  [startPositions release];
  [nonJumpEndPositions release];
  [super dealloc];
}

@end

@implementation AtaxxAI

-(NSEnumerator *)enumeratorForMovesToConsiderForGame:(Game *)game {
  return [[[AtaxxAIGoodMoveEnumerator alloc] initWithGame:game] autorelease];
}

@end
