File: main.c

package info (click to toggle)
xboing 2.4-26.1
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,108 kB
  • ctags: 1,516
  • sloc: ansic: 17,999; sh: 51; makefile: 44
file content (1517 lines) | stat: -rw-r--r-- 35,031 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
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
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
/*
 * XBoing - An X11 blockout style computer game
 *
 * (c) Copyright 1993, 1994, 1995, Justin C. Kibell, All Rights Reserved
 *
 * The X Consortium, and any party obtaining a copy of these files from
 * the X Consortium, directly or indirectly, is granted, free of charge, a
 * full and unrestricted irrevocable, world-wide, paid up, royalty-free,
 * nonexclusive right and license to deal in this software and
 * documentation files (the "Software"), including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons who receive
 * copies from any such party to do so.  This license includes without
 * limitation a license to do the foregoing actions under any patents of
 * the party supplying this software to the X Consortium.
 *
 * In no event shall the author be liable to any party for direct, indirect,
 * special, incidental, or consequential damages arising out of the use of
 * this software and its documentation, even if the author has been advised
 * of the possibility of such damage.
 *
 * The author specifically disclaims any warranties, including, but not limited
 * to, the implied warranties of merchantability and fitness for a particular
 * purpose.  The software provided hereunder is on an "AS IS" basis, and the
 * author has no obligation to provide maintenance, support, updates,
 * enhancements, or modifications.
 */

/* 
 * =========================================================================
 *
 * $Id: main.c,v 1.1.1.1 1994/12/16 01:36:47 jck Exp $
 * $Source: /usr5/legends/jck/xb/master/xboing/main.c,v $
 * $Revision: 1.1.1.1 $
 * $Date: 1994/12/16 01:36:47 $
 *
 * $Log: main.c,v $
 * Revision 1.1.1.1  1994/12/16  01:36:47  jck
 * The XBoing distribution requires configuration management. This is why the
 * cvs utility is being used. This is the initial import of all source etc..
 *
 *
 * =========================================================================
 */

/*
 *  Include file dependencies:
 */

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/keysym.h>

#include "score.h"
#include "presents.h"
#include "editor.h"
#include "special.h"
#include "audio.h"
#include "mess.h"
#include "ball.h"
#include "file.h"
#include "gun.h"
#include "demo.h"
#include "sfx.h"
#include "init.h"
#include "blocks.h"
#include "misc.h"
#include "level.h"
#include "bonus.h"
#include "stage.h"
#include "paddle.h"
#include "intro.h"
#include "inst.h"
#include "highscore.h"
#include "keys.h"
#include "keysedit.h"
#include "preview.h"
#include "dialogue.h"
#include "error.h"
#include "eyedude.h"

#include "main.h"

/*
 *  Internal macro definitions:
 */

/*
 *  Internal type declarations:
 */

#if NeedFunctionPrototypes
static KeySym 	GetKeySym(XEvent event);
static void 	handleGameMode(Display *display);
static void 	handleEventLoop(Display *display);
static void 	ToggleGamePaused(Display *display);
static void 	SetGamePaused(Display *display);
static void 	handleGameStates(Display *display);
static void 	handleMiscKeys(Display *display, KeySym keysym);
static void 	handleSpeedKeys(Display *display, KeySym keysym);
static void 	handleExitKeys(Display *display);
static void 	handleQuitKeys(Display *display);
#else
static void 	handleQuitKeys();
static void 	handleExitKeys();
static void 	handleSpeedKeys();
static void 	handleMiscKeys();
static void 	handleGameStates();
static KeySym 	GetKeySym();
static void 	handleGameMode();
static void 	handleEventLoop();
static void 	ToggleGamePaused();
static void 	SetGamePaused();
#endif

/*
 *  Internal variable declarations:
 */

int 			paddleMotion = 0;
int 			paddleDx = 0;
int 			speedLevel = 5;
int 			frame, gameActive;
int 			mode, oldMode;
static int 		iconified = False;
long 			speed;
static int 		userDelay = 1;
static int 		paddleControl;
static time_t 	pauseStartTime;
time_t 			pausedTime;
int 			UserTilts;


#if NeedFunctionPrototypes
int GetWarpSpeed(void)
#else
int GetWarpSpeed()
#endif
{
	/* Return warp speed in user terms */
	return (speedLevel);
}

#if NeedFunctionPrototypes
void SetUserSpeed(int delay)
#else
void SetUserSpeed(delay)
	int delay;
#endif
{
	long temp;

	/* Set an entire game speedup or slowdown speed */
	temp = (speed / (long) userDelay);
	userDelay = delay;
	speed = (long) (temp * userDelay);
	speedLevel = 10 - delay;
}

#if NeedFunctionPrototypes
int GetPaddleControlMode(void)
#else
int GetPaddleControlMode()
#endif
{
	/* Get the paddle control mode */
	return paddleControl;
}

