summaryrefslogtreecommitdiff
path: root/jeu-test/Lemmini/0.84/src/Game/GameController.java
blob: 0cc208a0a8ea35988494e0616055c92202aa6273 (plain)
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
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
package Game;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import GameUtil.Fader;
import GameUtil.KeyRepeat;
import GameUtil.Sound;
import GameUtil.Sprite;
import Tools.MicrosecondTimer;
import Tools.ToolBox;


/**
 * Game controller. Contains all the game logic.
 * @author Volker Oth
 */
public class GameController {
	/** game state */
	public static enum State {
		/** init state */
		INIT,
		/** display intro screen */
		INTRO,
		/** display level briefing screen */
		BRIEFING,
		/** display level */
		LEVEL,
		/** display debriefing screen */
		DEBRIEFING,
		/** fade out after level was finished */
		LEVEL_END
	}

	/** Transition states */
	public static enum TransitionState {
		/** no fading */
		NONE,
		/** restart level: fade out, fade in briefing */
		RESTART_LEVEL,
		/** replay level: fade out, fade in briefing */
		REPLAY_LEVEL,
		/** load level: fade out, fade in briefing */
		LOAD_LEVEL,
		/** load replay: fade out, fade in briefing */
		LOAD_REPLAY,
		/** level finished: fade out */
		END_LEVEL,
		/** go to intro: fade in intro */
		TO_INTRO,
		/** go to briefing: fade in briefing */
		TO_BRIEFING,
		/** go to debriefing: fade in debriefing */
		TO_DEBRIEFING,
		/** go to level: fade in level */
		TO_LEVEL
	}

	/** key repeat bitmask for icons */
	public final static int KEYREPEAT_ICON = 1;
	/** key repeat bitmask for keys */
	public final static int KEYREPEAT_KEY = 2;

	/** bang sound */
	public final static int SND_BANG = 0;
	/** brick wheel trap sound */
	public final static int SND_CHAIN = 1;
	/** setting new skill sound */
	public final static int SND_CHANGE_OP = 2;
	/** only some builder steps left sound */
	public final static int SND_CHINK = 3;
	/** dieing sound */
	public final static int SND_DIE = 4;
	/** trap door opening sound */
	public final static int SND_DOOR = 5;
	/** electric sound */
	public final static int SND_ELECTRIC = 6;
	/** explode sound */
	public final static int SND_EXPLODE = 7;
	/** fire sound */
	public final static int SND_FIRE = 8;
	/** drowning sound */
	public final static int SND_GLUG = 9;
	/** start of level sound */
	public final static int SND_LETSGO = 10;
	/** bear/twiner trap sound */
	public final static int SND_MANTRAP = 11;
	/** mouse clicked sound */
	public final static int SND_MOUSEPRE = 12;
	/** nuke command sound */
	public final static int SND_OHNO = 13;
	/** leaving exit sound */
	public final static int SND_OING = 14;
	/** scrape sound */
	public final static int SND_SCRAPE = 15;
	/** slicer sound */
	public final static int SND_SLICER = 16;
	/** splash sound */
	public final static int SND_SPLASH = 17;
	/** faller splat sound */
	public final static int SND_SPLAT = 18;
	/** ten tons sound, also pipe sucking lemmings in */
	public final static int SND_TEN_TONS = 19;
	/** icycle, brick stamper sound */
	public final static int SND_THUD = 20;
	/** thunk sound */
	public final static int SND_THUNK = 21;
	/** ting sound */
	public final static int SND_TING = 22;
	/** yipee sound */
	public final static int SND_YIPEE = 23;

	/** updates 5 frames instead of 1 in fast forward mode */
	public final static int FAST_FWD_MULTI = 5;
	/** updates 3 frames instead of 1 in Superlemming mode */
	public final static int SUPERLEMM_MULTI = 3;
	/** time per frame in microseconds - this is the timing everything else is based on */
	public final static int MICROSEC_PER_FRAME = 30*1000;
	/** resync if time difference greater than that (in microseconds)*/
	public final static int MICROSEC_RESYNC = 5*30*1000;

	/** redraw animated level obejcts every 3rd frame (about 100ms) */
	private final static int MAX_ANIM_CTR = 100*1000/MICROSEC_PER_FRAME;
	/** open Entry after about 1.5 seconds */
	private final static int MAX_ENTRY_OPEN_CTR = 1500*1000/MICROSEC_PER_FRAME;
	/** one second is 33.33 ticks (integer would cause error) */
	private final static double MAX_SECOND_CTR = 1000.0*1000/MICROSEC_PER_FRAME;
	/** maximum release rate */
	private final static int MAX_RELEASE_RATE = 99;

	/** nuke icon: maximum time between two mouse clicks for double click detection (in microseconds) */
	private final static long MICROSEC_NUKE_DOUBLE_CLICK = 240*1000;
	/** +/- icons: maximum time between two mouse clicks for double click detection (in microseconds) */
	private final static long MICROSEC_RELEASE_DOUBLE_CLICK = 200*1000;
	/** +/- icons: time for key repeat to kick in */
	private final static long MICROSEC_KEYREPEAT_START = 250*1000;
	/** +/- icons: time for key repeat rate */
	private final static long MICROSEC_KEYREPEAT_REPEAT = 67*1000;

