//
//  ReactorGame.m
//  Gridlock
//
//  Created by Brian on Sun Feb 15 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//

#import "ReactorGame.h"
#import "AnyDirectionUntilBlockedMoveRule.h"

@implementation ReactorGame

-(void)reset {
  [super reset];
  [self createGridFromConfiguration];

  [self fillRandomEmptyCellsWithValue:1  count:[[[self configurationInfo] objectForKey:@"p1pieces"] intValue]];
  [self fillRandomEmptyCellsWithValue:2  count:[[[self configurationInfo] objectForKey:@"p2pieces"] intValue]];
  [self fillRandomEmptyCellsWithValue:-1 count:[[[self configurationInfo] objectForKey:@"neutrons"] intValue]];
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  id pos0 = [positions objectAtIndex:0];
  id pos1 = [positions objectAtIndex:1];
  id previousUnmoveable = [[self grid] positionWithValue:-2]; // inefficient to call this every time
  NSArray *neighbors = [[self grid] neighborsOfPosition:pos1 distance:1];
  NSEnumerator *ne = [neighbors objectEnumerator];
  id npos;
  
  [self resetFutureGrid];
  
  [[self futureGrid] setValue:0 atPosition:pos0];
  // remove all non-neutrons around destination
  while (npos=[ne nextObject]) {
    if ([self valueAtPosition:npos]>0) {
      [[self futureGrid] setValue:0 atPosition:npos];
    }
  }
  // restore moving neutron, can't be moved on next turn
  [[self futureGrid] setValue:-2 atPosition:pos1];
  // neutron that couldn't be moved this turn can on next turn (inefficient to call -positionWithValue: every time)
  if (previousUnmoveable) [[self futureGrid] setValue:-1 atPosition:previousUnmoveable];
  return YES;
}

-(int)winningPlayer {
  int n1 = [[self grid] numberOfCellsWithValue:1];
  int n2 = [[self grid] numberOfCellsWithValue:2];
  if (n1>0 && n2==0) return 1;
  if (n2>0 && n1==0) return 2;
  // either both have no pieces, are tied at 1, or current player has no move
  return 0;
}

-(BOOL)isGameOver {
  // game over if either player has no pieces, or both have exactly 1, or current player can't move
  int n1 = [[self grid] numberOfCellsWithValue:1];
  int n2 = [[self grid] numberOfCellsWithValue:2];
  return (n1==0 || n2==0 || ![AnyDirectionUntilBlockedMoveRule gameHasAnyMoves:self fromPositionsWithValue:-1] || [self moveCount]>100);
}

-(NSArray *)allValidMoveSequences {
  return [AnyDirectionUntilBlockedMoveRule allValidMoveSequences:self fromPositionsWithValue:-1];
}

-(BOOL)showScores {
  return YES;
}

@end
