File: GameController.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 (987 lines) | stat: -rw-r--r-- 36,768 bytes parent folder | download | duplicates (6)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
/* 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 "GameController.h"
#import "GenericAI.h"
#import "Preferences.h"
#import "NetConnection.h"

static NSString *SAVED_FRAME_NAME=@"WindowFrame";

@implementation GameController

-(id)init {
  if (self=[super init]) {
    movePositions = [[NSMutableArray alloc] init];
    playerWins = [[NSMutableArray alloc] initWithObjects:[NSNumber numberWithInt:0],
                                                         [NSNumber numberWithInt:0],
                                                         [NSNumber numberWithInt:0], nil];
    [self setGameState:[[[GridlockGameState alloc] init] autorelease]];
  }
  return self;
}

-(void)dealloc {
  [[NSNotificationCenter defaultCenter] removeObserver:self];

  [self setGameState:nil];
  [movePositions release];
  [playerWins release];
  
  [super dealloc];
}

-(void)awakeFromNib {
  [self retain];
  
  // use Ataxx as default game if none set
  NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
  [defaults setObject:@"Ataxx" forKey:@"initialGame"];
  [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
  
  // save difference between window width and height so resizing can maintain it
  widthDelta = [window frame].size.width - [window frame].size.height;

  // setting Autosave name in IB is not reliable
  [window setFrameUsingName:SAVED_FRAME_NAME];
  [window setFrameAutosaveName:SAVED_FRAME_NAME];

  if ([[NSUserDefaults standardUserDefaults] integerForKey:@"StatsVisible"]) {
    [self showStatisticsDrawer:nil];
  }

  [window setAcceptsMouseMovedEvents:YES];
  [self buildGamePopup];

  [player1TurnView setPlayerNumber:1];
  [player2TurnView setPlayerNumber:2];

  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(gotNetworkConnection:)
                                               name:@"NetConnectionEstablishedNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(networkConnectionTerminated:)
                                               name:@"NetConnectionTerminatedNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(receivedPropertyListFromNetwork:)
                                               name:@"NetConnectionReadPropertyListNotification"
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(aiComputedMoveInfo:)
                                               name:@"AIComputedBestMoveNotification"
                                             object:nil];

  [self updateNetworkStatus];
  
  // set the default game
  [self restartGameWithConfiguration:[GameConfiguration configurationFromDefaults]];

  // workaround for bug where drawer size can't be set in IB
  [networkDrawer setContentSize:NSMakeSize(481, 157)];
}

idAccessor(gameState, setGameState)

-(GameHistory *)gameHistory {
  return [[self gameState] gameHistory];
}
-(void)setGameHistory:(GameHistory *)value {
  [[self gameState] setGameHistory:value];
}

-(GameConfiguration *)gameConfiguration {
  return [[self gameHistory] gameConfiguration];
}

-(NSString *)gameName {
  return [[self gameConfiguration] gameName];
}
-(NSString *)gameDisplayName {
  return [[self gameConfiguration] gameDisplayName];
}

-(NSString *)gameVariationName {
  return [[self gameConfiguration] variationName];
}
-(NSString *)gameVariationDisplayName {
  return [[self gameConfiguration] variationDisplayName];
}

-(Game *)game {
  return [[self gameHistory] currentGame];
}

-(void)restartGameWithHistory:(GameHistory *)history {
  [self setGameHistory:history];

  [self cancelPendingAIMoves];
  [statusField setStringValue:@""];
  [[self gameConfiguration] saveToDefaults];

  [self buildPlayerPopups];
  [self buildConfigurationPopup];

  if (![[self game] showScores]) {
    [player1ScoreField setStringValue:@""];
    [player2ScoreField setStringValue:@""];
  }

  [boardView setDelegate:[[self gameConfiguration] viewDelegate]];
  [boardView setGameHistory:[self gameHistory]];

  [boardView setHighlightedPositions:nil];

  [gamePopup selectItemWithTitle:[self gameDisplayName]];
  [window setTitle:[self gameDisplayName]];

  [self updateNetworkStatus];

  [self gameStateChanged];  
}

-(void)restartGameWithConfiguration:(GameConfiguration *)gameConfig {
  [self restartGameWithHistory:[[[GameHistory alloc] initWithGameConfiguration:gameConfig] autorelease]];
}

-(void)restartGame {
  [self restartGameWithConfiguration:[self gameConfiguration]];
}

-(void)buildGamePopup {
  NSArray *displayNames = [GameConfiguration allGameDisplayNames];
  NSArray *names = [GameConfiguration allGameNames];
  [gamePopup setItemTitles:displayNames representedObjects_:names];
}

-(void)buildConfigurationPopup {
  NSArray *variationDisplayNames = [[self gameConfiguration] allVariationDisplayNames];
  NSArray *variationNames = [[self gameConfiguration] allVariationNames];
  if ([variationDisplayNames count]>1) {
    int i;
    
    [configurationPopup removeAllItems];
    [configurationPopup setEnabled:YES];
    for(i=0; i<[variationDisplayNames count]; i++) {
      [configurationPopup addItemWithTitle:[variationDisplayNames objectAtIndex:i]];
      [[configurationPopup lastItem] setRepresentedObject:[variationNames objectAtIndex:i]];
    }
    [configurationPopup selectItemWithTitle:[[self gameConfiguration] variationDisplayName]];
  }
  else {
    [configurationPopup removeAllItems];
    [configurationPopup addItemWithTitle:NSLocalizedString(@"NoVariationsTitle", nil)];
    [configurationPopup setEnabled:NO];
  }
}


-(void)gameStateChanged {
  [self clearMovePositions];
  [self updateScores];
  [boardView setHighlightedPositions:nil];
  [boardView setFlashingPositions:nil];
  [boardView setNeedsDisplay:YES];
  [self cancelPendingAIMoves];

  if ([[self game] isGameOver]) {
    [self doGameOver];
  }
  else {
    [statusField setStringValue:@""];
    if ([self shouldMakeAIMove]) {
      [self makeAIMove];
    }
    else {
      [passButton setEnabled:[[self game] isPassValid]];
    }
  }
  [moveRecordTable reloadData];
}


-(BOOL)hasStartedMove {
  return ([[self movePositions] count]>0);
}

-(NSArray *)movePositions {
  return movePositions;
}

-(void)appendMovePosition:(id)position {
  [movePositions addObject:position];
}

-(void)setMovePositions:(NSMutableArray *)positions {
  [movePositions autorelease];
  movePositions = [positions retain];
}

-(void)removeLastPositionFromMove {
  [movePositions removeLastObject];
}

-(void)clearMovePositions {
  [movePositions removeAllObjects];
}

-(void)updateScores {
  int pnum = [[self game] currentPlayerNumber];
  if ([[self game] showScores]) {
    [player1ScoreField setIntValue:[[self game] scoreForPlayer:1]];
    [player2ScoreField setIntValue:[[self game] scoreForPlayer:2]];
  }
  [player1TurnView setVisible:(pnum==1)];
  [player2TurnView setVisible:(pnum==2)];
}

-(void)doGameOver {
  int wpnum = [[self game] winningPlayer];
  if (wpnum==0) {
    NSString *msg = [[NSBundle mainBundle] localizedStringForKey:@"TieMessage"
                                                           value:@"Tie"
                                                           table:nil];
    [statusField setStringValue:msg];
  }
  else {
    NSString *msg = [[NSBundle mainBundle] localizedStringForKey:@"WinMessage"
                                                           value:@"Player %d wins"
                                                           table:nil];
    [statusField setStringValue:[NSString stringWithFormat:msg,wpnum]];
  }
  [boardView setFlashingPositions:[[self game] positionsOfWinningPieces]];
  [passButton setEnabled:NO];
  //NSLog(@"Game Over: %d %d", [game scoreForPlayer:1], [game scoreForPlayer:2]);
  [playerWins replaceObjectAtIndex:wpnum
              withObject:[NSNumber numberWithInt:1+[[playerWins objectAtIndex:wpnum] intValue]]];
    
  [p1Wins setIntValue:[[playerWins objectAtIndex:1] intValue]];
  [p2Wins setIntValue:[[playerWins objectAtIndex:2] intValue]];

  /*
  if (FASTPLAY) {
    NSLog(@"Total record: %@", [playerWins componentsJoinedByString:@","]);
    if ([playerAIs count]==[[self game] numberOfPlayers]) {
      [self restartGame];
    }
  }
     */
}