	/** sound object */
	public static Sound sound;
	// pour le mode W
	public static boolean modeW = false;
	/** the background stencil */
	public static Stencil stencil;
	/** the background image */
	public static BufferedImage bgImage;
	/** flag: play music */
	private static boolean musicOn;
	/** flag: play sounds */
	private static boolean soundOn;
	/** flag: use advanced mouse selection methods */
	private static boolean advancedSelect;
	/** graphics object for the background image */
	private static Graphics2D bgGfx;
	/** color used to erase the background (black) */
	private static Color blankColor = new Color(0xff,0,0,0);
	/** flag: fast forward mode is active */
	private static boolean fastForward;
	/** flag: Superlemming mode is active */
	private static boolean superLemming;
	/** game state */
	private static State gameState;
	/** transition (fading) state */
	private static TransitionState transitionState;
	/** skill to assign to lemming (skill icon) */
	private static Lemming.Type lemmSkill;
	/** flag: entry is openend */
	private static boolean entryOpened;
	/** flag: nuke was acticated */
	private static boolean nuke;
	/** flag: game is paused */
	private static boolean paused;
	/** flag: cheat/debug mode is activated */
	public static boolean cheat = false;
	/** flag: cheat mode was activated during play */
	private static boolean wasCheated = false;
	/** frame counter for handling opening of entries */
	private static int entryOpenCtr;
	/** frame counter for handling time */
	private static double secondCtr;
	/** frame counter used to handle release of new Lemmings */
	private static int releaseCtr;
	/** threshold to release a new Lemming */
	private static int releaseBase;
	/** frame counter used to update animated sprite objects */
	private static int animCtr;
	/** level object */
	public static Level level;
	/** index of current difficulty level */
	private static int curDiffLevel;
	/** index of current level pack */
	private static int curLevelPack;
	/** index of current level */
	private static int curLevelNumber;
	/** index of next difficulty level */
	private static int nextDiffLevel;
	/** index of next level pack */
	private static int nextLevelPack;
	/** index of next level */
	private static int nextLevelNumber;
	/** list of all active Lemmings in the Level */
	private static LinkedList<Lemming> lemmings;
	/** list of all active explosions */
	private static LinkedList<Explosion> explosions;
	/** list of all Lemmings under the mouse cursor */
	private static ArrayList<Lemming> lemmsUnderCursor;
	/** array of available level packs */
	private static LevelPack levelPack[];
	/** small preview version of level used in briefing screen */
	private static BufferedImage mapPreview;
	/** timer used for nuking */
	private static MicrosecondTimer timerNuke;
	/** key repeat object for plus key/icon */
	private static KeyRepeat plus;
	/** key repeat object for minus key/icon */
	private static KeyRepeat minus;
	/** Lemming for which skill change is requested */
	private static Lemming lemmSkillRequest;
	/** horizontal scrolling offset for level */
	private static int xPos;
	/** replay stream used for handling replays */
	private static ReplayStream replay;
	/** frame counter used for handling replays */
	private static int replayFrame;
	/** old value of release rate */
	private static int releaseRateOld;
	/** old value of nuke flag */
	private static boolean nukeOld;
	/** old value of horizontal scrolling position */
	private static int xPosOld;
	/** old value of selected skill */
	private static Lemming.Type lemmSkillOld;
	/** flag: replay mode is active */
	private static boolean replayMode;
	/** flag: replay mode should be stopped */
	private static boolean stopReplayMode;
	/** listener to inform GUI of player's progress */
	private static UpdateListener levelMenuUpdateListener;
	/** number of Lemmings which left the level */
	private static int numLeft;
	/** release rate 0..99 */
	private static int releaseRate;
	/** number of Lemmings available */
	private static int numLemmingsMax;
	/** number of Lemmings who entered the level */
	private static int numLemmingsOut;
	/** number of Lemmings which have to be rescued to finish the level */
	private static int numToRecue;
	/** time left in seconds */
	private static int time;
	/** number of climber skills left to be assigned */
	private static int numClimbers;
	/** number of floater skills left to be assigned */
	private static int numFloaters;
	/** number of bomber skills left to be assigned */
	private static int numBombers;
	/** number of blocker skills left to be assigned */
	private static int numBlockers;
	/** number of builder skills left to be assigned */
	private static int numBuilders;
	/** number of basher skills left to be assigned */
	private static int numBashers;
	/** number of miner skills left to be assigned */
	private static int numMiners;
	/** number of digger skills left to be assigned */
	private static int numDiggers;
	/** free running update counter */
	private static int updateCtr;
	/** gain for sound 0..1.0 */
	private static double soundGain = 1.0;
	/** gain for music 0..1.0 */
	private static double musicGain = 1.0;

	/**
	 * Initialization.
	 * @throws ResourceException
	 */
	public static void init() throws ResourceException {
		bgImage = ToolBox.createImage(Level.WIDTH, Level.HEIGHT, Transparency.BITMASK);
		bgGfx = bgImage.createGraphics();

		gameState = State.INIT;
		sound = new Sound(24,SND_MOUSEPRE);
		sound.setGain(soundGain);
		Icons.init(Core.getCmp());
		Explosion.init();
		Lemming.loadLemmings(Core.getCmp());
		lemmings = new LinkedList<Lemming>();
		explosions = new LinkedList<Explosion>();
		lemmsUnderCursor = new ArrayList<Lemming>(10);
		lemmSkillRequest = null;

		LemmFont.init();
		NumFont.init();
		LemmCursor.init();
		Music.init();
		Music.setGain(musicGain);
		MiscGfx.init();

		plus  = new KeyRepeat(MICROSEC_KEYREPEAT_START, MICROSEC_KEYREPEAT_REPEAT, MICROSEC_RELEASE_DOUBLE_CLICK);
		minus = new KeyRepeat(MICROSEC_KEYREPEAT_START, MICROSEC_KEYREPEAT_REPEAT, MICROSEC_RELEASE_DOUBLE_CLICK);
		timerNuke = new MicrosecondTimer();

		level = new Level();
		// read level packs

		File dir = new File(Core.resourcePath+"levels");
		File files[] = dir.listFiles();
		// now get the names of the directories
		ArrayList<String> dirs = new ArrayList<String>();
		for (int i=0; i<files.length; i++)
			if (files[i].isDirectory())
				dirs.add(files[i].getName());
		Collections.sort(dirs);

		levelPack = new LevelPack[dirs.size()+1];
		levelPack[0] = new LevelPack(); // dummy
		for (int i=0; i<dirs.size(); i++) {  // read levels
			String lvlName = dirs.get(i);
			levelPack[i+1] = new LevelPack(Core.findResource("levels/"+ToolBox.addSeparator(lvlName)+"levelpack.ini"));
		}
		curDiffLevel = 0;
		curLevelPack = 1; // since 0 is dummy
		curLevelNumber = 0;

		replayFrame = 0;
		replay = new ReplayStream();
		replayMode = false;
		stopReplayMode = false;

		if (isCheat())
			wasCheated = true;
		else
			wasCheated = false;
	}