#if NeedFunctionPrototypes
void SetPaddleControlMode(int type)
#else
void SetPaddleControlMode(type)
	int type;
#endif
{
	/* Set the paddle control mode to the new mode */
	paddleControl = type;
}

#if NeedFunctionPrototypes
void SetGameSpeed(int delay)
#else
void SetGameSpeed(delay)
	int delay;
#endif
{
	/* This is the speed used in the sleeping routine */
	if (delay >= 0)
		speed = (long) (delay * userDelay);
}

#if NeedFunctionPrototypes
static KeySym GetKeySym(XEvent event)
#else
static KeySym GetKeySym(event)
	XEvent event;
#endif
{
	int count;
	char key;
	KeySym keysym;
	XComposeStatus compose;

	/* Lookup a keysym using the event key */
	count = XLookupString(&event.xkey, &key, 1, &keysym, &compose);

	return keysym;
}

#if NeedFunctionPrototypes
int paddleIsMoving(void)
#else
int paddleIsMoving()
#endif
{
	/* Returns direction of paddle 1 right -1 left 0 stopped */
	return paddleMotion;
}

#if NeedFunctionPrototypes
void handlePaddleMoving(Display *display)
#else
void handlePaddleMoving(display)
	Display *display;
#endif
{
	static oldx = 0;
	int x, y;

	if (paddleControl == CONTROL_KEYS)
	{
		switch (paddleMotion)
		{
			case 1:		/* Move the paddle to the right 1 increment */
				MovePaddle(display, playWindow, 
					PADDLE_RIGHT, currentPaddleSize, 0);
				break;

			case -1:		/* Move the paddle to the left 1 increment */
				MovePaddle(display, playWindow, 
					PADDLE_LEFT, currentPaddleSize, 0);
				break;

			default:
				break;
		}
	} else if (paddleControl == CONTROL_MOUSE)
	{
		if (ObtainMousePosition(display, playWindow, &x, &y))
		{
			/* Has the pointer moved since our last poll */
			if (x != oldx)
			{
				paddleDx = x - oldx;
	
				/* Move the paddle to the position of the mouse pointer */
				MovePaddle(display, playWindow, 
					PADDLE_NONE, currentPaddleSize, x);
				oldx = x;
	
				/* Adjust the paddle motion variable so the ball moves when in
				 * the BALL_READY state and BALL_CREATE state.
				 */
				if (x > oldx)
					paddleMotion = 1;
				else
					paddleMotion = -1;
			}
			else
			{
				/* Reset to no motion */
				paddleMotion = 0;
				paddleDx = 0;
			}
		}
	}
}


#if NeedFunctionPrototypes
static void ToggleGamePaused(Display *display)
#else
static void ToggleGamePaused(display)
	Display *display;
#endif
{
	if (mode == MODE_PAUSE)
	{
		/* Finished pause resume game */
		mode = MODE_GAME;
		SetCurrentMessage(display, messWindow, "- Play ball -", False);
		
		/* How many seconds were we paused for? */
		pausedTime += (time(NULL) - pauseStartTime);

 		XSelectInput(display, mainWindow, 
			KeyPressMask | KeyReleaseMask | ButtonPressMask |
   			ButtonReleaseMask | ButtonMotionMask | ExposureMask | 
			StructureNotifyMask | PointerMotionHintMask);

 		GrabPointer(display, mainWindow);
	}
	else 
		SetGamePaused(display);
}

#if NeedFunctionPrototypes
static void SetGamePaused(Display *display)
#else
static void SetGamePaused(display)
	Display *display;
#endif
{
	if (mode == MODE_GAME)
	{
		/* Set game to paused mode */
		mode = MODE_PAUSE;
		SetCurrentMessage(display, messWindow, 
			"- Game paused -", False);
		
		/* we need to keep track of how long we were paused so that later
		 * in the highscore thing I can take that off the time.
		 */
		pauseStartTime = time(NULL);

		XSelectInput(display, mainWindow, 
			KeyPressMask | ExposureMask | StructureNotifyMask);

		UnGrabPointer(display);
	}
}

#if NeedFunctionPrototypes
void handleIconify(Display *display)
#else
void handleIconify(display)
	Display *display;
#endif
{
	ToggleGamePaused(display);
}

#if NeedFunctionPrototypes
void SelectiveRedraw(Display *display)
#else
void SelectiveRedraw(display)
	Display *display;