-(void)doMoveSequence:(NSArray *)positions {
  // notify network players if this move wasn't received from the network
  //NSLog(@"Current player=%d", [[self game] currentPlayerNumber]);
  if (nil==[[self gameState] netConnectionForPlayer:[[self game] currentPlayerNumber]]) {
    [self sendMoveToNetworkPlayers:positions];
  }
  
  [[self game] prepareMoveSequence:positions];
  inAnimation = YES;
  {
    NSArray *positionsNotAnimating = [[Preferences sharedInstance] animateCapturedPieces] ?
                                        positions : [[self game] positionsOfAllChangingCells];

    [boardView setHighlightedPositions:nil];
    [boardView beginMoveAnimationForPositions:[[self game] positionsOfAllChangingCells]
                 immediatelyChangingPositions:positionsNotAnimating
                               callbackObject:positions];
  }
}

-(BOOL)isWaitingForHumanMove {
  return (![[self game] isGameOver] && !inAnimation &&
          [[self gameState] isCurrentPlayerHuman]);
}


-(void)boardView:(BoardView *)view clickedAtPosition:(DCHypergridPosition *)position {
  if (boardView && boardView==view && [self isWaitingForHumanMove]) {
    int row = [position row];
    int col = [position column];
    if (row>=0 && row<[[self game] numberOfRows] && col>=0 && col<[[self game] numberOfColumns]) {
      id position = [DCHypergridPosition positionWithRow:row column:col];
      //NSLog(@"Got click at row:%d col:%d", row, col);

      [self appendMovePosition:position];
      if ([[self game] isCompleteMoveSequenceValid:[self movePositions]]) {
        // FIXME: if the sequence is also a valid partial move, we should require confirmation
        //NSLog(@"Executing move");
        [self doMoveSequence:[self movePositions]];
      }
      else if ([[self game] isPartialMoveSequenceValid:[self movePositions]]) {
        // do nothing, keep added position
        //NSLog(@"Added to move sequence");
      }
      else {
        // not a valid move, but check if it's a valid move or start by itself
        NSMutableArray *newArray = [NSMutableArray arrayWithObject:position];
        [self removeLastPositionFromMove];
        if ([[self game] isPartialMoveSequenceValid:newArray]) {
          //NSLog(@"Started new move");
          [self setMovePositions:newArray];
        }
        else {
          // we don't want to execute it if it's a complete move
          [self clearMovePositions];
        }
        [boardView setHighlightedPositions:[[[self movePositions] copy] autorelease]];
      }      
    }
  }
}