	/**
	 * Calculate absolute level number from diff level and relative level number
	 * @param lvlPack   level pack
	 * @param diffLevel difficulty level
	 * @param level     relative level number
	 * @return absolute level number (0..127)
	 */
	static int absLevelNum(final int lvlPack, final int diffLevel, final int level) {
		LevelPack lpack = levelPack[lvlPack];
		// calculate absolute level number
		int absLvl = level;
		for (int i=0; i<diffLevel; i++)
			absLvl += lpack.getLevels(i).length;
		return absLvl;
	}

	/**
	 * Calculate diffLevel and relative level number from absolute level number
	 * @param lvlPack level pack
	 * @param lvlAbs  absolute level number
	 * @return { difficulty level, relative level number }
	 */
	public static int[] relLevelNum(final int lvlPack, final int lvlAbs) {
		int retval[] = new int[2];
		LevelPack lpack = levelPack[lvlPack];
		int diffLevels = lpack.getDiffLevels().length;
		int lvl=0;
		int diffLvl=0;
		int maxLevels=30;
		for (int i=0, ls = 0; i<diffLevels; i++) {
			int ls_old = ls;
			// add number of levels existing in this diff level
			maxLevels = lpack.getLevels(i).length;
			ls += maxLevels;
			if (lvlAbs < ls) {
				diffLvl = i;
				lvl = lvlAbs - ls_old; // relative level mumber
				break;
			}
		}
		retval[0] = diffLvl;
		retval[1] = lvl;
		return retval;
	}

	/**
	 * Proceed to next level.
	 * @return true: ok, false: no more level in this difficulty level
	 */
	public static synchronized boolean nextLevel() {
		int num = curLevelNumber + 1;

		if ( num < levelPack[curLevelPack].getLevels(curDiffLevel).length ) {
			curLevelNumber = num;
			return true;
		} else
			return false; // congrats - difficulty level done
	}

	/**
	 * Fade out at end of level.
	 */
	public static synchronized void endLevel() {
		transitionState = TransitionState.END_LEVEL;
		gameState = State.LEVEL_END;
		Fader.setState(Fader.State.OUT);
	}

	/**
	 * Level successfully finished, enter debriefing and tell GUI to enable next level.
	 */
	static synchronized void finishLevel() {
		Music.stop();
		setFastForward(false);
		setSuperLemming(false);
		replayMode = false;

		if (!wasLost()) {
			if (curLevelPack!=0)
				levelMenuUpdateListener.update();
			//			String pack = levelPack[curLevelPack].getName();
			//			String diff = levelPack[curLevelPack].getDiffLevels()[curDiffLevel];
			//			// get next level
			//			int num = curLevelNumber + 1;
			//			if ( num >= levelPack[curLevelPack].getLevels(curDiffLevel).length )
			//				num = curLevelNumber;
			//			// set next level as available
			//			GroupBitfield bf = Core.player.setAvailable(pack, diff, num);
			//			// update the menu
			//			if (curLevelPack!=0) // 0 is the dummy pack
			//				((Lemmini)Core.getCmp()).updateLevelMenu(pack, diff, bf);
		}
		gameState = State.DEBRIEFING;
	}

	/**
	 * Hook for GUI to get informed when a level was successfully finished.
	 * @param l UpdateListener
	 */
	public static void setLevelMenuUpdateListener(final UpdateListener l) {
		levelMenuUpdateListener = l;
	}

	/**
	 * Restart level.
	 * @param doReplay true: replay, false: play
	 */
	private static synchronized void restartLevel(final boolean doReplay) {
		initLevel();
		if (doReplay) {
			replayMode = true;
			replay.save(Core.resourcePath+"/replay.rpl");
			replay.rewind();
		} else {
			replayMode = false;
			replay.clear();
		}
	}

	/**
	 * Initialize a level after it was loaded.
	 */
	private static void initLevel() {
		Music.stop();

		setFastForward(false);
		setPaused(false);
		nuke = false;

		lemmSkillRequest = null;

		TextScreen.setMode(TextScreen.Mode.INIT);

		bgGfx.setBackground(blankColor);
		bgGfx.clearRect(0, 0, bgImage.getWidth(), bgImage.getHeight());

		stencil = getLevel().paintLevel(bgImage, Core.getCmp(), stencil);

		lemmings.clear();
		explosions.clear();
		Icons.reset();

		TrapDoor.reset(getLevel().getEntryNum());
		entryOpened = false;
		entryOpenCtr = 0;
		secondCtr = 0;
		releaseCtr = 0;
		lemmSkill = Lemming.Type.UNDEFINED;

		plus.init();
		minus.init();

		numLeft = 0;
		releaseRate = getLevel().getReleaseRate();
		numLemmingsMax = getLevel().getNumLemmings();
		numLemmingsOut = 0;
		numToRecue  = getLevel().getNumToRescue();
		time        = getLevel().getTimeLimitSeconds();
		numClimbers = getLevel().getNumClimbers();
		numFloaters = getLevel().getNumFloaters();
		numBombers = getLevel().getNumBombers();
		numBlockers = getLevel().getNumBlockers();
		numBuilders = getLevel().getNumBuilders();
		numBashers = getLevel().getNumBashers();
		numMiners = getLevel().getNumMiners();
		numDiggers = getLevel().getMumDiggers();
		setxPos(getLevel().getXpos());

		calcReleaseBase();

		mapPreview = getLevel().createMiniMap(mapPreview, bgImage, 4, 4, false);

		setSuperLemming(getLevel().isSuperLemming());

		replayFrame = 0;
		stopReplayMode = false;
		releaseRateOld = releaseRate;
		lemmSkillOld = lemmSkill;
		nukeOld = false;
		xPosOld = getLevel().getXpos();

		gameState = State.BRIEFING;
	}

	/**
	 * Request the restart of this level.
	 * @param doReplay
	 */
	public static synchronized void requestRestartLevel(final boolean doReplay) {
		if (doReplay)
			transitionState = TransitionState.REPLAY_LEVEL;
		else
			transitionState = TransitionState.RESTART_LEVEL;
		Fader.setState(Fader.State.OUT);
	}

