forked from alisdair/freecell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GameController.m
407 lines (345 loc) · 12.2 KB
/
GameController.m
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
//
// GameController.m
// Freecell
//
//
// Created by Alisdair McDiarmid on Tue Jul 08 2003.
// Copyright (c) 2003 Alisdair McDiarmid. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// ALISDAIR MCDIARMID BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#import "GameController.h"
@interface GameController (PrivateMethods)
- (void) GC_startGame;
@end
@implementation GameController
// Overridden methods
//
- (void) awakeFromNib
{
srandom((unsigned int)time(NULL));
[history awakeFromNib];
[self updateTime: timer];
[self moveMade];
[window setReleasedWhenClosed: NO];
[window setMiniwindowTitle: @"Freecell"];
[view setController: self];
[self newGame: self];
timer = nil;
}
- (BOOL) applicationShouldHandleReopen: (NSApplication *) app hasVisibleWindows: (BOOL) flag
{
if (flag == NO)
[self newGame: self];
return YES;
}
- (BOOL) windowShouldClose: (id) sender
{
if ([game inProgress] == NO)
{
[self setGame: nil];
return YES;
}
NSBeginAlertSheet(NSLocalizedString(@"closeTitle", @"windowShouldClose sheet title"),
NSLocalizedString(@"closeButton", @"Close button"),
NSLocalizedString(@"cancelButton", @"Cancel button"),
nil, window, self,
@selector(windowCloseSheetDidEnd:returnCode:contextInfo:),
NULL, NULL,
NSLocalizedString(@"closeText", @"windowShouldClose sheet text"));
return NO;
}
- (NSApplicationTerminateReply) applicationShouldTerminate: (id) sender
{
if ([game inProgress] == NO)
return NSTerminateNow;
NSBeginAlertSheet(NSLocalizedString(@"closeTitle", @"windowShouldClose sheet title"),
NSLocalizedString(@"closeButton", @"Close button"),
NSLocalizedString(@"cancelButton", @"Cancel button"),
nil, window, self,
@selector(applicationTerminateSheetDidEnd:returnCode:contextInfo:),
NULL, NULL,
NSLocalizedString(@"closeText", @"windowShouldClose sheet text"));
return NSTerminateLater;
}
- (BOOL) validateMenuItem: (NSMenuItem *) menuItem
{
if ([menuItem tag] == 1)
return [game canUndo];
if ([menuItem tag] == 2)
return [game canRedo];
return YES;
}
- (void) windowWillClose: (NSNotification *) notification
{
if ([[notification object] isEqual: window])
[self setGame: nil];
}
// Action methods
//
- (IBAction) newGame: (id) sender
{
[self playGameWithNumber: [NSNumber numberWithDouble: (double) random()]];
}
- (IBAction) retryGame: (id) sender
{
[self GC_startGame];
}
- (IBAction) playGameNumber: (id) sender
{
[NSApp stopModal];
[self GC_startGame];
}
- (IBAction) openPlayNumberDialog: (id) sender
{
if ([window attachedSheet] == nil)
{
[NSApp beginSheet: playNumberDialog
modalForWindow: window
modalDelegate: nil
didEndSelector: nil
contextInfo: nil];
[NSApp runModalForWindow: window];
// Wait for sheet to end...
[NSApp endSheet: playNumberDialog];
[playNumberDialog orderOut: self];
[playNumberDialog close];
}
}
- (IBAction) closePlayNumberDialog: (id) sender
{
[NSApp stopModal];
}
- (IBAction) showHint: (id) sender
{
[game setHint];
if ([game hint])
{
[view display];
[self performSelector:@selector(hintDone) withObject:nil afterDelay:1];
}
}
- (void) hintDone {
[game setHint: nil];
[view display];
}
- (IBAction) undo: (id) sender
{
[game undo];
}
- (IBAction) redo: (id) sender
{
[game redo];
}
// Private methods
//
- (void) GC_startGame
{
if ([window attachedSheet] != nil)
{
// Clear up the you-won/you-lost dialog if it's open
if ([game inProgress] == NO)
{
[NSApp endSheet: [window attachedSheet]];
[NSApp stopModal];
}
// Otherwise, we must already be checking whether or not to end the game
else
return;
}
if ([game inProgress] == YES)
NSBeginAlertSheet(NSLocalizedString(@"newGameTitle", @"New game sheet title"),
NSLocalizedString(@"newGameButton", @"New game button"),
NSLocalizedString(@"cancelButton", @"Cancel button"),
nil, window, self,
@selector(startGameSheetDidEnd:returnCode:contextInfo:),
NULL, NULL,
NSLocalizedString(@"newGameText", "New game sheet text"));
else
{
NSNumber *gameNumber = [NSNumber numberWithDouble: [gameNumberField doubleValue]];
[self setGame: [Game gameWithView: view controller: self gameNumber: gameNumber]];
[view setGame: game];
[window setTitle: [NSString stringWithFormat:
NSLocalizedString(@"gameWindowTitleFormat", @"Format for the title of the game window"), [gameNumberField stringValue]]];
[window makeKeyAndOrderFront: self];
[window makeMainWindow];
[timer invalidate];
timer = [NSTimer scheduledTimerWithTimeInterval: 1 target: self
selector: @selector(updateTime:)
userInfo: nil
repeats: YES];
[self updateTime: timer];
[self moveMade];
}
}
// Sheet handlers
//
- (void) startGameSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (void *) contextInfo
{
if (returnCode == NSAlertDefaultReturn)
{
[self setGame: nil];
[self GC_startGame];
}
}
- (void) windowCloseSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (void *) contextInfo
{
if (returnCode == NSAlertDefaultReturn)
[window close];
}
- (void) applicationTerminateSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (void *) contextInfo
{
if (returnCode == NSAlertDefaultReturn)
[window close];
[NSApp replyToApplicationShouldTerminate: (returnCode == NSAlertDefaultReturn)];
}
- (void) gameWonSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (void *) contextInfo
{
if (returnCode == NSAlertAlternateReturn)
[history openWindow: self];
if (returnCode == NSAlertOtherReturn)
[self newGame: self];
}
- (void) gameLostSheetDidEnd: (NSWindow *) sheet returnCode: (int) returnCode
contextInfo: (void *) contextInfo
{
if (returnCode == NSAlertAlternateReturn)
[self retryGame: self];
if (returnCode == NSAlertOtherReturn)
[self newGame: self];
}
// Timer stuff
//
- (void) updateTime: (NSTimer *) sender
{
NSDate *current = [NSDate dateWithTimeIntervalSinceReferenceDate: 0];
NSDate *shortest = [NSDate dateWithTimeIntervalSinceReferenceDate: 0];
NSString *currentDuration;
NSString *shortestDuration;
if ([game inProgress])
{
current = [NSDate dateWithTimeIntervalSinceReferenceDate: [[NSDate date] timeIntervalSinceDate: [game startDate]]];
}
else if (![[game result] isEqual: [Result resultWithUnplayed]])
{
NSTimeInterval duration = [game duration];
current = [NSDate dateWithTimeIntervalSinceReferenceDate: duration];
}
currentDuration = [current descriptionWithCalendarFormat: @"%H:%M:%S"
timeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]
locale: nil];
if (history)
shortest = [history shortestDuration];
shortestDuration = [shortest descriptionWithCalendarFormat: @"%H:%M:%S"
timeZone: [NSTimeZone timeZoneForSecondsFromGMT: 0]
locale: nil];
if (game != nil)
[timeElapsed setStringValue: [NSString stringWithFormat: @"%@ (%@ %@)",
currentDuration, NSLocalizedString(@"bestIs", "best is"), shortestDuration]];
}
- (void) moveMade {
[self performSelectorOnMainThread:@selector(moveMade2) withObject:nil waitUntilDone:NO];
}
- (void) moveMade2
{
NSUInteger currentMoves = [game moves];
NSUInteger shortestMoves = [history shortestMoves];
[movesMade setStringValue: [NSString stringWithFormat: @"%lu %@ (%@ %lu)",
currentMoves, NSLocalizedString(@"moves", "moves"),
NSLocalizedString(@"bestIs", "best is"), shortestMoves]];
}
// Mutators
//
- (void) playGameWithNumber: (NSNumber *) newGame
{
[gameNumberField setDoubleValue: [newGame doubleValue]];
[self GC_startGame];
}
- (void) setWindowSize: (NSSize) size
{
NSRect frame = [window frame];
frame.size = size;
[window setFrame: frame display: YES];
}
- (void) recordGame
{
[history addRecordWithGameNumber: [game gameNumber]
result: [game result]
moves: [game moves]
duration: [game duration]
date: [game startDate]];
}
- (void) setGame: (Game *) newGame
{
if ([game inProgress])
[game gameOverWithResult: [Result resultWithLoss]];
if ([[game result] isEqual: [Result resultWithWin]] || [[game result] isEqual: [Result resultWithLoss]])
[self recordGame];
[game release];
game = [newGame retain];
}
- (void) gameOver {
[self performSelectorOnMainThread:@selector(gameOver2) withObject:nil waitUntilDone:YES];
}
- (void) gameOver2
{
NSString *title, *defaultButton, *alternateButton, *message;
SEL selector;
Result *result = [game result];
NSUInteger moves = [game moves];
[timer fire];
[timer invalidate];
timer = nil;
if ([result isEqual: [Result resultWithWin]])
{
title = NSLocalizedString(@"wonTitle", @"Won sheet title");
defaultButton = NSLocalizedString(@"wonDefaultButton", @"Won sheet default button");
alternateButton = NSLocalizedString(@"showHistoryButton", @"Show history button");
message = NSLocalizedString(@"wonText", @"Won sheet text");
selector = @selector(gameWonSheetDidEnd:returnCode:contextInfo:);
}
else if ([result isEqual: [Result resultWithLoss]])
{
title = NSLocalizedString(@"lostTitle", @"Lost sheet title");
defaultButton = NSLocalizedString(@"lostDefaultButton", @"Lost sheet default button");
alternateButton = NSLocalizedString(@"retryGameButton", @"Retry game button");
message = NSLocalizedString(@"lostText", @"Lost sheet text");
selector = @selector(gameLostSheetDidEnd:returnCode:contextInfo:);
}
else
{
return;
}
[self recordGame];
NSBeginAlertSheet(title, defaultButton, alternateButton,
NSLocalizedString(@"newGameButton", @"New game button"),
window, self, selector, NULL, NULL, message, moves);
}
@end