-(void)recordAndExecuteMove:(NSArray *)move {
  [[self gameHistory] recordAndExecuteMove:move];
}

-(NSArray *)humanPlayerNumbers {
  NSMutableArray *humanNumbers = [NSMutableArray array];
  int i;
  for(i=0; i<[[self game] numberOfPlayers]; i++) {
    if ([[self gameState] isPlayerHuman:i+1]) {
      [humanNumbers addObject:[NSNumber numberWithInt:i+1]];
    }
  }
  return humanNumbers;
}

-(void)undoMove:(id)sender {
  if ([[self gameHistory] undoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]]) {
    [self gameStateChanged];
  }
  else {
    NSBeep();
  }
}

-(void)redoMove:(id)sender {
  if ([[self gameHistory] redoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]]) {
    [self gameStateChanged];
  }
  else {
    NSBeep();
  }
}

-(BOOL)validateMenuItem:(NSMenuItem *)item {
  // don't allow undo/redo in network games, and make sure the game state is undo/redoable
  // GNUstep selectors can't be compared with ==
  NSString *selName = NSStringFromSelector([item action]);
  if ([@"undoMove:" isEqualToString:selName]) {
    if ([self isInNetworkGame]) return NO;
    return [[self gameHistory] canUndoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]];
  }
  if ([@"redoMove:" isEqualToString:selName]) {
    if ([self isInNetworkGame]) return NO;
    return [[self gameHistory] canRedoMovesUntilPlayerNumberInArray:[self humanPlayerNumbers]];
  }
  if ([@"openDocument:" isEqualToString:selName]) {
    if ([self isInNetworkGame]) return NO;
  }
  return YES;
}

-(void)boardView:(BoardView *)view finishedMoveAnimation:(id)callbackObject {
  // callback object is positions in the move
  NSArray *moveToExecute = callbackObject;
  [self recordAndExecuteMove:moveToExecute];
  inAnimation = NO;
  [self gameStateChanged];
}

-(void)boardView:(BoardView *)view mouseMovedOverPosition:(DCHypergridPosition *)position {
  //NSLog(@"Mouse moved at row:%d col:%d", [position row], [position column]);
  if ([self isWaitingForHumanMove]) {
    if (position) {
      NSArray *moves = [[self movePositions] arrayByAddingObject:position];
      if ([[self game] isCompleteMoveSequenceValid:moves] || [[self game] isPartialMoveSequenceValid:moves]) {
        [boardView setHighlightedPositions:moves];
      }
      else {
        [boardView setHighlightedPositions:[[[self movePositions] copy] autorelease]];
      }
    }
    else {
      // mouse moved outside board
      [boardView setHighlightedPositions:[[[self movePositions] copy] autorelease]];
    }
  }
}

-(BOOL)shouldMakeAIMove {
  if (0==[[[self gameState] aiNameForPlayer:[[self game] currentPlayerNumber]] length]) return NO;
  if ([[self game] isGameOver]) return NO;

  return YES;
}