	/**
	 * Request a new level.
	 * @param lPack index of level pack
	 * @param dLevel index of difficulty level
	 * @param lNum level number
	 * @param doReplay true: replay, false: play
	 */
	public static synchronized void requestChangeLevel(final int lPack, final int dLevel, final int lNum, final boolean doReplay) {
		nextLevelPack = lPack;
		nextDiffLevel = dLevel;
		nextLevelNumber = lNum;

		if (doReplay)
			transitionState = TransitionState.LOAD_REPLAY;
		else
			transitionState = TransitionState.LOAD_LEVEL;
		Fader.setState(Fader.State.OUT);
	}

	/**
	 * Start a new level.
	 * @param lPack index of level pack
	 * @param dLevel index of difficulty level
	 * @param lNum level number
	 * @param doReplay true: replay, false: play
	 */
	static private synchronized Level changeLevel(final int lPack, final int dLevel, final int lNum, final boolean doReplay) throws ResourceException, LemmException {
		//gameState = GAME_ST_INIT;
		curLevelPack = lPack;
		curDiffLevel = dLevel;
		curLevelNumber = lNum;

		String lvlPath = levelPack[curLevelPack].getInfo(curDiffLevel, curLevelNumber).getFileName();
		// lemmings need to be reloaded to contain pink color
		Lemming.loadLemmings(Core.getCmp());
		// loading the level will patch pink lemmings pixels to correct color
		getLevel().loadLevel(lvlPath);

		// if with and height would be stored inside the level, the bgImage etc. would have to
		// be recreated here
		// bgImage = gc.createCompatibleImage(Level.width, Level.height, Transparency.BITMASK);
		// bgGfx = bgImage.createGraphics();

		initLevel();

		if (doReplay) {
			replayMode = true;
			replay.rewind();
		} else {
			replayMode = false;
			replay.clear();
		}

		return getLevel();
	}

	/**
	 * Get level lost state.
	 * @return true if level was lost, false otherwise
	 */
	static synchronized boolean wasLost() {
		if (gameState != State.LEVEL && numLeft >= numToRecue)
			return false;
		return true;
	}

	/**
	 * Get current replay image.
	 * @return current replay image
	 */
	public synchronized static BufferedImage getReplayImage() {
		if (!replayMode)
			return null;
		if ( (replayFrame & 0x3f) > 0x20)
			return MiscGfx.getImage(MiscGfx.Index.REPLAY_1);
		else
			return MiscGfx.getImage(MiscGfx.Index.REPLAY_2);
	}

	/**
	 * Get a Lemming under the selection cursor.
	 * @param type cursor type
	 * @return fitting Lemming or null if none found
	 */
	public static synchronized Lemming lemmUnderCursor(final LemmCursor.Type type) {
		// search for level without the skill
		for (int i=0; i<getLemmsUnderCursor().size(); i++) {
			Lemming l = getLemmsUnderCursor().get(i);
			// Walker only cursor: ignore non-walkers
			if (type == LemmCursor.Type.WALKER && l.getSkill()!=Lemming.Type.WALKER)
				continue;
			if (type == LemmCursor.Type.LEFT && l.getDirection() != Lemming.Direction.LEFT)
				continue;
			if (type == LemmCursor.Type.RIGHT && l.getDirection() != Lemming.Direction.RIGHT)
				continue;
			switch (lemmSkill) {
				case CLIMBER:
					if (!l.canClimb())
						return l;
					break;
				case FLOATER:
					if (!l.canFloat())
						return l;
					break;
				default:
					if (l.canChangeSkill() && l.getSkill() != lemmSkill && l.getName().length() > 0) {
						//System.out.println(l.getName());
						return l;
					}
			}
			break;
		}
		if (type == LemmCursor.Type.NORMAL && getLemmsUnderCursor().size() > 0) {
			Lemming l = getLemmsUnderCursor().get(0);
			if (l.getName().length() == 0)
				return null;
			//System.out.println(((Lemming)lemmsUnderCursor.get(0)).getName());
			return l;
		}
		return null;
	}

	/**
	 * Lemming has left the Level.
	 */
	static synchronized void increaseLeft() {
		numLeft += 1;
	}

	/**
	 * Stop replay.
	 */
	private static void stopReplayMode() {
		if (replayMode)
			stopReplayMode = true;
	}

	/**
	 * Return time as String "minutes-seconds"
	 * @return time as String "minutes-seconds"
	 */
	public synchronized static String getTimeString() {
		String t1 = Integer.toString(time/60);
		String t2 = Integer.toString(time%60);
		if (t2.length() < 2)
			t2 = "0"+t2;
		return t1 + "-" + t2;
	}

