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

#import "FissionGame.h"
#import "AnyDirectionUntilBlockedMoveRule.h"

@implementation FissionGame

-(void)reset {
  [super reset];
  [self createGridFromConfiguration];
  if ([[self configurationInfo] objectForKey:@"randomCells"]) {
    int ncells = [[[self configurationInfo] objectForKey:@"randomCells"] intValue];
    int p;
    for(p=1; p<=[self numberOfPlayers]; p++) {
      [self fillRandomEmptyCellsWithValue:p count:ncells];
    }
  }
  [self setCurrentPlayerNumber:1];
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  id pos0 = [positions objectAtIndex:0];
  id pos1 = [positions objectAtIndex:1];
  // get direction of move so we can tell if it ended by hitting an edge or another piece
  int dr = ([pos1 row]>[pos0 row]) ? 1 : (([pos1 row]<[pos0 row]) ? -1 : 0);
  int dc = ([pos1 column]>[pos0 column]) ? 1 : (([pos1 column]<[pos0 column]) ? -1 : 0);

  [self resetFutureGrid];
  
  [[self futureGrid] setValue:0 atPosition:pos0];
  // detonate if we hit a piece and not an edge
  if ([self isValidRow:[pos1 row]+dr column:[pos1 column]+dc]) {
    [[self futureGrid] setValue:0 atPositions:[[self futureGrid] neighborsOfPosition:pos1 distance:1]];
  }
  else {
    [[self futureGrid] setValue:[self currentPlayerNumber] atPosition:pos1];
  }
  return YES;
}

-(BOOL)isSuicideVariation {
  return ([[self configurationInfo] objectForKey:@"suicide"]!=nil);
}

-(int)winningPlayer {
  int n1 = [[self grid] numberOfCellsWithValue:1];
  int n2 = [[self grid] numberOfCellsWithValue:2];
  if (n1>0 && n2==0) return ([self isSuicideVariation]) ? 2 : 1;
  if (n2>0 && n1==0) return ([self isSuicideVariation]) ? 1 : 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 || (n1==1 && n2==1) || ![AnyDirectionUntilBlockedMoveRule gameHasAnyMoves:self]);
}

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

-(BOOL)showScores {
  return YES;
}

@end