#endif
{
	switch (mode)
	{
		case MODE_GAME:
		case MODE_PAUSE:
			RedrawPlayWindow(display, playWindow);
			break;

		case MODE_EDIT:
			RedrawEditor(display, playWindow);
			break;

		case MODE_INTRO:
			RedrawIntroduction(display, playWindow);
			break;

		case MODE_DEMO:
			RedrawDemonstration(display, playWindow);
			break;

		case MODE_PREVIEW:
			RedrawPreviewLevel(display, playWindow);
			break;

		case MODE_INSTRUCT:
			RedrawInstructions(display, playWindow);
			break;

		case MODE_KEYS:
			RedrawKeys(display, playWindow);
			break;

		case MODE_KEYSEDIT:
			RedrawKeysEdit(display, playWindow);
			break;

		case MODE_BONUS:
			RedrawBonus(display, mainWindow);
			break;

		case MODE_HIGHSCORE:
			RedrawHighScore(display, playWindow);
			break;

		default:
			break;
	}

	/* Redisplay the message and the level/score info */
	RedrawLevelInfo(display, levelWindow);
	DisplayCurrentMessage(display, messWindow);

	/* To be sure - to be sure */
	XFlush(display);
}

#if NeedFunctionPrototypes
void handleExposure(Display *display, XEvent event)
#else
void handleExposure(display, event)
	Display *display;
	XEvent event;
#endif
{
	/* Only redraw window once so wait until all expose events have sent
	 * and then redraw all that we need to redraw based on current game
	 * mode.
	 */
	if (event.xexpose.count == 0)
		SelectiveRedraw(display);
}

#if NeedFunctionPrototypes
void handleMouseButtons(Display *display, XEvent event, int Down)
#else
void handleMouseButtons(display, event, Down)
	Display *display;
	XEvent event;
	int Down;
#endif
{
	if (mode == MODE_EDIT)
	{
		/* Allow the editor window to have control over buttons */
		HandleEditorMouseButtons(display, event, Down);
		return;
	}
	
	if (Down == True)
	{
		/* Button pressed down */
		switch(event.xbutton.button)
		{
			/* Shoot a bullet on all buttons */
			case Button1:
			case Button2: 
			case Button3:
				/* If we are playing the game and a ball needs to be started
				 * then start it otherwise shoot a bullet.
				 */
				if (mode == MODE_GAME)
					if (ActivateWaitingBall(display, playWindow) == False)
						shootBullet(display, playWindow);
				break;
		}
	}
}

#if NeedFunctionPrototypes
static void handleControlKeys(Display *display)
#else
static void handleControlKeys(display)
	Display *display;
#endif
{
	/* Toggle game mode */
	if (GetPaddleControlMode() == CONTROL_KEYS)
	{
		SetCurrentMessage(display, messWindow, 
			"Control: Mouse", True);
		SetPaddleControlMode(CONTROL_MOUSE);
	}
	else
	{
		SetCurrentMessage(display, messWindow, 
			"Control: Keys", True);
		SetPaddleControlMode(CONTROL_KEYS);
	}

	/* Play a bit of sound */
	if (noSound == False)
		playSoundFile("toggle", 50);
}

#if NeedFunctionPrototypes
static void handleSoundKey(Display *display)
#else
static void handleSoundKey(display)
	Display *display;
#endif
{
	if (noSound == False)
	{
		/* Try and turn audio off */
		FreeAudioSystem();

		noSound = True;
		SetCurrentMessage(display, messWindow, 
			"- Audio OFF -", True);
	}
	else
	{
		/* Try and turn audio on */
		if (SetUpAudioSystem(display) == False)
		{
			/* Unable to turn audio on */
			noSound = True;
			SetCurrentMessage(display, messWindow, 
				"- Audio unavailable -", True);
		}
		else
		{
			/* Audio is now active */
			noSound = False;
			SetCurrentMessage(display, messWindow, 
				"- Audio ON -", True);
		}
	}
}

#if NeedFunctionPrototypes
void SetTiltsZero(void)
#else
void SetTiltsZero()
#endif
{
	/* Initialise the user tilt variable to zero tilts */
	UserTilts = 0;
}

#if NeedFunctionPrototypes
static void handleGameKeys(Display *display, KeySym keysym)
#else
static void handleGameKeys(display, keysym)
	Display *display;
	KeySym keysym;
