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

static int _fastGridValue(gridvalue_t *values, int r, int c, int maxr, int maxc) {
  return (int)values[r*maxc+c];
}

@implementation LifeGame

// private methods

-(int)valueAtPosition:(id)pos afterMoveAtPosition:(id)movepos byPlayer:(int)pnum {
  int dr,dc;
  // HACK: for speed, this uses internal fields in DCHypergrid
  gridvalue_t *values = [[self grid] cHypergrid]->grid_data;
  
  int moverow = [movepos row], movecol=[movepos column];
  int targetrow=[pos row], targetcol=[pos column];
  int maxr = [self numberOfRows], maxc = [self numberOfColumns];
  
  int origval = (moverow==targetrow && movecol==targetcol) ?
                    pnum : _fastGridValue(values, targetrow, targetcol, maxr, maxc);
  // count neighbors, wrapping around edges
  int n1=0, n2=0;
  for(dr=-1; dr<=1; dr++) {
    int r = (targetrow+dr)%maxr;
    if (r<0) r+=maxr;
    for(dc=-1; dc<=1; dc++) {
      if (dr!=0 || dc!=0) {
        int c = (targetcol+dc)%maxc;
        int nval;
        if (c<0) c+=maxc;
        nval = (r==moverow && c==movecol) ? pnum : _fastGridValue(values, r, c, maxr, maxc);
        if (nval==1) ++n1;
        else if (nval==2) ++n2;
      }
    }
  }
  //NSLog(@"neighbors of %@: %d %d", pos, n1, n2);
  if (origval==0) {
    // empty cell with 3 neighbors becomes filled
    if (n1+n2==3) {
      return (n2>n1) ? 2 : 1;
    }
    else return 0;
  }
  else {
    // filled cell needs 2 or 3 neighbors to survive
    if ((n1+n2==2) || (n1+n2==3)) return origval;
    else return 0;
  }
}


// end private methods

-(void)reset {
  [super reset];

  [self createGridFromConfiguration];
  {
    int p1cells = [[[self configurationInfo] objectForKey:@"player1RandomCells"] intValue];
    int p2cells = [[[self configurationInfo] objectForKey:@"player2RandomCells"] intValue];
    [self fillRandomEmptyCellsWithValue:1 count:p1cells];
    [self fillRandomEmptyCellsWithValue:2 count:p2cells];
  }
}

-(BOOL)prepareMoveSequence:(NSArray *)positions {
  [self resetFutureGrid];

  if ([positions count]==0) return YES;
  if ([positions count]!=1) return NO;
  else {
    id movepos = [positions objectAtIndex:0];
    int pnum = [self currentPlayerNumber];
    NSEnumerator *pe = [[self grid] positionEnumerator];
    id pos;
    while ((pos=[pe nextObject])) {
      int nextValue = [self valueAtPosition:pos afterMoveAtPosition:movepos byPlayer:pnum];
      [[self futureGrid] setValue:nextValue atPosition:pos];
    }
    return YES;
  }
}

-(BOOL)isGameOver {
  int s1=[[self grid] numberOfCellsWithValue:1];
  int s2=[[self grid] numberOfCellsWithValue:2];
  return ((s1==0 && s2==0) || s1>=s2*4 || s2>=s1*4);
}

-(NSArray *)allValidMoveSequences {
  return [[[self grid] allPositionsWithValue:0] valuesByObjectsPerformingSelector:@selector(arrayWithSelf_)];
}

-(BOOL)showScores {
  return YES;
}

@end
