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

static int ROW_DELTAS[] = {+1,+2,+2,+1};
static int COL_DELTAS[] = {-2,-1,+1,+2};

@implementation TourneyGame

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

-(int)rowIncrementForCurrentPlayer {
  return (playerNumber==1) ? 1 : -1;
}
-(int)rowIncrementForPlayer:(int)pnum {
  return (pnum==1) ? 1 : -1;
}

-(int)ownerOfPosition:(DCHypergridPosition *)pos {
  return abs([self valueAtPosition:pos]);
}
-(int)ownerOfRow:(int)r column:(int) c {
  return abs([self valueAtRow:r column:c]);
}

-(BOOL)isKingAtPosition:(DCHypergridPosition *)pos {
  return ([self valueAtPosition:pos]<0);
}

-(int)numberOfRegularPiecesForPlayer:(int)pnum {
  return [[self grid] numberOfCellsWithValue:pnum];
}
-(int)numberOfKingsForPlayer:(int)pnum {
  return [[self grid] numberOfCellsWithValue:-pnum];
}

-(int)firstRowForPlayer:(int)pnum {
  return (pnum==1) ? 0 : [self numberOfRows]-1;
}
-(int)lastRowForPlayer:(int)pnum {
  return (pnum==1) ? [self numberOfRows]-1 : 0;
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  int pnum = [self currentPlayerNumber];
  id lastpos = [positions lastObject];
  // destination cell gets a king if a king was moved, or if a piece is promoted at the last row
  BOOL newPieceIsKing = [self isKingAtPosition:[positions objectAtIndex:0]] || [lastpos row]==[self lastRowForPlayer:pnum];
  
  [self resetFutureGrid];
  // last position is new, all others are removed
  [[self futureGrid] setValue:0 atPositions:positions];
  [[self futureGrid] setValue:(newPieceIsKing ? -pnum : pnum) atPosition:lastpos];
  return YES;
}

-(BOOL)insertCapturesForPlayer:(int)pnum 
                  fromPosition:(id)pos 
                        isKing:(BOOL)king 
     ignoringCapturedPositions:(NSArray *)previousJumpedPositions 
             startingPositions:(NSArray *)partialMove 
                 intoMoveArray:(NSMutableArray *)moves {
  return NO; 
}

// returns true if the destination cell is valid, and the intermediate cell in a move is empty
-(BOOL)canMoveRows:(int)dr columns:(int)dc fromRow:(int)r column:(int)c {
  if ([self isValidRow:r+dr column:c+dc]) {
    // the first forward or sideways move has to be clear as well
    int tr = r;
    int tc = c;
    if (abs(dr)>abs(dc)) {
      tr += (dr>0) ? 1 : -1;
    }
    else {
      tc += (dc>0) ? 1 : -1;
    }
    if ([self valueAtRow:tr column:tc]==0) return YES;
  }
  return NO;
}

-(BOOL)insertCapturesForPlayer:(int)pnum
                  fromPosition:(id)pos
                        isKing:(BOOL)king
                   partialMove:(NSArray *)partialMove
                 intoMoveArray:(NSMutableArray *)moves {
  
  int oppnum = [self playerNumberMovingAfterPlayer:pnum];
  int dir = [self rowIncrementForCurrentPlayer];
  int i;
  BOOL checkingBackwards = NO;
  int r = [pos row];
  int c = [pos column];
  BOOL done = NO;
  BOOL foundJump = NO;
  int initialMoveCount = [moves count];
  // a king will run through the loop twice, setting checkingBackwards for the second iteration
  do {
    for(i=0; i<4; i++) {
      int dr = (checkingBackwards) ? -dir*ROW_DELTAS[i] : dir*ROW_DELTAS[i];
      int dc = COL_DELTAS[i];
      if ([self canMoveRows:dr columns:dc fromRow:r column:c] && [self ownerOfRow:r+dr column:c+dc]==oppnum) {
        id jpos = [DCHypergridPosition positionWithRow:r+dr column:c+dc];
        if (![partialMove containsObject:jpos]) {
          // found a jump target, continue recursively looking for more jumps
          if (!moves) return YES; // if moves is nil we just wanted to see if any jump exists
          [self insertCapturesForPlayer:pnum
                           fromPosition:jpos
                                 isKing:king
                            partialMove:[partialMove arrayByAddingObject:jpos]
                          intoMoveArray:moves];
          foundJump = YES;
        }
      }
    }
    if (!checkingBackwards && king) checkingBackwards = YES;
    else done = YES;
  }
  while (!done);
  
  if (!foundJump && [partialMove count]>=2) {
    [moves addObject:partialMove];
  }
  return ([moves count]>initialMoveCount);
}