-(void)cancelPendingAIMoves {
  /* create a unique move ID that we want the results for, so if multiple responses come back (which can happen if
  the user switches AIs while in mid-move, we only accept one of them.
  */
  aiMoveID = (aiMoveID+1)%(1<<14);  
}

-(id)idForPendingAIMove {
  return [NSNumber numberWithInt:aiMoveID];
}

-(void)makeAIMove {
  [self cancelPendingAIMoves];
  // We need a delay here, or else if the AI thread comes back really fast (as it will for low search levels),
  // the main event loop will never get a chance to process user input so menus and buttons won't respond.
  [self performSelector:@selector(detachAIThread) withObject:nil afterDelay:0.01 inModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, NSEventTrackingRunLoopMode, NSModalPanelRunLoopMode, nil]];
}

-(void)detachAIThread {
  [NSThread detachNewThreadSelector:@selector(makeAIMoveInThread:) toTarget:self withObject:[self idForPendingAIMove]];
}

-(void)makeAIMoveInThread:(id)moveIDForThread {
  id pool = [[NSAutoreleasePool alloc] init];
  [[[NSThread currentThread] threadDictionary] setObject:moveIDForThread forKey:@"moveID"];
  [[self gameState] makeAIMove];
  [pool release];  
}

-(void)aiComputedMoveInfoMainThread:(NSArray *)params {
  if ([self isWaitingForHumanMove]) {
    NSLog(@"Got move from AI but controller is human, ignoring move");
    return;
  }
  else {
    id threadMoveID = [params objectAtIndex:1];
    // we don't need a threadsafe accessor for moveID because it's only ever read and written from the main thread
    if (![threadMoveID isEqual:[self idForPendingAIMove]]) {
      NSLog(@"Got wrong move ID from worker thread (%@, expected %@), ignoring move", threadMoveID, [self idForPendingAIMove]);
      return;
    }
    else {
      NSNotification *notification = [params objectAtIndex:0];      
      //GenericAI *ai = [notification object];
      NSDictionary *moveInfo = [notification userInfo];
      //NSLog(@"Received best move:%@ in thread:%@", move, [NSThread currentThread]);
      NSArray *move = [moveInfo objectForKey:@"move"];
      int positionsEvaluated = [[moveInfo objectForKey:@"positionsEvaluated"] intValue];
      
      double moveTime = [[moveInfo objectForKey:@"time"] doubleValue];
      
      [self doMoveSequence:move];
      
      [aiNumMovesEvaluatedField setIntValue:positionsEvaluated];
      [aiTimeField setDoubleValue:moveTime];
      [aiMovesPerSecondField setIntValue:(int)(positionsEvaluated/moveTime)];
    }
  }
}

-(void)aiComputedMoveInfo:(NSNotification *)notification {
  [self performSelectorOnMainThread:@selector(aiComputedMoveInfoMainThread:) 
                         withObject:[NSArray arrayWithObjects:notification,[[[NSThread currentThread] threadDictionary] objectForKey:@"moveID"], nil]
                      waitUntilDone:NO];
}

-(void)buildPlayerPopups {
  NSArray *aiTypes = [[self gameState] availableAINames];
  NSArray *aiDisplayNames = [[self gameState] availableAIDisplayNames];
  NSArray *popups = [NSArray arrayWithObjects:player1TypePopup,player2TypePopup,nil];
  NSEnumerator *pe = [popups objectEnumerator];
  NSPopUpButton *popup;

  int pnum = 1;
  while (popup=[pe nextObject]) {
    int i;
    // representedObjects of popup items are the non-localized names of the AIs ("" for human)
    [popup removeAllItems];
    [popup addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"HumanPlayer" value:@"Human" table:nil]];
    [[popup lastItem] setRepresentedObject:@""];
    for(i=0; i<[aiDisplayNames count]; i++) {
      [popup addItemWithTitle:[[[NSBundle mainBundle] localizedStringForKey:@"ComputerPlayerPrefix"
                                                                      value:@"Human"
                                                                      table:nil]
                                stringByAppendingString:[aiDisplayNames objectAtIndex:i]]];
      [[popup lastItem] setRepresentedObject:[aiTypes objectAtIndex:i]];
    }
    [popup selectItemWithRepresentedObject_:[[self gameState] aiNameForPlayer:pnum]];

    // check for network
    if (nil!=[[self gameState] netConnectionForPlayer:pnum]) {
      [popup addItemWithTitle:[[NSBundle mainBundle] localizedStringForKey:@"NetworkPlayer"
                                                                      value:@"Network"
                                                                      table:nil]];
      [popup selectItemAtIndex:[popup numberOfItems]-1];
    }
    // FIXME: hide menu if only item is "Human"
    ++pnum;
  }
}


