Codebase list gridlock.app / run/7a88808b-69aa-4130-a8f5-ec42250fed0a/main AtomicAI.m
run/7a88808b-69aa-4130-a8f5-ec42250fed0a/main

Tree @run/7a88808b-69aa-4130-a8f5-ec42250fed0a/main (Download .tar.gz)

AtomicAI.m @run/7a88808b-69aa-4130-a8f5-ec42250fed0a/mainraw · history · blame

//
//  AtomicAI.m
//  Gridlock
//
//  Created by Brian on Sat Feb 14 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//

#import "AtomicAI.h"
#import "AtomicGame.h"

static NSArray* convertArrayValuesToNSNumbers(NSArray *array) {
  NSMutableArray *result = [NSMutableArray array];
  id obj;
  NSEnumerator *e = [array objectEnumerator];
  while (obj=[e nextObject]) {
    if ([obj isKindOfClass:[NSArray class]]) {
      [result addObject:convertArrayValuesToNSNumbers(obj)];
    }
    else if ([obj respondsToSelector:@selector(intValue)]) {
      [result addObject:[NSNumber numberWithInt:[obj intValue]]];
    }
    else {
      [result addObject:obj];
    }
  }
  return result;
}

@implementation AtomicAI

-(void)dealloc {
  [utilityArray release];
  [super dealloc];
}

-(int)utilityForPlayer:(int)pnum inGame:(AtomicGame *)game {
  NSEnumerator *pe = [[game grid] positionEnumerator];
  id pos;
  int utility = 0;
  while (pos=[pe nextObject]) {
    if ([game ownerOfPosition:pos]==pnum) {
      int numPieces = abs([game valueAtPosition:pos]);
      int maxStablePieces = [game maxStablePiecesForPosition:pos];
      utility += (utilityArray==nil) ? 1 : [[[utilityArray objectAtIndex:maxStablePieces-1] objectAtIndex:numPieces-1] intValue];
    }
  }
  return utility;
}


-(int)relativeUtilityForGame:(Game *)game player:(int)pnum {
  return [self utilityForPlayer:pnum inGame:game] - [self utilityForPlayer:[game playerNumberMovingAfterPlayer:pnum] inGame:game];
}

/* utilityArray values come in as strings. The setter converts them to NSNumbers to avoid
repeated string conversions in utilityForPlayer:inGame:
*/

-(void)setUtilityArray:(NSArray *)array {
  [utilityArray autorelease];
  utilityArray = [convertArrayValuesToNSNumbers(array) retain];
}

@end