#endif
{
	int temp;
	char astr[80];

	/* Switch on the keysym */
	switch (keysym)
	{
		case XK_z: case XK_Z:
			if (saving == True)
				SaveCurrentGame(display, playWindow);
			else
				SetCurrentMessage(display, messWindow, "Not available yet!", 
					True);
			break;

		case XK_X: case XK_x:
			LoadSavedGame(display, playWindow);
			break;

		case XK_t:	case XK_T:	
			/* Obtain an active ball and tilt it */
			if ((temp = GetAnActiveBall()) >= 0)
			{
				/* Check that the user is tilt happy */
				if (UserTilts < MAX_TILTS)
				{
					/* Bump the ball please */
					DoBoardTilt(display, temp);
					UserTilts++;

					sprintf(astr, "You have %d %s left!", 
						MAX_TILTS - UserTilts, 
						(MAX_TILTS - UserTilts) == 1 ? "tilt" : "tilts");
					SetCurrentMessage(display, messWindow, 
						astr, True);
				}
				else
				{
					/* All tilts used up for this level. */
					SetCurrentMessage(display, messWindow, 
						"Maximum tilts reached!", True);
				}
			}
			break;

		case XK_d:	case XK_D:	
			/* Obtain an active ball - ie: not on paddle */
			if ((temp = GetAnActiveBall()) >= 0)
			{
				/* Erase and reset ball to new one */
				ClearBallNow(display, playWindow, temp);
			}
			break;

		case XK_Left: case XK_j: case XK_J:
			/* Set paddle to move left */
			paddleMotion = -1;
			break;

		case XK_k: case XK_K:
			/* Shoot a bullet if available */
			if (ActivateWaitingBall(display, playWindow) == False)
				shootBullet(display, playWindow);
			break;

		case XK_Right: case XK_l: case XK_L:
			/* Set paddle to move right */
			paddleMotion = 1;
			break;

		case XK_Escape:
			if (YesNoDialogue(display, "Abort current game? [y/n]"))
				handleQuitKeys(display);
			break;

      	case XK_equal:
			if (debug == True)
			{
				/* Special cheat key for debugging mode */
            	SkipToNextLevel(display, playWindow);
            	SetCurrentMessage(display, messWindow,
            		"Cheating, skip level ...", True);
			}
			else
			{
            	SetCurrentMessage(display, messWindow,
            		"Stop trying to cheat!!", True);
			}
            break;

		case XK_p: case XK_P:
			ToggleGamePaused(display);
			break;

		default: 	/* All other keys */
			handleMiscKeys(display, keysym);
	}
}

#if NeedFunctionPrototypes
static void handleIntroKeys(Display *display, KeySym keysym)
#else
static void handleIntroKeys(display, keysym)
	Display *display;
	KeySym keysym;
#endif
{
	/* Switch on the keysym */
	switch (keysym)
	{
		case XK_space:
			if (mode == MODE_INTRO || mode == MODE_HIGHSCORE 
			  || mode == MODE_INSTRUCT || mode == MODE_KEYS || 
			  mode == MODE_KEYSEDIT || mode == MODE_DEMO || 
			  mode == MODE_PREVIEW)
			{
				ResetBorderGlow(display, playWindow);
				SetGameSpeed(FAST_SPEED);
				gameActive = False;
				mode = MODE_GAME;
			}

			if (mode == MODE_BONUS)
				SetBonusWait(BONUS_FINISH, frame);
			break;

		case XK_c: case XK_C:
			/* Cycle through the introduction screens if note in a game */
			if (mode == MODE_INTRO)
			{
				/* Ok - Goto the instructions mode */
				SetGameSpeed(FAST_SPEED);
				ResetInstructions();
				mode = MODE_INSTRUCT;
			} else if (mode == MODE_INSTRUCT)
			{
				/* Ok - Goto the demo mode */
				SetGameSpeed(FAST_SPEED);
				ResetDemonstration();
				mode = MODE_DEMO;
			} else if (mode == MODE_DEMO)
			{
				/* Ok - Goto the keys mode */
				SetGameSpeed(FAST_SPEED);
				ResetKeys();
				mode = MODE_KEYS;
			} else if (mode == MODE_KEYS)
			{
				/* Ok - Goto the keysedit mode */
				SetGameSpeed(FAST_SPEED);
				ResetKeysEdit();
				mode = MODE_KEYSEDIT;
			} else if (mode == MODE_KEYSEDIT)
			{
				/* Ok - Goto the highscore mode */
				SetGameSpeed(FAST_SPEED);
				ResetHighScore(GLOBAL);
				mode = MODE_HIGHSCORE;
			} else if (mode == MODE_HIGHSCORE)
			{
				/* Ok - Goto to the preview mode */
				SetGameSpeed(FAST_SPEED);
				ResetPreviewLevel();
				mode = MODE_PREVIEW;
			} else if (mode == MODE_PREVIEW)
			{
				/* Ok - Goto back to the intro mode */
				SetGameSpeed(FAST_SPEED);
				ResetIntroduction();
				mode = MODE_INTRO;
			} 
			break;

		case XK_H:	/* Personal highscores */
			if (mode == MODE_INTRO || mode == MODE_INSTRUCT 
				|| mode == MODE_KEYS || mode == MODE_HIGHSCORE 
				|| mode == MODE_DEMO || mode == MODE_PREVIEW ||
				mode == MODE_KEYSEDIT)
			{
				/* Display the high scores thanks */
				SetGameSpeed(FAST_SPEED);
				ResetHighScore(PERSONAL);
				mode = MODE_HIGHSCORE;

				/* Play a bit of sound */
				if (noSound == False)
					playSoundFile("toggle", 50);
				
			}
			break;

		case XK_h:	/* Global highscores */
			if (mode == MODE_INTRO || mode == MODE_INSTRUCT 
				|| mode == MODE_KEYS || mode == MODE_HIGHSCORE
				|| mode == MODE_DEMO || mode == MODE_PREVIEW ||
				mode == MODE_KEYSEDIT)
			{
				SetGameSpeed(FAST_SPEED);
				ResetHighScore(GLOBAL);
				mode = MODE_HIGHSCORE;

				/* Play a bit of sound */
				if (noSound == False)
					playSoundFile("toggle", 50);
			}
			break;

		case XK_s: case XK_S:
			if (mode == MODE_INTRO || mode == MODE_INSTRUCT 
				|| mode == MODE_KEYS || mode == MODE_HIGHSCORE
				|| mode == MODE_DEMO || mode == MODE_PREVIEW ||
				mode == MODE_KEYSEDIT)
			{
				/* toggle the special effects system */
				if (getSpecialEffects(display) == True)
				{
					/* Turn off special effects */
					useSpecialEffects(False);

					SetCurrentMessage(display, messWindow, 
						"- SFX OFF -", True);
				}
				else
				{
					/* Cannot use sfx on this display */
					if (getSpecialEffects(display) == -1)
					{
						SetCurrentMessage(display, messWindow, 
							"- SFX Unavailable -", True);
					}
					else
					{
						/* Try and turn on special effects */
						useSpecialEffects(True);

						SetCurrentMessage(display, messWindow, 
							"- SFX ON -", True);
					}
				}
			}
			break;

		case XK_w: case XK_W:
			ChangeStartingLevel(display);
			break;

		case XK_e: case XK_E:
			/* Change to editor mode */
			ResetEditor();
			mode = MODE_EDIT;
			break;

		default: 	/* All other keys */
			handleMiscKeys(display, keysym);
			handleSpeedKeys(display, keysym);
			break;
	}
}