-(BOOL)allowRestart {
  if ([[self game] isGameOver] || [[self game] moveCount]==0) {
    return YES;
  }
  else {
    // game is in progress, show confirmation dialog
    NSString *title = NSLocalizedString(@"RestartTitle", nil);
    NSString *okLabel = NSLocalizedString(@"RestartOK", nil);
    NSString *cancelLabel = NSLocalizedString(@"RestartCancel", nil);
    NSString *msgText = NSLocalizedString(@"RestartMessage", nil);

    int result = NSRunAlertPanel(title, msgText, okLabel, cancelLabel, nil);
    return (result==NSAlertDefaultReturn);
  }
}

-(BOOL)confirmNetworkDisconnect {
  NSString *title = NSLocalizedString(@"DisconnectTitle", nil);
  NSString *okLabel = NSLocalizedString(@"DisconnectOK", nil);
  NSString *cancelLabel = NSLocalizedString(@"DisconnectCancel", nil);
  NSString *msgText = NSLocalizedString(@"DisconnectMessage", nil);

  int result = NSRunAlertPanel(title, msgText, okLabel, cancelLabel, nil);
  return (result==NSAlertDefaultReturn);
}

-(IBAction)playerTypeUpdated:(id)sender {
  int pnum = [sender tag];
  NSString *aiName = [[sender selectedItem] representedObject];
  // if in network game, changing player type will disconnect
  if (![self isInNetworkGame] || [self confirmNetworkDisconnect]) {
    [self dropAllNetConnections];
    [[self gameState] setAIName:aiName forPlayer:pnum];
    if ([self shouldMakeAIMove]) {
      [self makeAIMove];
    }
  }
  [self buildPlayerPopups];
}

-(IBAction)configurationSelectedFromPopup:(id)sender {
  if ([self allowRestart]) {
    NSString *varname = [[sender selectedItem] representedObject];
    GameConfiguration *newConfig = [[[GameConfiguration alloc] initWithName:[self gameName] variation:varname] autorelease];
    [self restartGameWithConfiguration:newConfig];
    [self sendRestartToNetworkPlayers];
  }
  else {
    [sender selectItemWithTitle:[self gameVariationDisplayName]];
  }
}

-(IBAction)gameSelectedFromPopup:(id)sender {
  if ([self allowRestart]) {
    NSString *gameName = [[sender selectedItem] representedObject];
    GameConfiguration *newConfig = [[[GameConfiguration alloc] initWithName:gameName variation:nil] autorelease];
    [self restartGameWithConfiguration:newConfig];
    [self sendRestartToNetworkPlayers];
  }
  else {
    [sender selectItemWithTitle:[self gameName]];
  }
}

-(IBAction)passButtonClicked:(id)sender {
  if ([[self game] isCompleteMoveSequenceValid:nil]) {
    //NSLog(@"Executing move");
    [self doMoveSequence:nil];
  }
}

-(IBAction)restartGame:(id)sender {
  if ([self allowRestart]) {
    [[self gameConfiguration] createNewInitialGame];
    [self restartGame];
    [self sendRestartToNetworkPlayers];
  }
}

-(void)restartSheetEnded:(NSWindow *)window returnCode:(int)code contextInfo:(void *)unused {
  if (code==NSAlertDefaultReturn) {
    [self restartGame];
  }
}

-(void)windowWillClose:(NSNotification *)note {
  // clear any previous delayed invocations because they retain their targets
  [self cancelPendingAIMoves];
  [self autorelease];
  // terminate app
  [[NSApplication sharedApplication] performSelector:@selector(terminate:) withObject:nil afterDelay:0.01];
}

-(NSSize)windowWillResize:(NSWindow *)win toSize:(NSSize)newSize {
  if (newSize.width > newSize.height+widthDelta) {
    return NSMakeSize(newSize.height+widthDelta, newSize.height);
  }
  else {
    return NSMakeSize(newSize.width, newSize.width-widthDelta);
  }
}

// recorded move table view data source methods
-(int)numberOfRowsInTableView:(NSTableView *)table {
  return [[self gameHistory] numberOfMoves]/2;
}

-(id)tableView:(NSTableView *)table objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row {
  int col = [[tableColumn identifier] intValue];
  int index = [[table tableColumns] count]*row + col - 1;
  NSArray *move = [[self gameHistory] moveWithNumber:index];
  return (move) ? [[self game] descriptionForMove:move] : @"";
}

-(void)tableView:(NSTableView *)table willDisplayCell:(id)cell forTableColumn:(NSTableColumn *)tableColumn row:(int)row {
  int col = [[tableColumn identifier] intValue];
  int index = [[table tableColumns] count]*row + col - 1;
  if (index>=[[self gameHistory] currentMoveNumber]) {
    [cell setTextColor:[NSColor redColor]];
  }
  else {
    [cell setTextColor:[NSColor blackColor]];
  }
}

