//
//  AnyDirectionUntilBlockedMoveRule.m
//  Gridlock
//
//  Created by Brian on Sat Nov 22 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import "AnyDirectionUntilBlockedMoveRule.h"


@implementation AnyDirectionUntilBlockedMoveRule

+(BOOL)appendValidMovesForGame:(Game *)game fromPosition:(id)pos intoArray:(NSMutableArray *)moves {
  static int ROW_DIRECTIONS[] = {+1,+1,+1, 0, 0,-1,-1,-1};
  static int COL_DIRECTIONS[] = {+1, 0,-1,+1,-1,+1, 0,-1};
  BOOL found = NO;
  int r = [pos row];
  int c = [pos column];
  int i;
  for(i=0; i<8; i++) {
    int dr = ROW_DIRECTIONS[i];
    int dc = COL_DIRECTIONS[i];
    int dist = 1;
    while ([game isValidRow:r+dist*dr column:c+dist*dc] && [game valueAtRow:r+dist*dr column:c+dist*dc]==0) {
      dist++;
    }
    dist--; // we hit the edge or another piece, so back up 1
    if (dist>0) {
      if (!moves) return YES; // if no array, we just want to know if there's a valid move
      found = YES;
      [moves addObject:[NSArray arrayWithObjects:pos, [DCHypergridPosition positionWithRow:r+dist*dr column:c+dist*dc], nil]];
    }
  }
  return found;
}

+(NSArray *)allValidMoveSequences:(Game *)game fromPositionsWithValue:(int)sval {
  NSMutableArray *moves = [NSMutableArray array];
  NSEnumerator *pe = [[game grid] enumeratorForPositionsWithValue:sval];
  id pos;
  while (pos=[pe nextObject]) {
    [self appendValidMovesForGame:game fromPosition:pos intoArray:moves];
  }
  return moves;
}

+(NSArray *)allValidMoveSequences:(Game *)game {
  return [self allValidMoveSequences:game fromPositionsWithValue:[game currentPlayerNumber]];
}

+(BOOL)gameHasAnyMoves:(Game *)game fromPositionsWithValue:(int)sval {
  NSEnumerator *pe = [[game grid] enumeratorForPositionsWithValue:sval];
  id pos;
  while (pos=[pe nextObject]) {
    if ([self appendValidMovesForGame:game fromPosition:pos intoArray:nil]) return YES;
  }
  return NO;
}

+(BOOL)gameHasAnyMoves:(Game *)game {
  return [self gameHasAnyMoves:game fromPositionsWithValue:[game currentPlayerNumber]];
}

@end
