//
//  TongaGame.m
//  Gridlock
//
//  Created by Brian on 11/6/04.
//  Copyright 2004 __MyCompanyName__. All rights reserved.
//

#import "TongaGame.h"


@implementation TongaGame

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

-(BOOL)appendValidMovesFromPosition:(id)startpos intoArray:(NSMutableArray *)moves {
  int r = [startpos row];
  int c = [startpos column];
  int dr,dc;
  BOOL found = NO;
  for(dr=-1; dr<=+1; dr++) {
    for(dc=-1; dc<=+1; dc++) {
      if (dr!=0 || dc!=0) {
        if ([self isValidRow:r+dr column:c+dc] && [self valueAtRow:r+dr column:c+dc]==0) {
          if (!moves) return YES;
          found = YES;
          [moves addObject:[NSArray arrayWithObjects:startpos, [DCHypergridPosition positionWithRow:r+dr column:c+dc], nil]];
        }
      }
    }
  }
  return found;
}

-(NSArray *)allValidMoveSequences {
  NSMutableArray *moves = [NSMutableArray array];
  NSEnumerator *pe = [[self grid] enumeratorForPositionsWithValue:0];
  id pos;
  while(pos=[pe nextObject]) {
    [self appendValidMovesFromPosition:pos intoArray:moves];
  }
  return moves;
}

-(BOOL)isGameOver {
  NSEnumerator *pe = [[self grid] enumeratorForPositionsWithValue:0];
  id pos;
  while(pos=[pe nextObject]) {
    if ([self appendValidMovesFromPosition:pos intoArray:nil]) return NO;
  }
  return YES;
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  [self resetFutureGrid];
  [[self futureGrid] setValue:[self currentPlayerNumber] atPosition:[positions objectAtIndex:0]];
  [[self futureGrid] setValue:[self nextPlayerNumber] atPosition:[positions objectAtIndex:1]];
  return YES;
}

-(BOOL)showScores {
  return YES;
}

-(int)scoreForPlayer:(int)pnum {
  NSArray *groups = [[self grid] connectedGroupsWithValue:pnum onlyOrthoganal:YES];
  int score = 0;
  int len = [groups count];
  int i;
  for(i=0; i<3 && i<len; i++) {
    int size = [[groups objectAtIndex:len-1-i] count];
    score += size*size;
  }
  return score;
}

@end