-(BOOL)tableView:(NSTableView *)aTableView shouldEditTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex {
  return NO;
}

//////////////////////////////////////////////////////////////////////////////////
// loading and saving games
-(id)propertyList {
  NSMutableDictionary *plist = [NSMutableDictionary dictionary];
  [plist setObject:[[self gameHistory] propertyList] forKey:@"history"];
  {
    NSMutableDictionary *aiDict = [NSMutableDictionary dictionary];
    int i;
    for(i=1; i<=[[self game] numberOfPlayers]; i++) {
      NSString *aiName = [[self gameState] aiNameForPlayer:i];
      if ([aiName length]>0) {
        [aiDict setObject:aiName forKey:[[NSNumber numberWithInt:i] stringValue]];
      }
    }
    [plist setObject:aiDict forKey:@"AIs"];
  }
  return plist;
}
-(void)updateFromPropertyList:(id)plist {
  GameHistory *newHistory = [[[GameHistory alloc] initFromPropertyList:[plist objectForKey:@"history"]] autorelease];
  if (newHistory) {
    // update AIs in Preferences, they will be created in restartGame...
    NSDictionary *aiDict = [plist objectForKey:@"AIs"];
    int i;
    for(i=1; i<=[[newHistory currentGame] numberOfPlayers]; i++) {
      NSString *aiName = [aiDict objectForKey:[NSString stringWithFormat:@"%d",i]];
      if (!aiName) aiName = @"";
      [[Preferences sharedInstance] setAIType:aiName forGame:[[newHistory gameConfiguration] gameName] player:i];
    }
    [self restartGameWithHistory:newHistory];
  }
  else {
    NSLog(@"Failed to load game");
  }
}

-(IBAction)saveDocument:(id)sender {
  NSSavePanel *panel = [NSSavePanel savePanel];
  // GNUstep doesn't like sheets (it implements the methods but the return code isn't set)
#ifdef GNUSTEP
  if ([panel runModal]==NSFileHandlingPanelOKButton) {
    [self saveGameToURL:[panel URL]];
  }
#else
  [panel beginSheetForDirectory:nil file:nil modalForWindow:window modalDelegate:self didEndSelector:@selector(savePanelEnded:returnCode:contextInfo:) contextInfo:nil];
#endif
}

-(void)saveGameToURL:(NSURL *)url {
  id plist = [self propertyList];
  if ([plist writeToURL:url atomically:YES]==NO) {
    NSLog(@"Error saving game to:%@", url);
    [self performSelector:@selector(showSaveFailedPanelForURL:) withObject:url afterDelay:0.0];
  }
}

-(void)showSaveFailedPanelForURL:(NSURL *)url {
  NSRunAlertPanel(NSLocalizedString(@"SaveFailedTitle", nil),
                  NSLocalizedString(@"SaveFailedMessage", nil), nil, nil, nil);
}

-(void)savePanelEnded:(NSSavePanel *)panel returnCode:(int)code contextInfo:(void *)info {
  if (code==NSOKButton) {
    [self saveGameToURL:[panel URL]];
  }
}

-(IBAction)openDocument:(id)sender {
  if ([self isInNetworkGame]) {
    NSBeep();
  }
  else {
    NSOpenPanel *panel = [NSOpenPanel openPanel];
    // GNUstep doesn't like sheets (it implements the methods but the return code isn't set)
#ifdef GNUSTEP
    if ([panel runModalForTypes:nil]==NSOKButton) {
      [self loadGameFromURL:[panel URL]];
    }
#else
    [panel beginSheetForDirectory:nil file:nil modalForWindow:window modalDelegate:self didEndSelector:@selector(openPanelEnded:returnCode:contextInfo:) contextInfo:nil];
#endif
  }
}

-(void)loadGameFromURL:(NSURL *)url {
  id plist;
NS_DURING
  plist = [[NSString stringWithContentsOfURL:url] propertyList];
NS_HANDLER
  plist = nil;
NS_ENDHANDLER
  if (plist) {
    [self updateFromPropertyList:plist];
  }
  else {
    NSLog(@"Can't restore saved game from:%@", url);
    [self performSelector:@selector(showLoadFailedPanelForURL:) withObject:url afterDelay:0.0];
  }
}

-(void)showLoadFailedPanelForURL:(NSURL *)url {
  NSRunAlertPanel(NSLocalizedString(@"LoadFailedTitle", nil),
                  NSLocalizedString(@"LoadFailedMessage", nil), nil, nil, nil);
}