	/**
	 * Update the whole game state by one frame.
	 */
	public static synchronized void update() {
		if (gameState != State.LEVEL)
			return;

		updateCtr++;

		if (!replayMode)
			assignSkill(false); // first try to assign skill

		// check +/- buttons also if paused
		KeyRepeat.Event fired = plus.fired();
		if (fired != KeyRepeat.Event.NONE) {
			if (releaseRate < MAX_RELEASE_RATE) {
				if (fired == KeyRepeat.Event.DOUBLE_CLICK)
					releaseRate = MAX_RELEASE_RATE;
				else
					releaseRate += 1;
				calcReleaseBase();
				sound.playPitched(releaseRate);
			} else sound.play(SND_TING);
		}

		fired = minus.fired();
		if (fired != KeyRepeat.Event.NONE) {
			if (releaseRate > getLevel().getReleaseRate()) {
				if (fired == KeyRepeat.Event.DOUBLE_CLICK)
					releaseRate = getLevel().getReleaseRate();
				else
					releaseRate -= 1;
				calcReleaseBase();
				sound.playPitched(releaseRate);
			} else sound.play(SND_TING);
		}


		if (isPaused())
			return;

		// test for end of replay mode
		if ( replayMode && stopReplayMode ) {
			replay.clearFrom(replayFrame);
			replayMode = false;
			stopReplayMode = false;
		}

		if (!replayMode) {
			if (!wasCheated) {
				// replay: release rate changed?
				if (releaseRate != releaseRateOld) {
					replay.addReleaseRateEvent(replayFrame, releaseRate);
					releaseRateOld = releaseRate;
				}
				// replay: nuked?
				if (nuke != nukeOld) {
					replay.addNukeEvent(replayFrame);
					nukeOld = nuke;
				}
				// replay: xPos changed?
				if (getxPos() != xPosOld) {
					replay.addXPosEvent(replayFrame, getxPos());
					xPosOld = getxPos();
				}
				// skill changed
				if (lemmSkill != lemmSkillOld) {
					replay.addSelectSkillEvent(replayFrame, lemmSkill);
					lemmSkillOld = lemmSkill;
				}
			} else replay.clear();
		} else {
			// replay mode
			ReplayEvent r;
			while ( (r=replay.getNext(replayFrame)) != null) {
				switch (r.type) {
					case ReplayStream.ASSIGN_SKILL: {
						ReplayAssignSkillEvent rs = (ReplayAssignSkillEvent)r;
						synchronized (lemmings) {
							Lemming l = lemmings.get(rs.lemming);
							l.setSkill(rs.skill);
							l.setSelected();
						}
						switch (rs.skill) {
							case FLOATER:
								numFloaters -= 1;
								break;
							case CLIMBER:
								numClimbers -= 1;
								break;
							case BOMBER:
								numBombers -= 1;
								break;
							case DIGGER:
								numDiggers -= 1;
								break;
							case BASHER:
								numBashers -= 1;
								break;
							case BUILDER:
								numBuilders -= 1;
								break;
							case MINER:
								numMiners -= 1;
								break;
							case STOPPER:
								numBlockers -= 1;
								break;
						}
						sound.play(SND_CHANGE_OP);
						break;
					}
					case ReplayStream.SET_RELEASE_RATE:
						ReplayReleaseRateEvent rr = (ReplayReleaseRateEvent)r;
						releaseRate = rr.releaseRate;
						calcReleaseBase();
						sound.playPitched(releaseRate);
						break;
					case ReplayStream.NUKE:
						nuke = true;
						break;
					case ReplayStream.MOVE_XPOS: {
						ReplayMoveXPosEvent rx = (ReplayMoveXPosEvent)r;
						setxPos(rx.xPos);
						break;
					}
					case ReplayStream.SELECT_SKILL: {
						ReplaySelectSkillEvent rs = (ReplaySelectSkillEvent)r;
						lemmSkill = rs.skill;
						switch (lemmSkill) {
							case FLOATER:
								Icons.press(Icons.Type.FLOAT);
								break;
							case CLIMBER:
								Icons.press(Icons.Type.CLIMB);
								break;
							case BOMBER:
								Icons.press(Icons.Type.BOMB);
								break;
							case DIGGER:
								Icons.press(Icons.Type.DIG);
								break;
							case BASHER:
								Icons.press(Icons.Type.BASH);
								break;
							case BUILDER:
								Icons.press(Icons.Type.BUILD);
								break;
							case MINER:
								Icons.press(Icons.Type.MINE);
								break;
							case STOPPER:
								Icons.press(Icons.Type.BLOCK);
								break;
						}
						break;
					}
				}
			}
		}

		// replay: xpos changed

		// store locally to avoid it's overwritten amidst function
		boolean nukeTemp = nuke;

		// time
		secondCtr+=1.0;
		if (secondCtr > MAX_SECOND_CTR) {
			// one second passed
			secondCtr -= MAX_SECOND_CTR;
			time--;
			if (!isCheat() && time == 0) {
				// level failed
				endLevel();
			}
		}
		// release
		if (entryOpened && !nukeTemp && !isPaused() && numLemmingsOut < getNumLemmingsMax() && ++releaseCtr >= releaseBase) {
			releaseCtr = 0;
			//LemmingResource ls = Lemming.getResource(Lemming.TYPE_FALLER);
			try {
				if (getLevel().getEntryNum() != 0) {
					Entry e = getLevel().getEntry(TrapDoor.getNext());
					Lemming l = new Lemming(e.xPos+2, e.yPos+20);
					synchronized (lemmings) {
						lemmings.add(l);
					}
					numLemmingsOut++;
				}
			} catch (ArrayIndexOutOfBoundsException ex) {}
		}
		// nuking
		if (nukeTemp && ((updateCtr&1)==1)) {
			synchronized (lemmings) {
				Iterator<Lemming> it = lemmings.iterator();
				while (it.hasNext()) {
					Lemming l = it.next();
					if (!l.nuke() && !l.hasDied() && !l.hasLeft()) {
						l.setSkill(Lemming.Type.NUKE);
						//System.out.println("nuked!");
						break;
					}
				}
			}
		}
		// open trap doors ?
		if (!entryOpened) {
			if (++entryOpenCtr == MAX_ENTRY_OPEN_CTR) {
				for (int i=0; i<getLevel().getEntryNum(); i++)
					getLevel().getSprObject(getLevel().getEntry(i).id).setAnimMode(Sprite.Animation.ONCE);
				sound.play(SND_DOOR);
			} else if (entryOpenCtr == MAX_ENTRY_OPEN_CTR+10*MAX_ANIM_CTR) {
				//System.out.println("opened");
				entryOpened = true;
				releaseCtr = releaseBase; // first lemming to enter at once
				if (musicOn)
					Music.play();
			}
		}
		// end of game conditions
		if ((nukeTemp || numLemmingsOut == getNumLemmingsMax()) && explosions.size()==0 && lemmings.size()==0) {
			endLevel();
		}

		synchronized (lemmings) {
			Iterator<Lemming> it = lemmings.iterator();
			while (it.hasNext()) {
				Lemming l = it.next();
				if (l.hasDied() || l.hasLeft()) {
					it.remove();
					continue;
				}
				l.animate();
			}
		}

		synchronized (explosions) {
			Iterator<Explosion> it = explosions.iterator();
			while (it.hasNext()) {
				Explosion e = it.next();
				if (e.isFinished())
					it.remove();
				else
					e.update();
			}
		}

		// animate level objects
		if (++animCtr > MAX_ANIM_CTR) {
			animCtr -= MAX_ANIM_CTR;
			for (int n=0; n<getLevel().getSprObjectNum(); n++) {
				SpriteObject spr = getLevel().getSprObject(n);
				spr.getImageAnim(); // just to animate
			}
		}

		if (!replayMode)
			assignSkill(true); // 2nd try to assign skill

		replayFrame ++;
	}

	/**
	 * Request a skill change for a Lemming (currently selected skill).
	 * @param lemm Lemming
	 */
	public synchronized static void requestSkill(final Lemming lemm) {
		if (lemmSkill != Lemming.Type.UNDEFINED)
			lemmSkillRequest = lemm;
		stopReplayMode();
	}

