add Gem.sprite property
[exterlulz-kokogems.git] / src / GameController.m
blob9ecbc84cd0e304e861c6da0edc903501f0d9f460
1 /* ----====----====----====----====----====----====----====----====----====----
2 GameController.m (jeweltoy)
4 JewelToy is a simple game played against the clock.
5 Copyright (C) 2001  Giles Williams
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License
9 as published by the Free Software Foundation; either version 2
10 of the License, or (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 ----====----====----====----====----====----====----====----====----====---- */
22 #import "GameController.h"
23 #import "TimerView.h"
24 #import "Game.h"
25 #import "GameView.h"
26 #import "Gem.h"
28 @implementation GameController
30 @synthesize gameState = _gameState;
32 @dynamic crossHair1Position;
33 @dynamic crossHair2Position;
35 - (id) init
37     self = [super init];
38     
39     hiScores = [[NSUserDefaults standardUserDefaults] arrayForKey:@"hiScores"];
41     //NSLog(@"hiScores : %@",hiScores);
43     if ((!hiScores)||([hiScores count] < 8))
44     {
45         //NSLog(@"Creating High Score Tables");
46         hiScores = [self makeBlankHiScoresWith:hiScores];
47         [[NSUserDefaults standardUserDefaults] setObject:hiScores forKey:@"hiScores"];
48     }
49     [hiScores retain];
50     
51     noMoreMovesString = [[NSBundle mainBundle]
52                             localizedStringForKey:@"NoMoreMovesHTML"
53                             value:nil table:nil];
54     jeweltoyStartString = [[NSBundle mainBundle]
55                             localizedStringForKey:@"JewelToyStartHTML"
56                             value:nil table:nil];
57     gameOverString = [[NSBundle mainBundle]
58                             localizedStringForKey:@"GameOverHTML"
59                             value:nil table:nil];
60     titleImage = [NSImage imageNamed:@"title"];
61     gameLevel = 0;
62     gameNames = [hiScores objectAtIndex:0];
63     gameScores = [hiScores objectAtIndex:1];
64         
65     game = [[Game alloc] init];
66     animationTimerLock = [[NSLock alloc] init];
67     
68     gemMoveSize = GEM_GRAPHIC_SIZE;
69     gemMoveSpeed = GEM_MOVE_SPEED;
70     gemMoveSteps = gemMoveSize / gemMoveSpeed;
71         
72     useAlternateGraphics = [[NSUserDefaults standardUserDefaults] boolForKey:@"useAlternateGraphics"];
73     useImportedGraphics = [[NSUserDefaults standardUserDefaults] boolForKey:@"useImportedGraphics"];
74     
75     useCustomBackgrounds = [[NSUserDefaults standardUserDefaults] boolForKey:@"useCustomBackgrounds"];
76     customBackgroundFolderPath = [[NSUserDefaults standardUserDefaults] stringForKey:@"customBackgroundFolderPath"];
77     if (!customBackgroundFolderPath)
78         customBackgroundFolderPath = [[NSBundle mainBundle] localizedStringForKey:@"PicturesFolderPath"
79                                                                             value:nil table:nil];
80     return self;
83 - (void) dealloc
85     if (noMoreMovesString)      [noMoreMovesString release];
86     if (jeweltoyStartString)    [jeweltoyStartString release];
87     if (gameOverString) [gameOverString release];
88     if (game) [game release];
89     if (animationTimerLock) [animationTimerLock release];
90     if (timer)  [timer release];
91     if (hiScores)       [hiScores release];
92     [super dealloc];
95 - (void)awakeFromNib
97     [gameWindow setFrameAutosaveName:@"gameWindow"];
98     //useAlternateGraphics = [[NSUserDefaults standardUserDefaults] boolForKey:@"useAlternateGraphics"];
101 - (void)windowWillClose:(NSNotification *)aNotification
103     id obj = [aNotification object];
104     if (obj == aboutPanel)
105     {
106         //NSLog(@"Someone closed the 'About' window");
107         aboutPanel = nil;
108         return;
109     }
110     if (obj == prefsPanel)
111     {
112         //NSLog(@"Someone closed the 'Preferences' window");
113         useAlternateGraphics = [prefsAlternateGraphicsButton state];
114         [[NSUserDefaults standardUserDefaults]  setBool:useAlternateGraphics
115                                                 forKey:@"useAlternateGraphics"];
116         [[NSUserDefaults standardUserDefaults]  setBool:useImportedGraphics
117                                                 forKey:@"useImportedGraphics"];
119         useCustomBackgrounds = [prefsCustomBackgroundCheckbox state];
120         [[NSUserDefaults standardUserDefaults]  setBool:useCustomBackgrounds
121                                                 forKey:@"useCustomBackgrounds"];
122         [[NSUserDefaults standardUserDefaults]  removeObjectForKey:@"customBackgroundFolderPath"];
123         [[NSUserDefaults standardUserDefaults]  setObject:[prefsCustomBackgroundFolderTextField stringValue]
124                                                   forKey:@"customBackgroundFolderPath"];
125         if (gameView)
126         {
127             //[gameView loadImageArray];
128             [gameView graphicSetUp];
129             [gameView newBackground];
130             if (game)   [game setSpritesFrom:[gameView spriteArray]];
131             [gameView setNeedsDisplay:YES];
132         }
133         prefsPanel = nil;
134         return;
135     }
136     if (obj == gameWindow)
137     {
138         //NSLog(@"Someone closed the window - shutting down JewelToy");
139         [NSApp terminate:self];
140         return;
141     }
144 - (void)openPanelDidEnd:(NSOpenPanel *)sheet returnCode:(int)returnCode contextInfo:(void  *)contextInfo {
145   #pragma unused (returnCode, contextInfo)
146   [prefsCustomBackgroundFolderTextField setStringValue:[[sheet filenames] objectAtIndex:0]];
149 // TODO: move algorithm to its own method
150 - (IBAction)prefsGraphicDropAction
152     //
153     //  slice and dice importedImage, saving images to defaults
154     //
155     NSImage *importedImage = [prefsAlternateGraphicsImageView image];
156     if (importedImage)
157     {
158         int i = 0;
159         NSRect  cropRect = NSMakeRect(0.0,0.0,[importedImage size].width/7.0,[importedImage size].height);
160         NSRect  gemRect = NSMakeRect(0.0,0.0,48.0,48.0);
161         NSSize imageSize = NSMakeSize(48.0,48.0);
162         for (i = 0; i < 7; i++)
163         {
164             NSImage     *gemImage = [[NSImage alloc] initWithSize:imageSize];
165             NSString *key = [NSString stringWithFormat:@"tiffGemImage%d", i];
166             cropRect.origin.x = i * [importedImage size].width/7.0;
167             [gemImage lockFocus];
168             [[NSColor clearColor] set];
169             NSRectFill(gemRect);
170             [importedImage drawInRect:gemRect fromRect:cropRect operation:NSCompositeSourceOver fraction:1.0];
171             [gemImage unlockFocus];
172             [[NSUserDefaults standardUserDefaults]      setObject:[gemImage TIFFRepresentation] forKey:key];
173             if (i == 0) [iv1 setImage:gemImage];
174             if (i == 1) [iv2 setImage:gemImage];
175             if (i == 2) [iv3 setImage:gemImage];
176             if (i == 3) [iv4 setImage:gemImage];
177             if (i == 4) [iv5 setImage:gemImage];
178             if (i == 5) [iv6 setImage:gemImage];
179             if (i == 6) [iv7 setImage:gemImage];
180             [gemImage release];
181         }
182         useImportedGraphics = YES;
183     }
184         
187 - (IBAction)prefsCustomBackgroundCheckboxAction:(id)sender
189     //NSLog(@"prefsCustomBackgroundCheckboxAction");
191     if (sender!=prefsCustomBackgroundCheckbox)
192         return;
193     [prefsSelectFolderButton setEnabled:[prefsCustomBackgroundCheckbox state]];
194     [prefsCustomBackgroundFolderTextField setEnabled:[prefsCustomBackgroundCheckbox state]];
195     
198 - (IBAction)prefsSelectFolderButtonAction
200     NSOpenPanel *op=[NSOpenPanel openPanel];
202     //NSLog(@"prefsSelectFolderButtonAction");
203     [op setCanChooseDirectories:YES];
204     [op setCanChooseFiles:NO];
205     // get a sheet going to let the user pick a folder to scan for pictures
206     [op beginSheetForDirectory:[prefsCustomBackgroundFolderTextField stringValue] file:NULL types:NULL modalForWindow:prefsPanel modalDelegate:self didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:NULL];
209 - (BOOL) validateMenuItem: (NSMenuItem*) aMenuItem
211     if (aMenuItem == easyGameMenuItem)
212         return [easyGameButton isEnabled];
213     if (aMenuItem == hardGameMenuItem)
214         return [hardGameButton isEnabled];
215     if (aMenuItem == toughGameMenuItem)
216         return [toughGameButton isEnabled];
217     if (aMenuItem == freePlayMenuItem)
218         return [easyGameButton isEnabled];
219     if (aMenuItem == abortGameMenuItem)
220         return [abortGameButton isEnabled];
221     if (aMenuItem == pauseGameMenuItem)
222         return [pauseGameButton isEnabled];
223     //
224     // only allow viewing and reset of scores between games
225     //
226     if (aMenuItem == showHighScoresMenuItem)
227         return [easyGameButton isEnabled];
228     if (aMenuItem == resetHighScoresMenuItem)
229         return [easyGameButton isEnabled];
230     return YES;
233 - (IBAction)startNewGame:(id)sender
235     //NSLog(@"gameController.startNewGame messaged gameView:%@",gameView);
236     
237     [easyGameButton setEnabled:NO];
238     [hardGameButton setEnabled:NO];
239     [toughGameButton setEnabled:NO];
240     [abortGameButton setEnabled:YES];
241     [pauseGameButton setEnabled:YES];
243     abortGame = NO;
244     gameSpeed = 1.0;
245     gameLevel = 0;
246     
247     if ((sender == easyGameButton) ||
248         (sender == easyGameMenuItem)) {
249         //NSLog(@"debug - hiScores = %@\n...hiScores.count = %d",hiScores,[hiScores count]);
250         gameLevel = 0;
251         gameTime = 600.0; // ten minutes
252         [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
253                                             localizedStringForKey:@"EasyHighScoresHTML"
254                                             value:nil table:nil]];
255     }
256   // TODO: add else if?
257     if ((sender == hardGameButton) ||
258         (sender == hardGameMenuItem)) {
259         gameLevel = 1;
260         gameTime = 180.0; // three minutes
261         [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
262                                             localizedStringForKey:@"HardHighScoresHTML"
263                                             value:nil table:nil]];
264     }
265   // TODO: add else if?
266     if ((sender == toughGameButton) ||
267         (sender == toughGameMenuItem)) {
268         gameLevel = 2;
269         gameTime = 90.0; // one and a half minutes
270         [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
271                                             localizedStringForKey:@"ToughHighScoresHTML"
272                                             value:nil table:nil]];
273     }
274   
275     if (sender==freePlayMenuItem)
276     {
277         gameLevel = 3;
278         gameTime = 3600.0; // one hour FWIW
279         freePlay = YES;//       FREEPLAY
280         [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
281                                             localizedStringForKey:@"FreePlayHighScoresHTML"
282                                             value:nil table:nil]];
283     }
284     else {
285         freePlay = NO;//        FREEPLAY
286     }
287   
288     gameNames = [hiScores objectAtIndex:gameLevel*2];
289     gameScores = [hiScores objectAtIndex:gameLevel*2+1];
290     [game wholeNewGameWithSpritesFrom:[gameView spriteArray]];
292     [scoreTextField setStringValue:[NSString stringWithFormat:@"%d", game.score]];
293     [scoreTextField setNeedsDisplay:YES];
294     [bonusTextField setStringValue:[NSString stringWithFormat:@"x%d", game.bonusMultiplier]];
295     [bonusTextField setNeedsDisplay:YES];
296     
297     [game setMuted:muted];
298     [gameView setGame:game];
299     [gameView setLegend:nil];
300     [gameView setPaused:NO];
301     [gameView setMuted:muted];
302     [gameView setShowHint:!freePlay];//         FREEPLAY
303     
304     [timerView setTimerRunningEvery:0.5/gameSpeed
305                 decrement:(0.5/gameTime)
306                 withTarget:self
307                 whenRunOut:@selector(runOutOfTime)
308                 whenRunOver:@selector(bonusAwarded)];
309     
310     if (freePlay)
311     {
312         [timerView setDecrement:0.0];// FREEPLAY MW
313         [timerView setTimer:0.0];
314     }
315     
316     [timerView setPaused:YES];
317         
318     [gameView setLastMoveDate];
319     [self startAnimation:@selector(waitForFirstClick)];
322 - (IBAction)abortGame
324     [abortGameButton setEnabled:NO];
325     if (paused) [self togglePauseMode:self];
326     [pauseGameButton setEnabled:NO];
327     abortGame = YES;
328     [self waitForFirstClick];
331 - (IBAction)receiveHiScoreName
333     int         score = [hiScorePanelScoreTextField intValue];
334     NSString    *name = [hiScorePanelNameTextField stringValue];
336     [NSApp endSheet:hiScorePanel];
337     [hiScorePanel close];
338     
339     //NSLog(@"receiving HiScoreName:%@ %d",name,score);
340     
341     // reset arrays to gameLevel    
342     gameNames = [hiScores objectAtIndex:gameLevel*2];
343     gameScores = [hiScores objectAtIndex:gameLevel*2+1];
344     
345     for (int i = 0; i < 10; i++) {
346         if (score > [[gameScores objectAtIndex:i] intValue]) {
347             [gameScores insertObject:[NSNumber numberWithInt:score] atIndex:i];
348             [gameScores removeObjectAtIndex:10];
349           
350             [gameNames  insertObject:name atIndex:i];
351             [gameNames  removeObjectAtIndex:10];
352             break;
353         }
354     }
356     [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"hiScores"];     // or it won't work!?!
357     [[NSUserDefaults standardUserDefaults] setObject:hiScores forKey:@"hiScores"];
359     //NSLog(@"written high-scores to preferences");
360     
361     _gameState = GAMESTATE_GAMEOVER;
362     [gameView showHighScores:gameScores andNames:gameNames];
363     [gameView setLastMoveDate]; //reset timer so scores show for 20s    
366 - (IBAction)togglePauseMode:(id)sender
368   if (sender == pauseGameButton) {
369         paused = [pauseGameButton state];
370   }
371   else {
372         paused = !paused;
373   }
374     
375     [pauseGameButton setState:paused];
376     [timerView setPaused:paused];
377     if (paused)
378     {
379         [gameView setPaused:YES];
380         [gameView setHTMLLegend:[[NSBundle mainBundle]
381                             localizedStringForKey:@"PausedHTML"
382                             value:nil table:nil]];
383         [pauseGameMenuItem setTitle:[[NSBundle mainBundle]
384                             localizedStringForKey:@"ContinueGameMenuItemTitle"
385                             value:nil table:nil]];
386     }
387     else
388     {
389         [gameView setPaused:NO];
390         [gameView setLegend:nil];
391         [pauseGameMenuItem setTitle:[[NSBundle mainBundle]
392                             localizedStringForKey:@"PauseGameMenuItemTitle"
393                             value:nil table:nil]];
394     }
397 - (IBAction)toggleMute:(id)sender
399   if (sender == muteButton) {
400         muted = [muteButton state];
401   }
402   else {
403         muted = !muted;
404   }
405     
406     [muteButton setState:muted];
407     [gameView setMuted:muted];
408     [game setMuted:muted];
409     
410     if (muted)
411         [muteMenuItem setTitle:[[NSBundle mainBundle]
412                             localizedStringForKey:@"UnMuteGameMenuItemTitle"
413                             value:nil table:nil]];
414     else
415         [muteMenuItem setTitle:[[NSBundle mainBundle]
416                             localizedStringForKey:@"MuteGameMenuItemTitle"
417                             value:nil table:nil]];
418     
421 - (IBAction)orderFrontAboutPanel
423     //NSLog(@"GameController showAboutPanel called");
424   if (!aboutPanel) {
425         [NSBundle loadNibNamed:@"About" owner:self];
426   }
427     [aboutPanel setFrameAutosaveName:@"aboutPanel"];
428     [aboutPanel makeKeyAndOrderFront:self];
431 - (IBAction)orderFrontPreferencesPanel
433   if (!prefsPanel) {
434         [NSBundle loadNibNamed:@"Preferences" owner:self];
435   }
437     [prefsStandardGraphicsButton setState:!useAlternateGraphics];
438     [prefsAlternateGraphicsButton setState:useAlternateGraphics];
440     [prefsCustomBackgroundCheckbox setState:useCustomBackgrounds];
441     [prefsCustomBackgroundFolderTextField setStringValue:customBackgroundFolderPath];
442     [prefsSelectFolderButton setEnabled:[prefsCustomBackgroundCheckbox state]];
443     [prefsCustomBackgroundFolderTextField setEnabled:[prefsCustomBackgroundCheckbox state]];
444     
445     if ([[NSUserDefaults standardUserDefaults]  dataForKey:@"tiffGemImage0"])
446     {    // set up images!
447         for (int i = 0; i < 7; i++) {
448             NSString    *key = [NSString stringWithFormat:@"tiffGemImage%d", i];
449             NSData      *tiffData = [[NSUserDefaults standardUserDefaults]      dataForKey:key];
450             NSImage     *gemImage = [[NSImage alloc] initWithData:tiffData];
451             if (i == 0) [iv1 setImage:gemImage];
452             if (i == 1) [iv2 setImage:gemImage];
453             if (i == 2) [iv3 setImage:gemImage];
454             if (i == 3) [iv4 setImage:gemImage];
455             if (i == 4) [iv5 setImage:gemImage];
456             if (i == 5) [iv6 setImage:gemImage];
457             if (i == 6) [iv7 setImage:gemImage];
458             [gemImage release];
459         }
460     }
461     
462     [prefsPanel setFrameAutosaveName:@"prefsPanel"];
463     [prefsPanel makeKeyAndOrderFront:self];
466 - (IBAction)showHighScores
468     // rotate which scores to show
469     //
470     gameNames = [hiScores objectAtIndex:gameLevel*2];
471     gameScores = [hiScores objectAtIndex:gameLevel*2+1];
472     if (gameLevel==0)
473     [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
474                                             localizedStringForKey:@"EasyHighScoresHTML"
475                                             value:nil table:nil]];
476     else if (gameLevel==1)
477     [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
478                                             localizedStringForKey:@"HardHighScoresHTML"
479                                             value:nil table:nil]];
480     else if (gameLevel==2)
481     [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
482                                             localizedStringForKey:@"ToughHighScoresHTML"
483                                             value:nil table:nil]];
484     else if (gameLevel==3)
485     [gameView setHTMLHiScoreLegend:[[NSBundle mainBundle]
486                                             localizedStringForKey:@"FreePlayHighScoresHTML"
487                                             value:nil table:nil]];
488     gameLevel = (gameLevel +1)%4;
489     
490     [gameView showHighScores:gameScores andNames:gameNames];
491     [gameView setLastMoveDate]; //reset timer so scores show for 20s    
494 - (IBAction)resetHighScores
496     // don't rotate which scores to show
497     //
498     // blank the hi scores
499     //
500     [hiScores release];
501     hiScores = [[self makeBlankHiScoresWith:nil] retain];
502     [[NSUserDefaults standardUserDefaults] setObject:hiScores forKey:@"hiScores"];
503     
504     [self showHighScores];      //call the show scores routine    
507 - (NSArray *)makeBlankHiScoresWith:(NSArray *)oldScores
509     //int i,j;
510     int j;
511     NSMutableArray      *result = [NSMutableArray arrayWithCapacity:0];
512     
513     if (oldScores)      result = [NSMutableArray arrayWithArray:oldScores];
514     
515     //for (i = 0; i < 3; i++)
516     while ([result count] < 8)
517     {
518         NSMutableArray  *scores = [NSMutableArray arrayWithCapacity:0];
519         NSMutableArray  *names = [NSMutableArray arrayWithCapacity:0];
520         for (j = 0; j < 10; j++)
521         {
522             [scores addObject:[NSNumber numberWithInt:1000]];
523             [names addObject:[[NSBundle mainBundle]
524                                 localizedStringForKey:@"AnonymousName"
525                                 value:nil table:nil]];
526         }
527         [result addObject:names];
528         [result addObject:scores];
529     }
530     return [NSArray arrayWithArray:result];
533 - (void)runOutOfTime
535     _gameState = GAMESTATE_GAMEOVER;
536     [abortGameButton setEnabled:NO];
537     [pauseGameButton setEnabled:NO];
538     abortGame = YES;
539     [gameView setHTMLLegend:gameOverString];
540     [game shake];
541     [self startAnimation:@selector(waitForFirstClick)];
544 - (void)checkHiScores
546     int i;
547     // reset arrays with gameLevel
548     gameNames = [hiScores objectAtIndex:gameLevel*2];
549     gameScores = [hiScores objectAtIndex:gameLevel*2+1];
550     for (i = 0; i < 10; i++)
551     {
552         if (game.score > [[gameScores objectAtIndex:i] intValue])
553         {
554             [hiScorePanelScoreTextField
555                 setStringValue:[NSString stringWithFormat:@"%d", game.score]];
556             [NSApp      beginSheet:hiScorePanel
557                             modalForWindow:gameWindow
558                             modalDelegate:self
559                             didEndSelector:NULL
560                             contextInfo:NULL];
561             return;
562         }
563     }
564     [gameView showHighScores:gameScores andNames:gameNames];
567 - (void)bonusAwarded
570     [gameView newBackground];
572     if (!muted)         [[NSSound soundNamed:@"yes"] play];
574     if (!freePlay) {            // FREEPLAY MW
575         [game increaseBonusMultiplier];
576         [timerView decrementMeter:0.5];
577     } else {
578         [game increaseBonusMultiplier];
579         [timerView decrementMeter:1];
580     }
582     if (gameSpeed < SPEED_LIMIT)                // capping speed limit
583         gameSpeed = gameSpeed * 1.5;
584     //NSLog(@"...gamesSpeed %f",gameSpeed);
585     [timerView setTimerRunningEvery:0.5/gameSpeed
586                 decrement:(0.5/gameTime)
587                 withTarget:self
588                 whenRunOut:@selector(runOutOfTime)
589                 whenRunOver:@selector(bonusAwarded)];
590                 
591     if (freePlay)       [timerView setDecrement:0];//   FREEPLAY
594 - (void)startAnimation:(SEL)andThenSelector
596     [animationTimerLock lock];
597     //
598     if (!timer)
599         timer = [[NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL
600                                                   target:gameView
601                                                 selector:@selector(animate)
602                                                 userInfo:self
603                                                  repeats:YES] retain];
604     //
605     whatNext = andThenSelector;
606     //
607   gameView.animating = YES;
608     //
609     [animationTimerLock unlock];
612 - (void)animationEnded
614     //NSLog(@"gameController.animationEnded messaged");
615     
616     [animationTimerLock lock];
617     //
618   gameView.animating = NO;
619     //
620     [animationTimerLock unlock];
621     
622     if (whatNext)       [self performSelector:whatNext];
623         
624     [gameView setNeedsDisplay:YES];
627 - (void)waitForNewGame
629     [self checkHiScores];
630     
631     [game wholeNewGameWithSpritesFrom:[gameView spriteArray]];
632     [gameView setLegend:titleImage];
633     [easyGameButton setEnabled:YES];
634     [hardGameButton setEnabled:YES];
635     [toughGameButton setEnabled:YES];
636     [abortGameButton setEnabled:NO];
637     [pauseGameButton setEnabled:NO];
640 - (void)newBoard1
642     //NSLog(@"newBoard1");
643     [game erupt];
644     [self startAnimation:@selector(newBoard2)];
647 - (void)newBoard2
649     Gem *gem;
650     int i,j,r;
651     //NSLog(@"newBoard2");
652     for (i = 0; i < 8; i++)
653     {
654         for (j = 0; j < 8; j++)
655         {
656             gem = [game gemAt:i:j];
657             //NSLog(@"..gem..%@",gem);
658             r = rand() % 7;
659             [gem setGemType:r];
660             //[gem setImage:[[gameView imageArray] objectAtIndex:r]];
661           gem.sprite = [[gameView spriteArray] objectAtIndex:r];
662             [gem setPositionOnBoard:i:j];
663             [gem setPositionOnScreen:i*48:(i+j+8)*48];
664             [gem fall];
665         }
666     }
667     [gameView newBackground];
668     [gameView setLegend:nil];
669     [self startAnimation:@selector(testForThreesAgain)];
672 - (void)waitForFirstClick
674     //NSLog(@"waitForFirstClick");
675     /*- if (!freePlay)  MW CHANGE -*/   [timerView setPaused:NO];
676     if (abortGame)
677     {
678         [timerView setTimer:0.5];
679         _gameState = GAMESTATE_GAMEOVER;
680         [game explodeGameOver];
681         [self startAnimation:@selector(waitForNewGame)];
682         return;
683     }
684     if (![game boardHasMoves])
685     {
686         [timerView setPaused:YES];
687         [gameView setHTMLLegend:noMoreMovesString];
688         [game shake];
689         
690         if (freePlay)   [self startAnimation:@selector(runOutOfTime)];//        FREEPLAY
691         else            [self startAnimation:@selector(newBoard1)];//   FREEPLAY
692         
693         return;
694     }
695     _gameState = GAMESTATE_AWAITINGFIRSTCLICK;
698 - (void)receiveClickAt:(int)x:(int)y
700     if (paused) return;
701     if ((x < 0)||(x > 383)||(y < 0)||(y > 383)) return;
702     if (_gameState == GAMESTATE_AWAITINGFIRSTCLICK)
703     {
704         chx1 = floor(x / 48);
705         chy1 = floor(y / 48);
706         _gameState = GAMESTATE_AWAITINGSECONDCLICK;
707         [gameView setNeedsDisplay:YES];
708         return;
709     }
710     if (_gameState == GAMESTATE_AWAITINGSECONDCLICK)
711     {
712         chx2 = floor(x / 48);
713         chy2 = floor(y / 48);
714         if ((chx2 != chx1)^(chy2 != chy1))      // xor!
715         {
716             int d = (chx1-chx2)*(chx1-chx2)+(chy1-chy2)*(chy1-chy2);
717             //NSLog(@"square distance ==%d",d);
718             if (d==1)
719             {
720                 _gameState = GAMESTATE_FRACULATING;
721                 [gameView setNeedsDisplay:YES];
722                 [gameView setLastMoveDate];
723                 /*- MW CHANGE if (!freePlay) -*/ [timerView setPaused:YES];
724                 [self tryMoveSwapping:chx1:chy1 and:chx2:chy2];
725                 return;
726             }
727         }
728         // fall out of routine setting first click location
729         chx1 = floor(x / 48);
730         chy1 = floor(y / 48);
731         _gameState = GAMESTATE_AWAITINGSECONDCLICK;
732         [gameView setNeedsDisplay:YES];
733     }
736 - (void)tryMoveSwapping:(int)x1:(int)y1 and:(int)x2:(int)y2
738     // do stuff here!!!
739     int xx1, yy1, xx2, yy2;
740     //NSLog(@"tryMoveSwapping");
741     if (x1 != x2)
742     {
743         if (x1 < x2)    { xx1 = x1; xx2 = x2; }
744         else            { xx1 = x2; xx2 = x1; }
745         yy1 = y1;
746         yy2 = y2;
747     }
748     else
749     {
750         if (y1 < y2)    { yy1 = y1; yy2 = y2; }
751         else            { yy1 = y2; yy2 = y1; }
752         xx1 = x1;
753         xx2 = x2;
754     }
755     // store swap positions
756     chx1 = xx1; chy1 = yy1; chx2 = xx2; chy2 = yy2;
757     // swap positions
758     if (chx1 < chx2)    // swapping horizontally
759     {
760         [[game gemAt:chx1:chy1] setVelocity:gemMoveSpeed:0:gemMoveSteps];
761         [[game gemAt:chx2:chy2] setVelocity:-gemMoveSpeed:0:gemMoveSteps];
762     }
763     else                // swapping vertically
764     {
765         [[game gemAt:chx1:chy1] setVelocity:0:gemMoveSpeed:gemMoveSteps];
766         [[game gemAt:chx2:chy2] setVelocity:0:-gemMoveSpeed:gemMoveSteps];
767     }
768     [game swap:chx1:chy1 and:chx2:chy2];
769     _gameState = GAMESTATE_SWAPPING;
770     [self startAnimation:@selector(testForThrees)];
773     // test for threes
774 - (void)testForThrees
776     BOOL anyThrees;
777     int oldScore = game.score;
778     //NSLog(@"testForThrees");
779     anyThrees = ([game testForThreeAt:chx1:chy1])|([game testForThreeAt:chx2:chy2]);
780     [scoreTextField setStringValue:[NSString stringWithFormat:@"%d", game.score]];
781     [scoreTextField setNeedsDisplay:YES];
782     [bonusTextField setStringValue:[NSString stringWithFormat:@"x%d", game.bonusMultiplier]];
783     [bonusTextField setNeedsDisplay:YES];
784     if (game.score > oldScore) [timerView incrementMeter:[game collectFadedGems]/GEMS_FOR_BONUS];
785     if (anyThrees)
786         [self startAnimation:@selector(removeThreesAndReplaceGems)];    // fade gems
787     else
788         [self unSwap];
789 }    
791     //// repeat:        remove threes
792 - (void)removeThreesAndReplaceGems
794     
795     //NSLog(@"removeThreesAndReplaceGems");
796     // deal with fading
797     [game removeFadedGemsAndReorganiseWithSpritesFrom:[gameView spriteArray]];
798     
799     [self startAnimation:@selector(testForThreesAgain)];        // gems fall down
800 }    
802 - (void)testForThreesAgain
804   int oldScore = game.score;
805   BOOL anyThrees = [game checkBoardForThrees];
806   
807   [scoreTextField setStringValue:[NSString stringWithFormat:@"%d", game.score]];
808   [scoreTextField setNeedsDisplay:YES];
809   
810   [bonusTextField setStringValue:[NSString stringWithFormat:@"x%d", game.bonusMultiplier]];
811   [bonusTextField setNeedsDisplay:YES];
812   
813   if (game.score > oldScore) {
814     [timerView incrementMeter:[game collectFadedGems]/GEMS_FOR_BONUS];
815   }
816   if (anyThrees) {
817     [self startAnimation:@selector(removeThreesAndReplaceGems)];        // fade gems
818   }
819   else {
820     [self waitForFirstClick];
821   }
822 }   
823 ////            allow gems to fall
824     ////                test for threes
825     //// until there are no threes
827 - (void)unSwap
829     //NSLog(@"unSwap");
830     
831     if (!muted) [[NSSound soundNamed:@"no"] play];
832     
833     // swap positions
834     if (chx1 < chx2)    // swapping horizontally
835     {
836         [[game gemAt:chx1:chy1] setVelocity:4:0:12];
837         [[game gemAt:chx2:chy2] setVelocity:-4:0:12];
838     }
839     else                // swapping vertically
840     {
841         [[game gemAt:chx1:chy1] setVelocity:0:4:12];
842         [[game gemAt:chx2:chy2] setVelocity:0:-4:12];
843     }
844     [game swap:chx1:chy1 and:chx2:chy2];
845     _gameState = GAMESTATE_SWAPPING;
846     [self startAnimation:@selector(waitForFirstClick)];
847 }    
849 - (BOOL)gameIsPaused {
850   return paused;
853 - (BOOL)useCustomBackgrounds {
854   return useCustomBackgrounds;
857 - (NSPoint)crossHair1Position {
858   return NSMakePoint(chx1 * 48,chy1 * 48);
861 - (NSPoint)crossHair2Position {
862   return NSMakePoint(chx2 * 48,chy2 * 48);
865 @end