-(void)openPanelEnded:(NSSavePanel *)panel returnCode:(int)code contextInfo:(void *)info {
  if (code==NSOKButton) {
    [self loadGameFromURL:[panel URL]];
  }
}


/////////////////////////////////////////////////////////////////////////////////////
// network support

-(BOOL)isInNetworkGame {
  return [[[self gameState] allNetConnections] count]>0;
}

-(void)gotNetworkConnection:(NSNotification *)notification {
  id playerNum = [[notification userInfo] objectForKey:@"playerNumber"];
  NetConnection *connection = [[notification userInfo] objectForKey:@"connection"];
  GameConfiguration *config = [[notification userInfo] objectForKey:@"configuration"];
  if (playerNum && connection && config) {
    NSLog(@"Got remote connection, restarting");
    [self restartGameWithConfiguration:config];
    // update player menus
    [[self gameState] makeAllPlayersHuman];
    [[self gameState] setNetConnection:connection forPlayer:[playerNum intValue]];
    [self buildPlayerPopups];

    [self updateNetworkStatus];
    
    [self showNetworkDrawer:nil];
  }
}

-(void)sendPropertyListToNetworkPlayers:(id)plist {
  [[[self gameState] allNetConnections] makeObjectsPerformSelector:@selector(transmitPropertyList:) withObject:plist];  
}

-(void)updateNetworkStatus {
  NSArray *connections = [[self gameState] allNetConnections];
  if ([connections count]>0) {
    // for now assume only one
    id conn = [connections objectAtIndex:0];
    [networkStatusField setStringValue:[NSString stringWithFormat:NSLocalizedString(@"NetworkStatusConnected", nil), [conn remoteIPAddress]]];
    [disconnectButton setEnabled:YES];
    [chatMessageField setEnabled:YES];
  }
  else {
    [networkStatusField setStringValue:NSLocalizedString(@"NetworkStatusNotConnected", nil)];
    [disconnectButton setEnabled:NO];
    [chatMessageField setEnabled:NO];
  }  
}

-(void)dropAllNetConnections {
  [[[self gameState] allNetConnections] makeObjectsPerformSelector:@selector(sendDisconnect)];
}

-(IBAction)disconnectButtonClicked:(id)sender {
  if ([self isInNetworkGame] && [self confirmNetworkDisconnect]) {
    [self dropAllNetConnections];
  }
}

-(void)dropNetConnectionForPlayer:(NSNumber *)pnum {
  [[[self gameState] netConnectionForPlayer:[pnum intValue]] setIsDisconnected:YES];
  [[self gameState] setNetConnection:nil forPlayer:[pnum intValue]];
  [self buildPlayerPopups];
  // this won't work if >2 players
  [self updateNetworkStatus];
}