	/**
	 * Assign the selected skill to the selected Lemming.
	 * @param delete flag: reset the current skill request
	 */
	private synchronized static void assignSkill(final boolean delete) {
		if (lemmSkillRequest == null || lemmSkill == Lemming.Type.UNDEFINED)
			return;

		Lemming lemm = lemmSkillRequest;
		if (delete)
			lemmSkillRequest = null;

		boolean canSet = false;
		stopReplayMode();

		if (isCheat()) {
			canSet = lemm.setSkill(lemmSkill);
		} else {
			switch (lemmSkill) {
				case BASHER:
					if (numBashers > 0 && lemm.setSkill(lemmSkill)) {
						numBashers -= 1;
						canSet = true;
					}
					break;
				case BOMBER:
					if (numBombers > 0 && lemm.setSkill(lemmSkill)) {
						numBombers -= 1;
						canSet = true;
					}
					break;
				case BUILDER:
					if (numBuilders > 0 && lemm.setSkill(lemmSkill)) {
						numBuilders -= 1;
						canSet = true;
					}
					break;
				case CLIMBER:
					if (numClimbers > 0 && lemm.setSkill(lemmSkill)) {
						numClimbers -= 1;
						canSet = true;
					}
					break;
				case DIGGER:
					if (numDiggers > 0 && lemm.setSkill(lemmSkill)) {
						numDiggers -= 1;
						canSet = true;
					}
					break;
				case FLOATER:
					if (numFloaters > 0 && lemm.setSkill(lemmSkill)) {
						numFloaters -= 1;
						canSet = true;
					}
					break;
				case MINER:
					if (numMiners > 0 && lemm.setSkill(lemmSkill)) {
						numMiners -= 1;
						canSet = true;
					}
					break;
				case STOPPER:
					if (numBlockers > 0 && lemm.setSkill(lemmSkill)) {
						numBlockers -= 1;
						canSet = true;
					}
					break;
			}
		}
		if (canSet) {
			lemmSkillRequest = null; // erase request
			sound.play(SND_MOUSEPRE);
			if (isPaused()) {
				setPaused(false);
				Icons.press(Icons.Type.PAUSE);
			}
			// add to replay stream
			if (!wasCheated)
				synchronized (lemmings) {
					for (int i=0; i<lemmings.size(); i++)
						if (lemmings.get(i) == lemm) // if 2nd try (delete==true) assign to next frame
							replay.addAssignSkillEvent(replayFrame+((delete) ? 1:0), lemmSkill, i);
				}
		} else if (delete)
			sound.play(SND_TING);
	}

	/**
	 * Calculate the counter threshold for releasing a new Lemmings.
	 */
	static private void calcReleaseBase() {
		// the original formula is: release lemming every 4+(99-speed)/2 time steps
		// where one step is 60ms (3s/50) or 66ms (4s/60).
		// Lemmini runs at 30ms/33ms, so the term has to be multiplied by 2
		// 8+(99-releaseRate) should be correct
		releaseBase = 8 + (99 - releaseRate);
	}

	/**
	 * Handle pressing of an icon button.
	 * @param type icon type
	 */
	public static synchronized void handleIconButton(final Icons.Type type) {
		Lemming.Type lemmSkillOld = lemmSkill;
		boolean ok = false;
		switch (type) {
			case FLOAT:
				if (isCheat() || numFloaters>0)
					lemmSkill = Lemming.Type.FLOATER;
				stopReplayMode();
				break;
			case CLIMB:
				if (isCheat() || numClimbers>0)
					lemmSkill = Lemming.Type.CLIMBER;
				stopReplayMode();
				break;
			case BOMB:
				if (isCheat() || numBombers>0)
					lemmSkill = Lemming.Type.BOMBER;
				stopReplayMode();
				break;
			case DIG:
				if (isCheat() || numDiggers>0)
					lemmSkill = Lemming.Type.DIGGER;
				stopReplayMode();
				break;
			case BASH:
				if (isCheat() || numBashers>0)
					lemmSkill = Lemming.Type.BASHER;
				stopReplayMode();
				break;
			case BUILD:
				if (isCheat() || numBuilders>0)
					lemmSkill = Lemming.Type.BUILDER;
				stopReplayMode();
				break;
			case MINE:
				if (isCheat() || numMiners>0)
					lemmSkill = Lemming.Type.MINER;
				stopReplayMode();
				break;
			case BLOCK:
				if (isCheat() || numBlockers>0)
					lemmSkill = Lemming.Type.STOPPER;
				stopReplayMode();
				break;
			case NUKE: {
				ok = true;
				stopReplayMode();
				if (timerNuke.delta() < MICROSEC_NUKE_DOUBLE_CLICK) {
					if (!nuke) {
						nuke = true;
						sound.play(SND_OHNO);
					}
				} else timerNuke.deltaUpdate();
				break;}
			case PAUSE:
				setPaused(!isPaused());
				ok = true;
				break;
			case FFWD:
				setFastForward(!isFastForward());
				ok = true;
				break;
			case PLUS:
				ok = true; // supress sound
				plus.pressed(KEYREPEAT_ICON);
				stopReplayMode();
				break;
			case MINUS:
				ok = true; // supress sound
				minus.pressed(KEYREPEAT_ICON);
				stopReplayMode();
				break;
		}
		if (ok || lemmSkill != lemmSkillOld) {
			switch (type) {
				case PLUS:
				case MINUS:
					break; // supress sound
				default:
					sound.play(SND_CHANGE_OP);
			}
			Icons.press(type);
		} else
			sound.play(SND_TING);
	}