#if NeedFunctionPrototypes
static void handleQuitKeys(Display *display)
#else
static void handleQuitKeys(display)
	Display *display;
#endif
{
	/* Save out the scores if you were playing */
	if (oldMode == MODE_GAME || oldMode == MODE_BONUS)
	{
		/* Save out scores when quitting */
		UpdateHighScores(display);
	}

	/* Abort game and return to intros */
	SetGameSpeed(FAST_SPEED);
	ResetIntroduction();
	mode = MODE_INTRO;
}

#if NeedFunctionPrototypes
static void handleExitKeys(Display *display)
#else
static void handleExitKeys(display)
	Display *display;
#endif
{
	/* Save out the scores if you were playing */
	if (oldMode == MODE_GAME || oldMode == MODE_BONUS)
	{
		/* Save out scores when quitting */
		UpdateHighScores(display);
	}

	if (noSound == False) playSoundFile("game_over", 100);

	/* Shut down and exit game */
	ShutDown(display, 0, "Thank you for playing XBoing.");
}

#if NeedFunctionPrototypes
static void handlePresentsKeys(Display *display, KeySym keysym)
#else
static void handlePresentsKeys(display, keysym)
	Display *display;
	KeySym keysym;
#endif
{
	/* Switch on the keysym */
	switch (keysym)
	{
		case XK_space:
			QuickFinish(display, mainWindow);
			break;

		case XK_Q: case XK_q:
			/* Shut down and exit game */
			ShutDown(display, 0, "Thank you for playing XBoing.");
			break;

		default:
			break;
	}
}

#if NeedFunctionPrototypes
static void handleSpeedKeys(Display *display, KeySym keysym)
#else
static void handleSpeedKeys(display, keysym)
	Display *display;
	KeySym keysym;
#endif
{
	/* Switch on the keysym */
	switch (keysym)
	{
		case XK_1:	/* Set speed to speed 1 */
			SetUserSpeed(9);
			SetCurrentMessage(display, messWindow, "Warp 1 - Slow", True);
			if (noSound == False) playSoundFile("tone", 10);
			break;

		case XK_2:	/* Set speed to speed 2 */
			SetUserSpeed(8);
			SetCurrentMessage(display, messWindow, "Warp 2", True);
			if (noSound == False) playSoundFile("tone", 20);
			break;

		case XK_3:	/* Set speed to speed 3 */
			SetUserSpeed(7);
			SetCurrentMessage(display, messWindow, "Warp 3", True);
			if (noSound == False) playSoundFile("tone", 30);
			break;

		case XK_4:	/* Set speed to speed 4 */
			SetUserSpeed(6);
			SetCurrentMessage(display, messWindow, "Warp 4", True);
			if (noSound == False) playSoundFile("tone", 40);
			break;

		case XK_5:	/* Set speed to speed 5 */
			SetUserSpeed(5);
			SetCurrentMessage(display, messWindow, "Warp 5 - Medium", True);
			if (noSound == False) playSoundFile("tone", 50);
			break;

		case XK_6:	/* Set speed to speed 6 */
			SetUserSpeed(4);
			SetCurrentMessage(display, messWindow, "Warp 6", True);
			if (noSound == False) playSoundFile("tone", 60);
			break;

		case XK_7:	/* Set speed to speed 7 */
			SetUserSpeed(3);
			SetCurrentMessage(display, messWindow, "Warp 7", True);
			if (noSound == False) playSoundFile("tone", 70);
			break;

		case XK_8:	/* Set speed to speed 8 */
			SetUserSpeed(2);
			SetCurrentMessage(display, messWindow, "Warp 8", True);
			if (noSound == False) playSoundFile("tone", 80);
			break;

		case XK_9:	/* Set speed to speed 9 */
			SetUserSpeed(1);
			SetCurrentMessage(display, messWindow, "Warp 9 - Fast", True);
			if (noSound == False) playSoundFile("tone", 90);
			break;

		default: 	/* All other keys */
			break;
	}
}