-(BOOL)insertNonCapturesForPlayer:(int)pnum fromPosition:(id)pos isKing:(BOOL)king intoMoveArray:(NSMutableArray *)moves {
  int dir = [self rowIncrementForCurrentPlayer];
  int i;
  BOOL checkingBackwards = NO;
  int r = [pos row];
  int c = [pos column];
  BOOL done = NO;
  BOOL foundMove = NO;
  // a king will run through the loop twice, setting checkingBackwards for the second iteration
  do {
    for(i=0; i<4; i++) {
      int dr = (checkingBackwards) ? -dir*ROW_DELTAS[i] : dir*ROW_DELTAS[i];
      int dc = COL_DELTAS[i];
      if ([self canMoveRows:dr columns:dc fromRow:r column:c] && [self valueAtRow:r+dr column:c+dc]==0) {
        if (!moves) return YES;
        [moves addObject:[NSArray arrayWithObjects:pos, [DCHypergridPosition positionWithRow:r+dr column:c+dc], nil]];
        foundMove = YES;
      }
    }
    if (!checkingBackwards && king) checkingBackwards = YES;
    else done = YES;
  }
  while (!done);
  return foundMove;
}

-(NSArray *)allValidMoveSequences {
  NSMutableArray *jumps = [NSMutableArray array];
  NSMutableArray *nonjumps = [NSMutableArray array];
  int pnum = [self currentPlayerNumber];
  NSEnumerator *pe = [[self grid] positionEnumerator];
  id pos;
  while ((pos=[pe nextObject])) {
    if (pnum==[self ownerOfPosition:pos]) {
      BOOL king = [self isKingAtPosition:pos];
      // process jumps
      [self insertCapturesForPlayer:pnum
                       fromPosition:pos
                             isKing:king
                        partialMove:[pos arrayWithSelf_]
                      intoMoveArray:jumps];
      // process nonjumps if no jumps found
      if ([jumps count]==0) {
        [self insertNonCapturesForPlayer:pnum fromPosition:pos isKing:king intoMoveArray:nonjumps];
      }      
    }
  }
  return ([jumps count]>0) ? jumps : nonjumps;  
}

-(int)playerWithKingAtHomeRow {
  int c;
  int numc = [self numberOfColumns];
  int maxr = [self numberOfRows]-1;
  for(c=0; c<numc; c++) {
    if ([self valueAtRow:0 column:c]==-1) return 1;
    if ([self valueAtRow:maxr column:c]==-2) return 2;
  }
  return 0;
}

-(BOOL)isGameOver {
  if ([self playerWithKingAtHomeRow]>0) return YES;
  else {
    int pnum = [self currentPlayerNumber];
    NSEnumerator *pe = [[self grid] positionEnumerator];
    id pos;
    while ((pos=[pe nextObject])) {
      if (pnum==[self ownerOfPosition:pos]) {
        BOOL king = [self isKingAtPosition:pos];
        // process jumps
        if ([self insertCapturesForPlayer:pnum
                             fromPosition:pos
                                   isKing:king
                              partialMove:[pos arrayWithSelf_]
                            intoMoveArray:nil])
          return NO;

        if ([self insertNonCapturesForPlayer:pnum fromPosition:pos isKing:king intoMoveArray:nil]) {
          return NO;
        }      
      }
    }
    return YES;
  }
}

-(int)winningPlayer {
  int pnum = [self playerWithKingAtHomeRow];
  if (pnum!=0) return pnum;
  // if no moves available, next player wins
  return [self nextPlayerNumber];  
}

@end