	/**
	 * Fade in/out.
	 * @param g graphics object
	 */
	public static void fade(final Graphics g) {
		if (Fader.getState() == Fader.State.OFF && transitionState != TransitionState.NONE) {
			switch (transitionState) {
				case END_LEVEL:
					finishLevel();
					break;
				case TO_BRIEFING:
					gameState = State.BRIEFING;
					break;
				case TO_DEBRIEFING:
					gameState = State.DEBRIEFING;
					break;
				case TO_INTRO:
					gameState = State.INTRO;
					break;
				case TO_LEVEL:
					GameController.sound.play(SND_LETSGO);
					try {
						Music.load("music/"+GameController.levelPack[GameController.curLevelPack].getInfo(GameController.curDiffLevel,
								GameController.curLevelNumber).getMusic());
					} catch (ResourceException ex) {
						Core.resourceError(ex.getMessage());
					} catch (LemmException ex) {
						JOptionPane.showMessageDialog( null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
						System.exit(1);
					}
					gameState = State.LEVEL;
					break;
				case RESTART_LEVEL:
				case REPLAY_LEVEL:
					restartLevel(transitionState == TransitionState.REPLAY_LEVEL);
					break;
				case LOAD_LEVEL:
				case LOAD_REPLAY:
					try {
						changeLevel(nextLevelPack, nextDiffLevel, nextLevelNumber, transitionState == TransitionState.LOAD_REPLAY);
						((JFrame)Core.getCmp()).setTitle("Lemmini - "+getLevel().getLevelName());
					} catch (ResourceException ex) {
						Core.resourceError(ex.getMessage());
					} catch (LemmException ex) {
						JOptionPane.showMessageDialog( null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE );
						System.exit(1);
					}
					break;
			}
			Fader.setState(Fader.State.IN);
			transitionState = TransitionState.NONE;
		}
		Fader.fade(g);
	}

	/**
	 * Draw the explosions
	 * @param g graphics object
	 * @param width width of screen in pixels
	 * @param height height of screen in pixels
	 * @param xOfs horizontal level offset in pixels
	 */
	public static void drawExplosions(final Graphics2D g, final int width, final int height, final int xOfs) {
		synchronized (explosions) {
			Iterator<Explosion> it = explosions.iterator();
			while (it.hasNext()) {
				Explosion e = it.next();
				e.draw(g, width, height, xOfs);
			}
		}
	}

	/**
	 * Add a new explosion.
	 * @param x x coordinate in pixels.
	 * @param y y coordinate in pixels.
	 */
	public static void addExplosion(final int x, final int y) {
		// create particle explosion
		synchronized (GameController.explosions) {
			GameController.explosions.add(new Explosion(x, y));
		}
	}

	/**
	 * Draw icon bar.
	 * @param g graphics object
	 * @param x x coordinate in pixels
	 * @param y y coordinate in pixels
	 */
	public static void drawIcons(final Graphics2D g, final int x, final int y) {
		g.drawImage(Icons.getImg(),x,y,null);
	}

	/**
	 * Draw the skill/release rate values
	 * @param g graphics object
	 * @param y y offset in pixels
	 */
	public static void drawCounters(final Graphics2D g, final int y) {
		// draw counters
		int val = 0;
		for (int i=0; i<10;i++) {
			switch (i) {
				case 0:
					val = level.getReleaseRate();
					break;
				case 1:
					val = releaseRate;
					break;
				case 2:
					val = numClimbers;
					break;
				case 3:
					val = numFloaters;
					break;
				case 4:
					val = numBombers;
					break;
				case 5:
					val = numBlockers;
					break;
				case 6:
					val = numBuilders;
					break;
				case 7:
					val = numBashers;
					break;
				case 8:
					val = numMiners;
					break;
				case 9:
					val = numDiggers;
					break;
			}
			g.drawImage(NumFont.numImage(val),Icons.WIDTH*i+8,y,null);
		}

	}

	/**
	 * Get index of current level pack.
	 * @return index of current level pack
	 */
	public static int getCurLevelPackIdx() {
		return curLevelPack;
	}

	/**
	 * Get current level pack.
	 * @return current level pack
	 */
	public static LevelPack getCurLevelPack() {
		return levelPack[curLevelPack];
	}

	/**
	 * get number of level packs
	 * @return number of level packs
	 */
	public static int getLevelPackNum() {
		return levelPack.length;
	}

	/**
	 * Get level pack via index.
	 * @param i index of level pack
	 * @return LevelPack
	 */
	public static LevelPack getLevelPack(final int i) {
		return levelPack[i];
	}

	/**
	 * Get index of current difficulty level.
	 * @return index of current difficulty level
	 */
	public static int getCurDiffLevel() {
		return curDiffLevel;
	}

	/**
	 * Get number of current level.
	 * @return number of current leve
	 */
	public static int getCurLevelNumber() {
		return curLevelNumber;
	}


	/**
	 * Set horizontal scrolling offset.
	 * @param x horizontal scrolling offset in pixels
	 */
	public static void setxPos(final int x) {
		xPos = x;
	}

	/**
	 * Get horizontal scrolling offset.
	 * @return horizontal scrolling offset in pixels
	 */
	public static int getxPos() {
		return xPos;
	}

	/**
	 * Set game state.
	 * @param s new game state
	 */
	public static void setGameState(final State s) {
		gameState = s;
	}

	/**
	 * Get game state.
	 * @return game state
	 */
	public static State getGameState() {
		return gameState;
	}

	/**
	 * Enable/disable cheat mode.
	 * @param c true: enable, false: disable
	 */
	public static void setCheat(final boolean c) {
		cheat = c;
	}

	/**
	 * Get state of cheat mode.
	 * @return true if cheat mode enabled, false otherwise
	 */
	public static boolean isCheat() {
		return cheat;
	}

	/**
	 * Set transition state.
	 * @param ts TransitionState
	 */
	public static void setTransition(final TransitionState ts) {
		transitionState = ts;
	}


	/**
	 * Load a replay.
	 * @param fn file name
	 * @return replay level info object
	 */
	public static ReplayLevelInfo loadReplay(final String fn) {
		return replay.load(fn);
	}

	/**
	 * Save a replay.
	 * @param fn file name
	 * @return true if saved successfully, false otherwise
	 */
	public static boolean saveReplay(final String fn) {
		return replay.save(fn);
	}

	/**
	 * Activate/deactivate Superlemming mode.
	 * @param sl true: activate, false: deactivate
	 */
	public static void setSuperLemming(final boolean sl) {
		superLemming = sl;
	}

	/**
	 * Get Superlemming state.
	 * @return true is Superlemming mode is active, false otherwise
	 */
	public static boolean isSuperLemming() {
		return superLemming;
	}

	/**
	 * Set cheated detection.
	 * @param c true: cheat mode was activated, false otherwise
	 */
	public static void setWasCheated(final boolean c) {
		wasCheated = c;
	}

	/**
	 * Enable pause mode.
	 * @param p true: pause is active, false otherwise
	 */
	public static void setPaused(final boolean p) {
		paused = p;
	}

	/**
	 * Get pause state.
	 * @return true if pause is active, false otherwise
	 */
	public static boolean isPaused() {
		return paused;
	}

	/**
	 * Enable fast forward mode.
	 * @param ff true: fast forward is active, false otherwise
	 */
	public static void setFastForward(final boolean ff) {
		fastForward = ff;
	}

	/**
	 * Get fast forward state.
	 * @return true if fast forward is active, false otherwise
	 */
	public static boolean isFastForward() {
		return fastForward;
	}

	/** get number of lemmings left in the game
	 * @return number of lemmings left in the game
	 */
	public static int getNumLeft() {
		return numLeft;
	}

	/**
	 * Set number of Lemmings left in the game.
	 * @param n number of Lemmings left in the game
	 */
	public static void setNumLeft(final int n) {
		numLeft = n;
	}

	/**
	 * Get level object.
	 * @return level object
	 */
	public static Level getLevel() {
		return level;
	}

	/**
	 * Get maximum number of Lemmings for this level.
	 * @return maximum number of Lemmings for this level
	 */
	public static int getNumLemmingsMax() {
		return numLemmingsMax;
	}

	/**
	 * Get icon type from x position.
	 * @param x x position in pixels
	 * @return icon type
	 */
	public static Icons.Type getIconType(final int x) {
		return Icons.getType(x);
	}

	/**
	 * Icon was pressed.
	 * @param t icon type
	 */
	public static void pressIcon(final Icons.Type t) {
		Icons.press(t);
	}

	/**
	 * Icon was released.
	 * @param t icon type
	 */
	public static void releaseIcon(final Icons.Type t) {
		Icons.release(t);
	}

	/**
	 * Plus was pressed.
	 * @param d bitmask: key or icon
	 */
	public static void pressPlus(final int d) {
		plus.pressed(d);
	}

	/**
	 * Plus was released.
	 * @param d bitmask: key or icon
	 */
	public static void releasePlus(final int d) {
		plus.released(d);
	}

	/**
	 * Minus was pressed.
	 * @param d bitmask: key or icon
	 */
	public static void pressMinus(final int d) {
		minus.pressed(d);
	}

	/**
	 * Minus was released.
	 * @param d bitmask: key or icon
	 */
	public static void releaseMinus(final int d) {
		minus.released(d);
	}

	/**
	 * Get list of all Lemmings under the mouse cursor.
	 * @return list of all Lemmings under the mouse cursor
	 */
	public static ArrayList<Lemming> getLemmsUnderCursor() {
		return lemmsUnderCursor;
	}

	/**
	 * Get list of all Lemmings in this level.
	 * @return list of all Lemmings in this level
	 */
	public static LinkedList<Lemming> getLemmings() {
		return lemmings;
	}

	/**
	 * Set sound gain.
	 * @param g gain (0..1.0)
	 */
	public static void setSoundGain(final double g) {
		soundGain = g;
		if (sound != null)
			sound.setGain(soundGain);
	}

	/**
	 * Set music gain.
	 * @param g gain (0..1.0)
	 */
	public static void setMusicGain(final double g) {
		musicGain = g;
		if (Music.getType() != null)
			Music.setGain(musicGain);
	}

	/**
	 * Set advanced mouse selection mode.
	 * @param sel true: advanced selection mode active, false otherwise
	 */
	public static void setAdvancedSelect(final boolean sel) {
		advancedSelect = sel;
	}

	/**
	 * Get state of advanced mouse selection mode.
	 * @return true if advanced selection mode activated, false otherwise
	 */
	public static boolean isAdvancedSelect() {
		return advancedSelect;
	}

	/**
	 * Get background image of level.
	 * @return background image of level
	 */
	public static BufferedImage getBgImage() {
		return bgImage;
	}

	/**
	 * Get background stencil of level.
	 * @return background stencil of level
	 */
	public static Stencil getStencil() {
		return stencil;
	}

	/**
	 * Enable music.
	 * @param on true: music on, false otherwise
	 */
	public static void setMusicOn(final boolean on) {
		musicOn = on;
	}

	/**
	 * Get music enable state.
	 * @return true: music is on, false otherwise
	 */
	public static boolean isMusicOn() {
		return musicOn;
	}

	/**
	 * Enable sound.
	 * @param on true: sound on, false otherwise
	 */
	public static void setSoundOn(final boolean on) {
		soundOn = on;
	}

	/**
	 * Get sound enable state.
	 * @return true: sound is on, false otherwise
	 */
	public static boolean isSoundOn() {
		return soundOn;
	}

	/**
	 * Get small preview image of level.
	 * @return small preview image of level
	 */
	public static BufferedImage getMapPreview() {
		return mapPreview;
	}

	/**
	 * Get number of Lemmings to rescue.
	 * @return number of Lemmings to rescue
	 */
	public static int  getNumToRecue() {
		return numToRecue;
	}

	/**
	 * Get time left in seconds.
	 * @return time left in seconds
	 */
	public static int getTime() {
		return time;
	}
}


/**
 * Trapdoor/Entry class
 * Trapdoor logic: for numbers >1, just take the next door for each lemming and wrap around to 1 when
 * the last one is reached.
 * Special rule for 3 trapdoors: the order is 1, 2, 3, 2 (loop), not 1, 2, 3 (loop)
 *
 * @author Volker Oth
 */
class TrapDoor {
	/** pattern for three entries */
	private final static int[] PATTERN3 = {0,1,2,1};

	/** number of entries */
	private static int entries;
	/** entry counter */
	private static int counter;

	/**
	 * Reset to new number of entries.
	 * @param e number of entries
	 */
	static void reset(final int e) {
		entries = e;
		counter = 0;
	}

	/**
	 * Get index of next entry.
	 * @return index of next entry
	 */
	static int getNext() {
		int retVal = counter;
		counter++;
		if (entries != 3) {
			if (counter >= entries)
				counter = 0;
			return retVal;
		}
		// special case: 3
		if (counter >= 4)
			counter = 0;
		return PATTERN3[retVal];
	}

}