#if NeedFunctionPrototypes
static void handleMiscKeys(Display *display, KeySym keysym)
#else
static void handleMiscKeys(display, keysym)
	Display *display;
	KeySym keysym;
#endif
{
	int vol = 0;
	char str[30];

	/* Switch on the keysym */
	switch (keysym)
	{
		case XK_plus: case XK_KP_Add:
			if (noSound == False)
			{
				vol = GetMaximumVolume();
				if (vol < 100)
					vol++;
				SetMaximumVolume(vol);
				sprintf(str, "Maximum volume: %d%%", vol);
				SetCurrentMessage(display, messWindow, str, True);
			}
			break;

		case XK_minus: case XK_KP_Subtract:
			if (noSound == False)
			{
				vol = GetMaximumVolume();
				if (vol > 0)
					vol--;
				SetMaximumVolume(vol);
				sprintf(str, "Maximum volume: %d%%", vol);
				SetCurrentMessage(display, messWindow, str, True);
			}
			break;

		case XK_a: case XK_A:
			handleSoundKey(display);
			break;

		case XK_i: case XK_I:
			/* Iconify the window quickly - main loop handles events */
			XIconifyWindow(display, mainWindow, 0);
			break;

		case XK_g: case XK_G:
			handleControlKeys(display);
			break;

		case XK_Q: case XK_q:
			if (YesNoDialogue(display, "Exit XBoing you wimp? [y/n]"))
				handleExitKeys(display);
			break;

		default: 	/* All other keys */
			break;
	}
}

#if NeedFunctionPrototypes
void handleKeyPress(Display *display, KeySym keysym, XEvent event, int Pressed)
#else
void handleKeyPress(display, keysym, event, Pressed)
	Display *display;
	KeySym keysym;
	XEvent event;
	int Pressed;
#endif
{

	if (Pressed == False)
	{
		/* key was released */
		paddleMotion = 0;
	}
	else
	{
		/* Switch on the game mode */
		switch (mode)
		{
			case MODE_DIALOGUE:
				break;

			case MODE_WAIT: case MODE_BALL_WAIT:
			case MODE_PAUSE: case MODE_GAME:
				handleGameKeys(display, keysym);
				break;

			case MODE_HIGHSCORE: case MODE_BONUS: case MODE_INTRO:
			case MODE_INSTRUCT: case MODE_DEMO: case MODE_PREVIEW:
			case MODE_KEYS: case MODE_KEYSEDIT:
				handleIntroKeys(display, keysym);
				break;

			case MODE_PRESENTS:
				handlePresentsKeys(display, keysym);
				break;

			case MODE_EDIT:
				handleEditorKeys(display, keysym);
				break;

			case MODE_NONE:
				break;
		}
	}
}


#if NeedFunctionPrototypes
static void handleGameMode(Display *display)
#else
static void handleGameMode(display)
	Display *display;