-(void)receivedPropertyListFromNetwork:(NSNotification *)notification {
  int pnum = [[self gameState] playerNumberForNetConnection:[notification object]];
  if (pnum>0) {
    NSDictionary *plist = [[notification userInfo] objectForKey:@"plist"];
    //NSLog(@"Read plist from network:%@", [plist description]);
    // check for disconnect or error
    if ([plist objectForKey:@"disconnect"]) {
      NSLog(@"Received disconnect");
      // we want to keep the connection around until the next run loop, otherwise
      // there are timing problems where the NetConnection can get data notifications
      // just after it's dealloced.
      [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
    }
    else if ([plist objectForKey:@"error"]) {
      NSLog(@"Received error:%@", [plist objectForKey:@"error"]);
      [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
    }
    else if ([plist objectForKey:@"chat"]) {
      NSString *msg = [plist objectForKey:@"chat"];
      //NSLog(@"Received chat message:%@", msg);
      [chatTranscriptArea appendText:[NSString stringWithFormat:@"%@: %@\n",
                                               [[notification object] remoteUsername], msg]
                        scrollToEnd_:YES];
    }
    else if ([plist objectForKey:@"restart"]) {
      // TODO: ask for verification
      GameConfiguration *config = [self gameConfiguration];
      NSDictionary *configPlist = [plist objectForKey:@"configuration"];
      if (configPlist) {
        config = [[[GameConfiguration alloc] initFromPropertyList:configPlist] autorelease];
      }
      [self restartGameWithConfiguration:config];
      [chatTranscriptArea appendText:[NSLocalizedString(@"GameRestartedMessage",nil) stringByAppendingString:@"\n"] scrollToEnd_:YES];
    }
    else if ([plist objectForKey:@"start"]) {
      // do nothing, this is the start request, handled in ClientController
    }
    else {
      NSArray *moveStrings = [plist objectForKey:@"move"];
      id gamePlist = [plist objectForKey:@"game"];
      //NSLog(@"Got move from network:%@", [moveStrings description]);
      if (moveStrings && gamePlist) {
        // make sure it's the right turn
        if (pnum!=[[self game] currentPlayerNumber]) {
          NSLog(@"Move for player %d received when player %d's turn", pnum, [[self game] currentPlayerNumber]);
          [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
        }
        else {
          // validate move
          NSArray *move = [DCHypergridPosition positionArrayFromPropertyListValueArray:moveStrings];
          Game *gameCopy = [[[self game] copy] autorelease];
          if ([gameCopy isCompleteMoveSequenceValid:move] && [gameCopy makeMoveSequence:move]) {
            // move is valid, make sure the resulting state matches
            Game *gameFromClient = [[[[self gameConfiguration] initialGame] copy] autorelease];
            [gameFromClient updateFromPropertyList:gamePlist];
            if ([[gameCopy grid] isEqualToHypergrid:[gameFromClient grid]]) {
              // good move, execute
              [self doMoveSequence:move];
            }
            else {
              NSLog(@"Inconsistency in game state from client");
              [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
            }
          }
          else {
            NSLog(@"Received invalid move from client:%@", [move description]);
            [self performSelector:@selector(dropNetConnectionForPlayer:) withObject:[NSNumber numberWithInt:pnum] afterDelay:0.0];
          }
        }
      }
      else {
        NSLog(@"Received unrecognized message:%@", [plist description]);
      }
    }
  }
}

-(IBAction)sendChatMessage:(id)sender {
  if ([[chatMessageField stringValue] length]>0 && [[[self gameState] allNetConnections] count]>0) {
    NSMutableDictionary *chatDict = [NSMutableDictionary dictionary];
    [chatDict setObject:[chatMessageField stringValue] forKey:@"chat"];
    [self sendPropertyListToNetworkPlayers:chatDict];
    [chatTranscriptArea appendText:[NSString stringWithFormat:@"%@: %@\n", [[Preferences sharedInstance] networkUsername], [chatMessageField stringValue]] scrollToEnd_:YES];
  }
  [chatMessageField setStringValue:@""];
}

-(void)sendMoveToNetworkPlayers:(NSArray *)move {
  if ([[self gameState] hasNetConnections]) {
    Game *gameCopy = [[[self game] copy] autorelease];
    NSMutableDictionary *movePlist = [NSMutableDictionary dictionary];
    NSEnumerator *ne = [[[self gameState] allNetConnections] objectEnumerator];
    id conn;
    
    [gameCopy makeMoveSequence:move];
    [movePlist setObject:[move valuesByObjectsPerformingSelector:@selector(propertyListValue)] forKey:@"move"];
    //NSLog(@"move array:%@", move);
    [movePlist setObject:[gameCopy propertyList] forKey:@"game"];

    while (conn=[ne nextObject]) {
      //NSLog(@"Writing plist to network:%@", [movePlist description]);
      [conn transmitPropertyList:movePlist];
    }
  }
}

-(void)sendRestartToNetworkPlayers {
  NSMutableDictionary *restartDict = [NSMutableDictionary dictionary];
  [restartDict setObject:@"1" forKey:@"restart"];
  [restartDict setObject:[[self gameConfiguration] propertyList] forKey:@"configuration"];
  [self sendPropertyListToNetworkPlayers:restartDict];
}

-(void)networkConnectionTerminated:(NSNotification *)notification {
  int pnum = [[self gameState] playerNumberForNetConnection:[notification object]];
  if (pnum>0) {
    [self dropNetConnectionForPlayer:[NSNumber numberWithInt:pnum]];
  }
}


/////////////////////////////////////////////////////////////////////////////////

/* These methods operate on both the drawer and window ivars. One of each will be nil
(window ivar is not set in OS X, drawer is not set in GNUstep), messages to them will be ignored.
*/
-(IBAction)toggleStatisticsDrawer:(id)sender {
  [statisticsDrawer toggle:self];
  [statisticsWindow makeKeyAndOrderFront:nil];
}
-(IBAction)showStatisticsDrawer:(id)sender {
  [statisticsDrawer open];
  [statisticsWindow makeKeyAndOrderFront:nil];
}

-(IBAction)toggleNetworkDrawer:(id)sender {
  [networkDrawer toggle:self];
  [networkWindow makeKeyAndOrderFront:nil];
}
-(IBAction)showNetworkDrawer:(id)sender {
  [networkDrawer open];
  [networkWindow makeKeyAndOrderFront:nil];
}

-(void)drawerDidOpen:(NSNotification *)notification {
  if ([notification object]==statisticsDrawer) {
    [[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"StatsVisible"];
  }
}
-(void)drawerDidClose:(NSNotification *)notification {
  if ([notification object]==statisticsDrawer) {
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"StatsVisible"];
  }
}

@end