File: GenericAI.m

package info (click to toggle)
gridlock.app 1.10-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,556 kB
  • sloc: objc: 10,334; ansic: 669; makefile: 12
file content (347 lines) | stat: -rw-r--r-- 12,888 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/* 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 "GenericAI.h"

#define DEBUG 0

static int LOSE_UTILITY = -(1<<30); // for losing positions
static int WIN_UTILITY  = 1<<30;

@interface ArrayConsumerEnumerator : NSEnumerator {
  NSLock *lock;
  NSMutableArray *sourceArray;
}
+(ArrayConsumerEnumerator *)enumeratorWithSourceArray:(NSMutableArray *)array lock:(NSLock *)theLock;
@end

@implementation ArrayConsumerEnumerator
+(ArrayConsumerEnumerator *)enumeratorWithSourceArray:(NSMutableArray *)array lock:(NSLock *)theLock {
  ArrayConsumerEnumerator *enumerator = [[[self alloc] init] autorelease];
  enumerator->sourceArray = array;
  enumerator->lock = theLock;
  return enumerator;
}

-(id)nextObject {
  id obj = nil;
  [lock lock];
  if ([sourceArray count]>0) {
    obj = [sourceArray lastObject];
    [sourceArray removeLastObject];
  }
  [lock unlock];
  return obj;
}
@end

@implementation GenericAI

-(id)init {
  if (self=[super init]) {
    //NSLog(@"Creating AI:%@", NSStringFromClass([self class]));
    threadLock = [[NSLock alloc] init];
    bestThreadMoves = [[NSMutableArray alloc] init];
  }
  return self;
}

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

idAccessor(name, setName)
idAccessor(threadLock, setThreadLock)
idAccessor(bestThreadMoves, setBestThreadMoves)
intAccessor(depth, setDepth)
intAccessor(useThreads, setUseThreads)

// alpha-beta algorithm adapted from http://www.seanet.com/~brucemo/topics/alphabeta.htm
-(NSArray *)alphaBetaMoveForGame:(Game *)game
                           depth:(int)d
                           alpha:(int)alpha
                            beta:(int)beta
                  candidateMoves:(NSEnumerator *)moveenum
               positionsEvaluated:(int *)numEvaluated
                         utility:(int *)utility {
  int nextUtility;
  if (!moveenum) moveenum = [self enumeratorForMovesToConsiderForGame:game];
  
  NSArray *move, *nextMove, *bestMove=nil;
  Game *gameCopy = nil;
  int movenum=0;
  NSAssert2(alpha<beta, @"alpha(%d)>=beta(%d)", alpha, beta);

  while ((alpha<beta) && (move=[moveenum nextObject])) {
    id pool = [[NSAutoreleasePool alloc] init];

    if (!gameCopy) gameCopy = [game copy];
    else [game copyValuesToGame:gameCopy];

    // make and evaluate move
    movenum++;
    [gameCopy makeMoveSequence:move];
    // stop recursion if game is over or we're at depth 1
    if ([gameCopy isGameOver]) {
      int wpnum = [gameCopy winningPlayer];
      if (wpnum==[game currentPlayerNumber]) {
        nextUtility = WIN_UTILITY+d;
      }
      else if (wpnum!=0) {
        nextUtility = LOSE_UTILITY-d;
      }
      else {
        // tie; should handle this better
        nextUtility = -[self relativeUtilityForGame:gameCopy player:[gameCopy currentPlayerNumber]];
      }
    }
    else if (d<=1) {
      nextUtility = -[self relativeUtilityForGame:gameCopy player:[gameCopy currentPlayerNumber]];
    }
    else {
      // continue down the tree, swapping alpha and beta and negating utility since players are switched
      nextMove = [self alphaBetaMoveForGame:gameCopy
                                      depth:d-1
                                      alpha:-beta
                                        beta:-alpha
                              candidateMoves:nil
                          positionsEvaluated:numEvaluated
                                    utility:&nextUtility];
      nextUtility = -nextUtility; // negate since we just calculated from opponent's persepctive
      
    }
    
    if (nextUtility>=beta) {
      nextUtility = beta;
    }
    if (bestMove==nil || nextUtility>alpha) {
      bestMove = move;
    }
    if (nextUtility>alpha) alpha=nextUtility;

    if (numEvaluated) ++(*numEvaluated);
    [pool release];
  }
  [gameCopy release];
  *utility = alpha;
  if (alpha>=beta) {
    //NSLog(@"Exceeded beta at depth %d", d);
  }
  return bestMove;
}
  

-(int)searchDepthForGame:(Game *)game {
  return depth;
}

-(int)relativeUtilityForGame:(Game *)game player:(int)pnum {
  return ([game scoreForPlayer:pnum] -
          [game scoreForPlayer:[game nextPlayerNumber]]);
}

-(NSArray *)movesToConsiderForGame:(Game *)game {
  return [game allValidMoveSequences];
}

-(NSEnumerator *)enumeratorForMovesToConsiderForGame:(Game *)game {
  return [[[self movesToConsiderForGame:game] arrayWithObjectsInRandomOrder_] objectEnumerator];
}

+(double)normalizedRatioOf:(double)u1 to:(double)u2 maxRatio:(double)maxr {
  // Look at the ratio of my vs. opponent's utility. This will encourage exchanges when we're ahead and
  // avoid them when we're behind.
  double logratio = 0.0;
  if (u1<=0) return -1;
  if (u2<=0) return +1;
  else {
    logratio = log(u1/u2);
    if (logratio<-maxr) return -1;
    if (logratio>maxr) return +1;
  }
  return logratio/maxr;
}

////////////////////////////////// thread support //////////////////////////////

-(int)threadsToUse {
  if ([self useThreads]) {
    int nthreads = [[NSUserDefaults standardUserDefaults] integerForKey:@"CPUPlayerThreads"];
    if (nthreads<1) {
      // use MPProcessors() on Mac OS X, default to 1 on GNUstep until I find a portable way
#ifdef GNUSTEP
      nthreads = 1;
#else
      nthreads = MPProcessors();
#endif
    }
    return nthreads;
  }
  else return 1;
}

-(NSDictionary *)_bestMoveInfoForGame:(Game *)game
                       candidateMoves:(NSArray *)moves
                      spawningThreads:(int)nthreads {
  NSTimeInterval t1 = [NSDate timeIntervalSinceReferenceDate];
  NSTimeInterval t2;
  // each worker thread gets a lock whose condition it sets to 1 when it finishes
  NSMutableArray *locks = [NSMutableArray array];
  NSMutableArray *randomMoves = [[[moves arrayWithObjectsInRandomOrder_] mutableCopy] autorelease];
  int nmoves = [moves count];
  int i;
  if (nthreads>nmoves) nthreads = nmoves;
  for(i=0; i<nthreads; i++) {
    [locks addObject:[[[NSConditionLock alloc] initWithCondition:0] autorelease]];
  }
  // dispatch to threads, they'll pull moves from the randomMoves array using ArrayConsumerEnumerator
  [[self bestThreadMoves] removeAllObjects];
  for(i=0; i<nthreads; i++) {
    // each thread gets the game, the moves to evaluate, and the lock to update when it's finished
    NSArray *args = [NSArray arrayWithObjects:game, randomMoves, [locks objectAtIndex:i], nil];
    [NSThread detachNewThreadSelector:@selector(_bestMoveThreadEntry:)
                             toTarget:self
                           withObject:args];
  }
  // wait until all threads are done and have set their condition locks
  for(i=0; i<nthreads; i++) {
    [[locks objectAtIndex:i] lockWhenCondition:1];
    //NSLog(@"Got lock for thread %d", i);
  }
  // now find the best move in bestThreadMoves and assemble return info
  {
    NSDictionary *bestThreadMove = nil;
    NSMutableDictionary *bestMoveInfo;
    int totalEvaluated = 0;
    int bestUtility = 0;
    for(i=0; i<[[self bestThreadMoves] count]; i++) {
      NSDictionary *threadMove = [[self bestThreadMoves] objectAtIndex:i];
      totalEvaluated += [[threadMove objectForKey:@"positionsEvaluated"] intValue];
      if (bestThreadMove==nil || bestUtility<[[threadMove objectForKey:@"utility"] intValue]) {
        bestThreadMove = threadMove;
        bestUtility = [[threadMove objectForKey:@"utility"] intValue];
      }
    }
    bestMoveInfo = [[bestThreadMove mutableCopy] autorelease];
    [bestMoveInfo setObject:[NSNumber numberWithInt:totalEvaluated] forKey:@"positionsEvaluated"];
    t2 = [NSDate timeIntervalSinceReferenceDate];
    [bestMoveInfo setObject:[NSNumber numberWithDouble:t2-t1] forKey:@"time"];
    
    return bestMoveInfo;
  }
}


// these two methods execute in spawned threads
-(void)_recordBestMoveFoundInThread:(id)moveInfo {
  [[self threadLock] lock];
  [[self bestThreadMoves] addObject:moveInfo];
  [[self threadLock] unlock];
}

-(void)_bestMoveThreadEntry:(NSArray *)args {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  
  Game *game = [args objectAtIndex:0];
  NSMutableArray *moves = [args objectAtIndex:1];
  NSConditionLock *lock = [args objectAtIndex:2];
  NSMutableDictionary *moveInfo = [NSMutableDictionary dictionary];
  NSArray *bestMove = nil;
  int positionsEvaluated=0, utility;
  int d = [self searchDepthForGame:game];

  if (DEBUG) {
    NSLog(@"Starting computation in thread:%@", [NSThread currentThread]);
  }
  // the ArrayConsumerEnumerator will pull moves off the array, in cooperation with other threads
  bestMove = [self alphaBetaMoveForGame:game
                                  depth:d
                                  alpha:LOSE_UTILITY-d
                                   beta:WIN_UTILITY+d
                         candidateMoves:[ArrayConsumerEnumerator enumeratorWithSourceArray:moves lock:[self threadLock]]
                     positionsEvaluated:&positionsEvaluated
                                utility:&utility];
  
  if (positionsEvaluated>0) {
    if (bestMove==nil) bestMove = [NSArray array];
    
    [moveInfo setObject:bestMove forKey:@"move"];
    [moveInfo setObject:[NSNumber numberWithInt:positionsEvaluated] forKey:@"positionsEvaluated"];
    [moveInfo setObject:[NSNumber numberWithInt:utility] forKey:@"utility"];
    
    [self _recordBestMoveFoundInThread:moveInfo];
    if (DEBUG) {
      NSLog(@"Finished processing in thread:%@", [NSThread currentThread]);
    }
  }
  else {
    if (DEBUG) NSLog(@"No moves available to process in thread:%@", [NSThread currentThread]);
  }
  [lock unlockWithCondition:1];
  [pool release];
}

//////////////////////////////// end thread support /////////////////////////////

-(NSDictionary *)bestMoveInfoForGame:(Game *)game {
  int nthreads = [self threadsToUse];
  NSDictionary *moveInfo;

  if (nthreads<=1) {
    NSTimeInterval t1 = [NSDate timeIntervalSinceReferenceDate];
    NSTimeInterval t2;
    int positionsEvaluated=0;
    NSMutableDictionary *detailInfo = [NSMutableDictionary dictionary];
    NSArray *bestMove = nil;
    int d = [self searchDepthForGame:game];
    int utility;

    bestMove = [self alphaBetaMoveForGame:game
                                    depth:d
                                    alpha:LOSE_UTILITY-d
                                     beta:WIN_UTILITY+d
                           candidateMoves:nil
                       positionsEvaluated:&positionsEvaluated
                                  utility:&utility];
    
    if (bestMove==nil) bestMove = [NSArray array];
    [detailInfo setObject:bestMove forKey:@"move"];
    [detailInfo setObject:[NSNumber numberWithInt:positionsEvaluated] forKey:@"positionsEvaluated"];
    [detailInfo setObject:[NSNumber numberWithInt:utility] forKey:@"utility"];
    t2 = [NSDate timeIntervalSinceReferenceDate];
    [detailInfo setObject:[NSNumber numberWithDouble:t2-t1] forKey:@"time"];
    moveInfo = detailInfo;
  }
  else {
    NSArray *candidateMoves = [self movesToConsiderForGame:game];
    moveInfo = [self _bestMoveInfoForGame:game
                           candidateMoves:candidateMoves
                          spawningThreads:nthreads];
  }
  
  if (DEBUG) {
    NSLog(@"AI done, time=%@ sec, utility=%@", [moveInfo objectForKey:@"time"], [moveInfo objectForKey:@"utility"]);
  }
  return moveInfo;
}

-(void)computeBestMoveForGame:(Game *)game {
  Game *gamecopy = [[game copy] autorelease];
  NSMutableDictionary *moveInfo = [[self bestMoveInfoForGame:gamecopy] mutableCopy];
  [moveInfo setObject:game forKey:@"game"];
  //NSLog(@"Computed best move:%@ in thread:%@", move, [NSThread currentThread]);
  [[NSNotificationCenter defaultCenter] postNotificationName:@"AIComputedBestMoveNotification"
                                                      object:self
                                                    userInfo:moveInfo];
}

@end