#endif
{
	static int bonusRow = 0;
	static int bonusCol = 0;
	static int nextBonusFrame = 0;

	/* If we are going to play then setup first level */
	if (gameActive == False)
	{
		/* Choose a random velocity for the ball */

		/* Always start at level 1 or level specified */
		SetLevelNumber(GetStartingLevel());

		/* Set some important variables */
		/* PLEASE CHANGE SETUP IN EDITOR.C IF YOU CHANGE STUFF HERE */
		SetLivesLeft(3);
		ToggleSaving(display, False);
		SetTheScore(0L);
		nextBonusFrame 		= 0;
		currentPaddleSize 	= PADDLE_HUGE;
		pausedTime			= 0;
		bonusBlock 			= False;
		UserTilts			= 0;

		/* Setup the stage and load 1st level */
		SetupStage(display, playWindow);

		/* Start game play */
		gameActive = True;

		/* Keep track of the game duration - shown in highscores */
		gameTime = time(NULL);
	}

	/* If we need to move the paddle then do so */
	if ((frame % PADDLE_ANIMATE_DELAY) == 0)
		handlePaddleMoving(display);

	if (mode == MODE_GAME)
	{
		HandleBallMode(display, playWindow);

		/* Add bonus coin block at random intervals */
		if (nextBonusFrame == 0 && bonusBlock == False)
			nextBonusFrame = frame + (rand() % BONUS_SEED);

		/* Do we need to add a bonus coin or special? */
		if (nextBonusFrame <= frame && bonusBlock == False)
		{
			/* Add the bonus block now - different types */
			switch (rand() % 27)
			{
				case 0: case 1: 
				case 2: case 3: 
				case 4: case 5: 
				case 6: case 7:
					/* Add a normal bonus block */
					AddBonusBlock(display, playWindow, &bonusRow, &bonusCol, 
						BONUS_BLK);
					DEBUG("Attempting Adding a bonus block.")
					break;

				case 8: case 9:
				case 10: case 11:
					/* Add the x2 bonus block */
					if (x2Bonus == False)
					{
						AddBonusBlock(display, playWindow, &bonusRow, 
							&bonusCol, BONUSX2_BLK);
						DEBUG("Attempting Adding a bonus x2 block.")
					}
					break;

				case 12: case 13:
					/* Add the x4 bonus block */
					if (x4Bonus == False)
					{
						AddBonusBlock(display, playWindow, &bonusRow, 
							&bonusCol, BONUSX4_BLK);
						DEBUG("Attempting Adding a bonus x4 block.")
					}
					break;

				case 14: case 15: 
					/* Add the shrink paddle special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						PAD_SHRINK_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special paddle shrink block.")
					break;

				case 16: case 17: 
					/* Add the expand paddle  special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						PAD_EXPAND_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special paddle expand block.")
					break;

				case 18: 
					/* Add the multiball special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						MULTIBALL_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special multiball block.")
					break;

				case 19: 
					/* Add the reverse special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						REVERSE_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special reverse control block.")
					break;

				case 20: case 21: 
					/* Add the machine gun special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						MGUN_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special machine gun block.")
					break;

				case 22:
					/* Add the walloff special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						WALLOFF_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special walls off block.")
					break;

				case 23:
					/* Add the extraball special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						EXTRABALL_BLK, 0);
					DEBUG("Attempting Adding a special extra ball block.")
					break;

				case 24:
					/* Add the death special block */
					AddSpecialBlock(display, playWindow, &bonusRow, &bonusCol, 
						DEATH_BLK, SHOTS_TO_KILL_SPECIAL);
					DEBUG("Attempting Adding a special death block.")
					break;

				case 25:	/* choose a type to dynamite */
					switch (rand() % 7)
					{
						case 0:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, YELLOW_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;

						case 1:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, BLUE_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;

						case 2:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, RED_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;

						case 3:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, PURPLE_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;

						case 4:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, TAN_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;

						case 5:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, COUNTER_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;

						case 6:	/* Dynamite the block */
							SetExplodeAllType(display, playWindow, GREEN_BLK);
							DEBUG("Attempting Adding a special dynamite block.")
							break;
					}
					break;

				case 26:	/* Try and start the eyedude on his way */
					if (getEyeDudeMode() == EYEDUDE_NONE)
						ChangeEyeDudeMode(EYEDUDE_RESET);
					DEBUG("Attempting to start the eyedude.")
					break;

				default:
					break;
			}

			nextBonusFrame = 0;
		}
	}

	HandleBulletMode(display, playWindow);

	/* If any blocks need exploding then do so */
	ExplodeBlocksPending(display, playWindow);

	/* So blocks need animation all the time so do it */
	HandlePendingAnimations(display, playWindow);

	HandleEyeDudeMode(display, playWindow);

	/* See if the level is finished and update level info if needed */
	if (mode == MODE_GAME)
		CheckGameRules(display, playWindow);
}

#if NeedFunctionPrototypes
static void handleGameStates(Display *display)
#else
static void handleGameStates(display)
	Display *display;
#endif
{
	/* Update the message window if any new messages come along */
	DisplayCurrentMessage(display, messWindow);

	/* In game effects */
	switch (currentSfxMode())
	{
		case SFX_STATIC:
			/* Show some static */
			WindowStaticEffect(display, playWindow, PLAY_WIDTH, PLAY_HEIGHT);
			break;

		case SFX_SHAKE:
			/* Something exploded or bumped the screen */
			WindowShakeEffect(display, playWindow);
			break;

		case SFX_FADE:
			/* fade when play arena is taken off screen */
			WindowFadeEffect(display, playWindow, PLAY_WIDTH, PLAY_HEIGHT);
			break;
			
		case SFX_BLIND:
			/* bring the backing buffer pixmap into view via a blind effect */
			WindowBlindEffect(display, playWindow);
			break;
			
		case SFX_SHATTER:
			/* bring the backing buffer pixmap into view via a blind effect */
			WindowShatterEffect(display, playWindow);
			break;
			
		case SFX_NONE:
		default:
			break;
	}

	/* Switch on the current game mode */
	switch (mode)
	{
		case MODE_GAME:
			handleGameMode(display);
			break;

		case MODE_PRESENTS:
			Presents(display, mainWindow);
			break;

		case MODE_BONUS:
			DoBonus(display, mainWindow);
			break;

		case MODE_DIALOGUE:
			break;

		case MODE_INTRO:
			Introduction(display, playWindow);
			break;

		case MODE_INSTRUCT:
			Instructions(display, playWindow);
			break;

		case MODE_KEYS:
			Keys(display, playWindow);
			break;

		case MODE_KEYSEDIT:
			KeysEdit(display, playWindow);
			break;

		case MODE_DEMO:
			Demonstration(display, playWindow);
			break;

		case MODE_PREVIEW:
			PreviewLevel(display, playWindow);
			break;

		case MODE_HIGHSCORE:
			HighScore(display, playWindow);
			break;

		case MODE_EDIT:
			Editor(display, playWindow);
			break;

		case MODE_PAUSE:  
			break;
	}

	/* Flush the display */
	XFlush(display);
}

#if NeedFunctionPrototypes
static void handleEventLoop(Display *display)
#else
static void handleEventLoop(display)
	Display *display;
#endif
{
	XEvent event;
	int pending;
	KeySym keysym;

	pending = frame = 0;

	/* Initial mode for game is Introduction */
	mode = MODE_PRESENTS;

	/* No special effects yet */
	changeSfxMode(SFX_NONE);

	/* Flush all events until app is fully mapped */
    do
	{
		/* handle audio device events if they exist */
		audioDeviceEvents();

		/* Get the next event */
		XNextEvent(display, &event);
	}
	while (event.type != MapNotify);

	ChangePointer(display, mainWindow, CURSOR_NONE);

 	/* Grab the pointer to the main window */
	GrabPointer(display, mainWindow);

	/* Loop forever and ever */
	while (True)
	{
		/* handle and audio device events if supported */
		audioDeviceEvents();

		/* See if any events are waiting for me to handle */
		if (iconified == False && mode != MODE_PAUSE)
		{
			/* Get an event but don't wait if none arrives */
			pending = XPending(display);

			if (mode != MODE_DIALOGUE)
				frame++;
		}
		else
		{
			/* Wait here for an event and then get the number waiting */
			XPeekEvent(display, &event);
			pending = XPending(display);
		}
		
		/* Handle any events pending */
		while (pending > 0)
		{
			/* Get the next X event thanks */
			XNextEvent(display, &event);

			switch(event.type)
			{
				case UnmapNotify:
					/* Turn off just all events except the mapping ones */
    				XSelectInput(display, mainWindow, StructureNotifyMask);
					handleIconify(display);
					iconified = True;
					break;

				case MapNotify:
					/* Turn back on all the events that are needed */
    				XSelectInput(display, mainWindow, 
						KeyPressMask | KeyReleaseMask | ButtonPressMask |
       					ButtonReleaseMask | ButtonMotionMask | ExposureMask | 
						StructureNotifyMask | PointerMotionHintMask);

					/*SelectiveRedraw(display);*/
 					GrabPointer(display, mainWindow);
					iconified = False;
					break;

				case ButtonRelease:
					handleMouseButtons(display, event, False);
					break;

				case ButtonPress:
					handleMouseButtons(display, event, True);
					break;

				case MotionNotify:
					if (mode == MODE_EDIT)
						HandleButtonMotion(display, event);
					break;

				case KeyRelease:
					keysym = GetKeySym(event);
					handleKeyPress(display, keysym, event, False);
					break;

				case KeyPress:
					keysym = GetKeySym(event);
					handleKeyPress(display, keysym, event, True);
					break;

				case Expose:
					handleExposure(display, event);
					break;

				default:
					break;
			}

			/* Decrement the number of pending events */
			pending--;
		}
		
		/* Sleep a bit if not iconified */
		if (iconified == False)
			sleepSync(display, speed);

		/* handle all game states and animations */
		if (iconified == False) 
			handleGameStates(display);
	}

	/* NOT REACHED */
}

#if NeedFunctionPrototypes
int main(int argc, char **argv)
#else
int main(argc, argv)
	int argc;
	char **argv;
#endif
{
	static Display *display;

	/* Initialise everything and return display */
	display = InitialiseGame(argv, argc);

	SetGameSpeed(FAST_SPEED);
	gameActive = False;
	iconified = False;

	XSelectInput(display, mainWindow, 
		KeyPressMask | KeyReleaseMask | ButtonPressMask |
   		ButtonReleaseMask | ExposureMask | StructureNotifyMask );

	/* main event loop */
	handleEventLoop(display);

	/* NOTREACHED */
}