-
Notifications
You must be signed in to change notification settings - Fork 0
/
Allenroids.cpp
1701 lines (1479 loc) · 65 KB
/
Allenroids.cpp
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
/*
* asteroids.c
* My very first bona-fide C program
*
* Created by Allen Smith on Oct. 6, 2002.
*
* Scoring System:
* Fire a shot: -levelNumber
* Destroy Big Asteroid: (1+playerMaxStrength-playerStrength) * levelNumber
* Destroy Med Asteroid: (2+playerMaxStrength-playerStrength) * levelNumber
* Destroy Small Asteroid: (3+playerMaxStrength-playerStrength) * levelNumber
* Clear Level: 24 * levelNumber
* Destroy Opponent: (144+playerMaxStrength-playerStrength) * levelNumber
* Use reverse drive: -(36 + levelNumber) per 30th of a second
*
*/
#include <cmath>
#include "Allenroids.h"
#include "ConfigureScreen.h"
#include "sound.h"
#include "Starfield.h"
#include "TitleScreen.h"
/*****Global Variables*****/
extern SDL_AudioCVT soundBuffer[];
extern SoundSample channels[NUMBER_CHANNELS];
unsigned int levelNumber = 0; //0 indicates that the game has not yet started
boolean startingNewLevel = false; //this is a flag used while beginning a new level during gameplay. It must be set to false while initializing Level 1
LinkedList<GameObject> shotList;
LinkedList<GameObject> asteroidList; // all the asteroids
LinkedList<GameObject> kerblooieList; // explosion particles
LinkedList<GameObject> crystalList; // special crystals
LinkedList<GameObject> badGuyList; // computer opponents
Starfield starfield;
int millisecondsPerStandardFrame = 1000/FRAMES_PER_SECOND;
int minimumMillisecondsPerFrame = 1000/MAX_FRAMES_PER_SECOND;
GLubyte playerColors[2][3] = { {0, 255, 0}, //Player 1: Green
{0, 128, 255} }; //Player 2: Aqua
GLubyte badGuyColors[] = {224, 0, 0 }; //A reddish color
//Global Constants which are important
unsigned int *crystalReleaseSchedule[CRYSTAL_NUMBER_OF_SPECIMENS]; //how many crystals should be created; arranged into subarrays indicating the release schedule (see startLevel())
int crystalsReleased[CRYSTAL_NUMBER_OF_SPECIMENS]; //how many crystals have been created (the index of the subarrays above)
int *asteroidReleaseSchedule; //how many medium-sized asteroids to release
unsigned int unsmallAsteroidsDestroyedToDate; //how many unsmall asteroids have been hit so far this level
int bigAsteroidsDestroyedToDate; //how many big asteroids have been hit so far this level
int *badGuySchedule; //becomes an array containing the index at which to call a bad guy
int badGuysSummonedToDate; //how many bad guys have appeared in this level so far.
boolean paused; //true if the game is paused
//Players
unsigned short numberOfPlayers = 0;
short numberOfPlayersActive = 0;
Player playerObjects[MAX_NUMBER_PLAYERS];
extern PlayerKeys playerKeys[MAX_NUMBER_PLAYERS]; //defined in 'Configure Screen.c'
/****************************************************
* gameInit
* set up the game and window
***************************************************/
void gameInit(int numberOfPlayersChosen){
unsigned int counter;
//set up glut function calls
glutMouseFunc(NULL);
glutKeyboardFunc(handleKeyboard);
glutKeyboardUpFunc(handleKeyboardUp);
glutSpecialFunc(handleSpecialKeyboard);
glutSpecialUpFunc(handleSpecialKeyboardUp);
glutIgnoreKeyRepeat(true);
glutDisplayFunc(display);
#ifdef TIGHT_IDLE_DRAWING
glutIdleFunc(idle);
#else
glutTimerFunc(10, idleByTimer, 0);
#endif
glPolygonMode(GL_FRONT, GL_FILL);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClearColor(0,0,0, 1);
glClear(GL_COLOR_BUFFER_BIT);
glShadeModel(GL_SMOOTH);
glEnable(GL_LINE_SMOOTH);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_POLYGON_SMOOTH);
glLoadIdentity();
// gluOrtho2D(0, FRAMEWIDTH, 0, FRAMEHEIGHT);
glOrtho(0,FRAMEWIDTH, 0, FRAMEHEIGHT,-640,640);
soundInit();
numberOfPlayers = numberOfPlayersChosen;
numberOfPlayersActive = numberOfPlayersChosen;
for(counter = 1; counter <= numberOfPlayers; counter++){
playerObjects[P(counter)] = Player(counter, numberOfPlayers, playerColors[P(counter)], 3, 8); //3 lives, default strength 8
//Player is created enabled, with score=0, highest level=0
}
//start a completely fresh game.
levelNumber = 0;
paused = false;
//Blank lists must be wiped here, though they were constructed at variable elaboration
//the reason is, if you start another game after finishing one,
//the lists retain all their old data and must be wiped clean.
asteroidList.clearList();
kerblooieList.clearList();
shotList.clearList();
crystalList.clearList();
badGuyList.clearList();
//start level 1
#ifdef RANDOM_ON
srand( time(NULL) );
#endif
startLevel(1);
}
/****************************************************
* display
* paints all the game elements
***************************************************/
void display(void) {
char pausedText[] = "PAUSED"; //print this if the game is paused
char *levelText;
unsigned int counter;
int stringWidth = 0;
float scaleFactor = 0.75; //75% of original size
glClear(GL_COLOR_BUFFER_BIT);
drawStarfield();
for(counter = 1; counter <= numberOfPlayers; counter++){
if(playerObjects[P(counter)].isEnabled() == true)
playerObjects[P(counter)].spaceship.drawInGame();
}
if(!shotList.isEmpty())
drawList(&shotList);
if(!asteroidList.isEmpty())
drawList(&asteroidList);
if( !kerblooieList.isEmpty() )
drawList(&kerblooieList);
if( !crystalList.isEmpty() )
drawList(&crystalList);
if( !badGuyList.isEmpty() )
drawList(&badGuyList);
drawStatisticsHeader();
/**** SOME VERY INTERESTING TESTS. IF SIMPLY gluOrtho2d() IN INIT WITH OUT glLoadIdentity() THESE HUGE SHAPES ARE FULLY VISIBLE!
glColor3ub(255,255,255);
glBegin(GL_POLYGON);
glVertex2i(-9000, -9000);
glVertex2i(-9000, 9000);
glVertex2i( 9000, 9000);
glVertex2i( 9000, -9000);
glEnd();
glColor3ub(255,0,0);
glLineWidth(1.0);
glBegin(GL_LINES);
glVertex2i( 1000, 1000);
glVertex2i( 90000, 90000);
glEnd();
****/
if(paused == true){ //an overlay to indicate a paused game
glColor4ub(128,128,128,128); //transparent grey
glBegin(GL_POLYGON);
glVertex2i( 0, 0);
glVertex2i( FRAMEWIDTH, 0);
glVertex2i( FRAMEWIDTH, FRAMEHEIGHT);
glVertex2i(0, FRAMEHEIGHT);
glEnd();
//Now print the word "PAUSED"
glColor4ub(255,0,0,192);
glLineWidth(4.0);
glPushMatrix();
for(counter = 0; counter < strlen(pausedText); counter++){
stringWidth += glutStrokeWidth( GLUT_STROKE_ROMAN , pausedText[counter]);
}
glTranslatef( FRAMEWIDTH/2 - (stringWidth/2)*scaleFactor, FRAMEHEIGHT/2, 0);
glScalef(scaleFactor, scaleFactor, 0);
glRasterPos2i(0,0);
for(counter = 0; counter < strlen(pausedText); counter++){
glutStrokeCharacter( GLUT_STROKE_ROMAN , pausedText[counter]);
}
glPopMatrix();
} //end if(paused)
//Draw big "Level X" if appropriate
if(startingNewLevel == true && paused == false){ //"Between" levels
//Print the new level number
levelText = (char *) calloc( strlen( "LEVEL ")+levelNumber+1, sizeof(char) );
sprintf(levelText, "LEVEL %d", levelNumber+1);
glColor4ub(128, 0, 64,192); //Maroon with opacity
glLineWidth(4.0);
glPushMatrix();
stringWidth = 0;
for(counter = 0; counter < strlen(levelText); counter++){
stringWidth += glutStrokeWidth( GLUT_STROKE_ROMAN , levelText[counter]);
}
glTranslatef( FRAMEWIDTH/2 - (stringWidth/2)*scaleFactor, FRAMEHEIGHT/2, 0);
glScalef(scaleFactor, scaleFactor, 0);
glRasterPos2i(0,0);
for(counter = 0; counter < strlen(levelText); counter++){
glutStrokeCharacter( GLUT_STROKE_ROMAN , levelText[counter]);
}
glPopMatrix();
free(levelText);
}
glutSwapBuffers();
}
/****************************************************
* drawStarfield
* draws the stars
***************************************************/
void drawStarfield()
{
starfield.Draw();
}
/****************************************************
* drawStatisticsHeader
* Spits out score data and vital signs at the top of the window
***************************************************/
void drawStatisticsHeader(){
char hudText[64]; //"heads-up display?"
const int hudWidth = 80;
const int hudHeight = 12;
const int hudOffsetX = 8;
const int hudOffsetY = 8;
int characterWidth; //width of one glut monospaced character
unsigned int counter;
//create the status bar for ship strength
glPushMatrix();
glTranslatef(hudOffsetX, FRAMEHEIGHT - hudOffsetY - hudHeight, 0);
playerObjects[P(1)].spaceship.drawHealthMeter(hudWidth, hudHeight, true);
glPopMatrix();
//print player 1 vital signs
sprintf(hudText, "Lives:%2d Score:%6d", playerObjects[P(1)].lives >= 0 ? playerObjects[P(1)].lives : 0, playerObjects[P(1)].score); //The evil conditional operator: if lives >= 0, print lives, else print '0'
glRasterPos2i( 2*hudOffsetX + hudWidth, FRAMEHEIGHT - hudHeight - hudOffsetY);
for(counter = 0; counter < strlen(hudText); counter++)
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, hudText[counter]);
//print level number
glColor3ub(128, 0, 64); //Maroon
sprintf(hudText, "LEVEL%3d", levelNumber);
characterWidth = glutBitmapWidth(GLUT_BITMAP_8_BY_13, 'A');
glRasterPos2i( FRAMEWIDTH/2 - strlen(hudText)*characterWidth/2, FRAMEHEIGHT - hudHeight - hudOffsetY);
for(counter = 0; counter < strlen(hudText); counter++)
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, hudText[counter]);
//Player 2
if(numberOfPlayers >= 2){
//create the status bar for ship strength. It changes color based on health
glPushMatrix();
glTranslatef(FRAMEWIDTH - hudOffsetX - hudWidth, FRAMEHEIGHT - hudOffsetY - hudHeight, 0);
playerObjects[P(2)].spaceship.drawHealthMeter(hudWidth, hudHeight, false);
glPopMatrix();
//print player 2 vital signs
sprintf(hudText, "Score:%6d Lives:%2d", playerObjects[P(2)].score, playerObjects[P(2)].lives >= 0 ? playerObjects[P(2)].lives : 0); //The evil conditional operator: if lives >= 0, print lives, else print '0'
glRasterPos2i( FRAMEWIDTH - (2*hudOffsetX + hudWidth) - strlen(hudText)*characterWidth, FRAMEHEIGHT - hudHeight - hudOffsetY);
for(counter = 0; counter < strlen(hudText); counter++)
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, hudText[counter]);
}//endif for player2
}
/****************************************************
* drawList
* draws all elements in the specified linked list
***************************************************/
void drawList(LinkedList<GameObject> *list){
GameObject *currentObject;
Iterator<GameObject> listIterator(list);
currentObject = listIterator.nextObject();
while(listIterator.atEnd() == false){
currentObject->drawInGame();
currentObject = listIterator.nextObject();
}
}
/****************************************************
* moveSpaceShip
* adjust's a ship's location based on its direction vector
***************************************************/
void moveSpaceShip(Spaceship * shipPtr, float movementScaleFactor){
unsigned int counter;
int numberWarningDingsPlaying = 0;
#ifndef ETERNAL_INVINCIBILITY
//If NOT defined
if(shipPtr->invinciblityTimeToLive > 0)
shipPtr->invinciblityTimeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
if(shipPtr->drawShieldsTimeToLive > 0)
shipPtr->drawShieldsTimeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
#endif
if(shipPtr->playerNumber > 0){
//Do max strength computations
if(shipPtr->strength == shipPtr->maxStrength*(1+OVERLOAD_FACTOR) ){
for(counter = 0; counter < NUMBER_CHANNELS; counter++){
if(channels[counter].soundID == WARNING_SOUND(shipPtr->playerNumber) &&
channels[counter].dataPosition != channels[counter].dataLength)
numberWarningDingsPlaying++; //count how many times the thrust sound effect is playing
}
if(numberWarningDingsPlaying < 1)
playSound(soundBuffer, WARNING_SOUND(shipPtr->playerNumber) );
}
}
shipPtr->adjustCoordinate(movementScaleFactor);
}
/****************************************************
* moveShots
* adjust's all shots' locations based on their direction vectors
***************************************************/
void moveShots(LinkedList<GameObject> * shots, float movementScaleFactor){
Shot *shotToMovePtr;
Iterator<GameObject> shotListIterator(shots);
shotToMovePtr = static_cast<Shot *>(shotListIterator.nextObject());
while(shotListIterator.atEnd() == false){
shotToMovePtr->timeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
if(shotToMovePtr->timeToLive > 0 &&
shotToMovePtr->impacted == false){
shotToMovePtr->adjustCoordinate(movementScaleFactor);
}
else{ //destroy the shot; it has expired
#ifdef DEBUG_SHOTS
printf("At time %d shot %d > 8\n",time(NULL),shotToMovePtr->timeFired);
#endif
//we could create an explosion for every shot that vanishes, but it would be pretty annoying
//instead, we only create explosions for shots that hit each other.
//see findShotCollisions()
//spawnKerblooie(KERBLOOIE_INFINITESIMAL, shotToMovePtr->radius, shotToMovePtr->color, shotToMovePtr->position, shotToMovePtr->direction, &kerblooieList);
shotListIterator.removeCurrentPosition();
}
shotToMovePtr = static_cast<Shot *>(shotListIterator.nextObject());
}
}
/****************************************************
* moveAsteroids
* adjusts all asteroids' locations based on their direction vectors
* If an asteroid has been hit by a shot, appropriate action is taken
***************************************************/
void moveAsteroids(LinkedList<GameObject> * asteroids, float movementScaleFactor){
Asteroid *asteroidToMovePtr;
Iterator<GameObject> asteroidListIterator(asteroids);
unsigned short asteroidsToRelease;
int oldAsteroidSize;
unsigned int counter;
Asteroid *newAsteroid;
asteroidToMovePtr = static_cast<Asteroid*>(asteroidListIterator.nextObject());
while(asteroidListIterator.atEnd() == false){
asteroidToMovePtr->adjustCoordinate(movementScaleFactor);
oldAsteroidSize = asteroidToMovePtr->size;
isAsteroidHit(asteroidToMovePtr, &shotList); //if it is, an impacted flag is activated
if(asteroidToMovePtr->impacted.hitCode == true){
if(oldAsteroidSize > ASTEROID_SMALL){
//Do we release crystals?
for(counter = 0; counter < CRYSTAL_NUMBER_OF_SPECIMENS; counter++){
if(crystalReleaseSchedule[counter][ crystalsReleased[counter] ] == unsmallAsteroidsDestroyedToDate ){
spawnCrystal(
counter, //What kind of crystal
asteroidToMovePtr->position,
&crystalList );
crystalsReleased[counter]++;
#ifdef DEBUG_CRYSTALS
printf("C%d: %d\n",counter, crystalsReleased[counter]);
#endif
}
}
//Do we summon a bad guy?
if(badGuySchedule[badGuysSummonedToDate] == unsmallAsteroidsDestroyedToDate){
playSound(soundBuffer, WARNING_ALIEN_SOUND );
badGuysSummonedToDate++; //do not move this line to summonBadGuy(). It doesn't always work in there.
glutTimerFunc(0, summonBadGuy, smartiness(levelNumber) );
}
//Create new, smaller asteroids
if(oldAsteroidSize == ASTEROID_BIG){
asteroidsToRelease = asteroidReleaseSchedule[bigAsteroidsDestroyedToDate]; //schedule defined in startLevel()
//printf("Number New: %d\n",asteroidReleaseSchedule[bigAsteroidsDestroyedToDate]);
bigAsteroidsDestroyedToDate++;
}
else //This will happen on ASTEROID_MEDIUM
asteroidsToRelease = rand()%2+2; //just release a random number. No need to schedule these.
for(counter = 0; counter < asteroidsToRelease; counter++){
newAsteroid = spawnAsteroid(
oldAsteroidSize - 1,
asteroidToMovePtr->position.x + ( rand()%10 *pow(-1,rand()) ),
asteroidToMovePtr->position.y + ( rand()%10 *pow(-1,rand()) ),
asteroidToMovePtr->direction
);
asteroids->insertObject(newAsteroid);
}
#ifdef DEBUG_CRYSTALS
printf("Impacts: %d\n",unsmallAsteroidsDestroyedToDate);
#endif
unsmallAsteroidsDestroyedToDate++; //just a counter for unsmall (potentially crystal-causing) impacts
}
spawnKerblooie(
oldAsteroidSize + KERBLOOIE_SMALL, //so it sizes up from small, allowing us to have kerblooies smaller than 'small'
Asteroid::asteroidSizes[oldAsteroidSize]/2,
asteroidToMovePtr->color,
asteroidToMovePtr->position,
asteroidToMovePtr->direction,
&kerblooieList
);
asteroidListIterator.removeCurrentPosition(); //since it has been hit by a shot!
}
asteroidToMovePtr = static_cast<Asteroid*>(asteroidListIterator.nextObject());
}//end while
}
/****************************************************
* moveKerblooies
* adjusts all explosion particles appropriately
***************************************************/
void moveKerblooies(LinkedList<GameObject> * kerblooies, float movementScaleFactor){
Kerblooie *kerblooieToMovePtr;
float colorFade;
Iterator<GameObject> kerblooieListIterator(kerblooies);
kerblooieToMovePtr = static_cast<Kerblooie*>(kerblooieListIterator.nextObject());
while(kerblooieListIterator.atEnd() == false){
kerblooieToMovePtr->timeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
if(kerblooieToMovePtr->timeToLive > 0){
kerblooieToMovePtr->adjustCoordinate(movementScaleFactor);
colorFade = kerblooieToMovePtr->timeToLive / (float) kerblooieToMovePtr->lifespan;
kerblooieToMovePtr->color[3] = (GLubyte) floor( 255 * colorFade); //adjust alpha, which starts at 255
}
else{
kerblooieListIterator.removeCurrentPosition();
}
kerblooieToMovePtr = static_cast<Kerblooie*>(kerblooieListIterator.nextObject());
}
}
/****************************************************
* moveCrystals
* adjusts all crystals appropriately, killing those that have expired
***************************************************/
void moveCrystals(LinkedList<GameObject> * crystals, float movementScaleFactor){
Crystal *crystalToMovePtr;
Iterator<GameObject> crystalListIterator(crystals);
crystalToMovePtr = static_cast<Crystal *>(crystalListIterator.nextObject());
while(crystalListIterator.atEnd() == false){
crystalToMovePtr->timeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
isCrystalHit(crystalToMovePtr, &shotList); //First determine if the crystal is still alive
if(crystalToMovePtr->timeToLive > 0 && crystalToMovePtr->status.hitCode == CRYSTAL_NORMAL){
crystalToMovePtr->adjustCoordinate(movementScaleFactor);
crystalToMovePtr->rotationAngle = fmod(crystalToMovePtr->rotationAngle + crystalToMovePtr->rotationIncrement * movementScaleFactor, 360);
}
else{
if(crystalToMovePtr->status.hitCode == CRYSTAL_RETRIEVED)
playSound(soundBuffer, RETRIEVE_CRYSTAL_SOUND);
else{
if(crystalToMovePtr->status.hitCode == CRYSTAL_IMPACTED) //crystal shot
playSound(soundBuffer, CRYSTAL_SPLATTER_SOUND);
//else if(crystalToMovePtr->timeToLive <= 0)
spawnKerblooie(
KERBLOOIE_SMALL,
crystalToMovePtr->radius/2,
crystalToMovePtr->color,
crystalToMovePtr->position,
crystalToMovePtr->direction,
&kerblooieList );
}
crystalListIterator.removeCurrentPosition();
}
crystalToMovePtr = static_cast<Crystal *>(crystalListIterator.nextObject());
}
}
/****************************************************
* collideObjects
* an actual physics equation! (corrected as of version 1.2, Jul. 27, 2004)
* Note: 55% of velocity is lost in a collision. (not as in the physics equation!)
***************************************************/
void collideObjects(GameObject *hitter, GameObject *hittee){
Vector hitterInitialVelocity = hitter->direction; //initial values must be preserved, because they will be referenced in both equations
Vector hitteeInitialVelocity = hittee->direction;
static float dampendingFactor = 0.45;
hitter->direction.x = dampendingFactor * ( (hitter->mass - hittee->mass)*hitterInitialVelocity.x + 2 * hittee->mass * hitteeInitialVelocity.x) / (hitter->mass + hittee->mass);
hitter->direction.y = dampendingFactor * ( (hitter->mass - hittee->mass)*hitterInitialVelocity.y + 2 * hittee->mass * hitteeInitialVelocity.y) / (hitter->mass + hittee->mass);
hittee->direction.x = dampendingFactor * (2 * hitter->mass * hitterInitialVelocity.x + (hittee->mass - hitter->mass) * hitteeInitialVelocity.x) / (hitter->mass + hittee->mass);
hittee->direction.y = dampendingFactor * (2 * hitter->mass * hitterInitialVelocity.y + (hittee->mass - hitter->mass) * hitteeInitialVelocity.y) / (hitter->mass + hittee->mass);
}
/****************************************************
* idleByTimer
* controls animation on a periodic basis
* There are two ways to do animation:
* 1) in a tight idle loop--squeeze in as many
* frames as the processor can do.
* 2) on a periodic timer, so there is a maximum
* number of frames.
*
* This function allows for #2, since #1 consumes
* way more of the processor than is warranted for
* this simple game.
*
* Note: I tried to avoid this by using
* SLD_Delay/nanosleep, but it caused everything to
* become HUGELY unresponsive.
*
* controlled by TIGHT_IDLE_DRAWING
***************************************************/
void idleByTimer(int delayForThisTimer){
static int previousStartTime = 0; //time at beginning of previous calculation/draw cycle
int previousFrameCalcDrawTime;
int millisecondsTillNextFrame = 0;
//schedule delay until next frame based on *previous* frame's
//drawing/calculation time. (It's probably a pretty good estimate.
//We can't do the current frame because we don't know how long
//drawing is going to take.)
// = calcTime + drawTime
previousFrameCalcDrawTime = glutGet(GLUT_ELAPSED_TIME) - previousStartTime - delayForThisTimer;
if(previousFrameCalcDrawTime < minimumMillisecondsPerFrame){
millisecondsTillNextFrame = minimumMillisecondsPerFrame - previousFrameCalcDrawTime;
}
//mark the new time just before doing the calculations and drawing for the next frame.
previousStartTime = glutGet(GLUT_ELAPSED_TIME);
//Go!
if(paused == false){
idle(); //do all update calculations
glutTimerFunc(millisecondsTillNextFrame, idleByTimer, millisecondsTillNextFrame); //schedule the next frame
}
}//end idleByTimer
/****************************************************
* idle
* controls animation
***************************************************/
void idle(void){
static int previousSystemTime;
int timeForPreviousFrame;
unsigned int counter;
float movementScaleFactor;
timeForPreviousFrame = glutGet(GLUT_ELAPSED_TIME) - previousSystemTime;
movementScaleFactor = (float)timeForPreviousFrame/millisecondsPerStandardFrame;
movementScaleFactor = fmod(movementScaleFactor, 1);
//Record the new "previous system time" before doing all the movement calculations
previousSystemTime = glutGet(GLUT_ELAPSED_TIME);
//generic objects
if(shotList.isEmpty() == false){
moveShots(&shotList, movementScaleFactor);
findShotCollisions(&shotList);
}
if(asteroidList.isEmpty() == false)
moveAsteroids(&asteroidList, movementScaleFactor);
if( kerblooieList.isEmpty() == false )
moveKerblooies(&kerblooieList, movementScaleFactor);
if( crystalList.isEmpty() == false )
moveCrystals(&crystalList, movementScaleFactor);
//player operations
for(counter = 1; counter <= numberOfPlayers; counter++){
if(playerObjects[P(counter)].isEnabled() == true){
if(playerObjects[P(counter)].spaceship.rotating != NOT_ROTATING)
rotateShip(&(playerObjects[P(counter)].spaceship), movementScaleFactor);
if(playerObjects[P(counter)].spaceship.thrusting == true)
accelerateShip(&(playerObjects[P(counter)].spaceship), movementScaleFactor);
if(playerObjects[P(counter)].spaceship.decelerating == true)
decelerateShip(&(playerObjects[P(counter)].spaceship), movementScaleFactor);
moveSpaceShip(&(playerObjects[P(counter)].spaceship), movementScaleFactor);
}
}
//bad guy operations (also assesses damage, so must happen after shot updates, etc.)
updateBadGuys(&badGuyList, movementScaleFactor);
//assess damage to players (must be done after shots are moved)
for(counter = 1; counter <= numberOfPlayers; counter++){
if(playerObjects[P(counter)].isEnabled() == true){
impactShip(&playerObjects[P(counter)].spaceship, isShipHit(&(playerObjects[P(counter)].spaceship), &asteroidList, &shotList, &crystalList) );
}
}
//starts new level if needs be
if(asteroidList.isEmpty() && startingNewLevel == false){
glutTimerFunc(0, startLevel, levelNumber+1); //start new level after four seconds (handled inside function call)
startingNewLevel = true;
}
//windowing
glutPostRedisplay();
}
/****************************************************
* updateBadGuys
* moves badGuys and calls AI if necessary
***************************************************/
void updateBadGuys(LinkedList<GameObject> *badGuys, float movementScaleFactor){
BadGuy *currentBadGuy;
Iterator<GameObject> badGuyIterator(badGuys);
currentBadGuy = static_cast<BadGuy*>(badGuyIterator.nextObject());
while(badGuyIterator.atEnd() == false){
//First do all updating
if(currentBadGuy->rotating != NOT_ROTATING) //because rotation can be +1 or -1, *not* a boolean
rotateShip(currentBadGuy, movementScaleFactor);
if(currentBadGuy->thrusting == true)
accelerateShip(currentBadGuy, movementScaleFactor);
if(currentBadGuy->decelerating == true)
decelerateShip(currentBadGuy, movementScaleFactor);
//Rotation
currentBadGuy->rotationTimeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
if(currentBadGuy->rotationTimeToLive <= 0)
currentBadGuy->rotating = NOT_ROTATING;
//Thrust
currentBadGuy->thrustTimeToLive -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
if(currentBadGuy->thrustTimeToLive <= 0 && currentBadGuy->thrusting == true){
currentBadGuy->thrusting = false;
currentBadGuy->drawThrustUntil = glutGet( GLUT_ELAPSED_TIME ) + FADEOUTS;
playSound(soundBuffer, STOP_THRUSTING_SOUND);
}
moveSpaceShip(currentBadGuy, movementScaleFactor);
impactShip(currentBadGuy, isShipHit(currentBadGuy, &asteroidList, &shotList, &crystalList) );
//wipe him out if necessary
if(currentBadGuy->strength <= 0)
badGuyIterator.removeCurrentPosition();
else{
//Do AI, if necessary
currentBadGuy->timeToNextUpdate -= (int) (millisecondsPerStandardFrame * movementScaleFactor);
if(currentBadGuy->timeToNextUpdate <= 0){
doAI(currentBadGuy);
currentBadGuy->timeToNextUpdate = (FRAMES_PER_SECOND * millisecondsPerStandardFrame) / (currentBadGuy->smartiness);
}
}
//get the next bad guy in the badGuys list
currentBadGuy = static_cast<BadGuy*>(badGuyIterator.nextObject()); //gets the next bad guy in the badGuys list
}//end while
}
/****************************************************
* doAI
* calculates so-called "intelligence" for a bad guy
* the Idea:
*
* find closest player
* rotate ship to align with player
* get dot product
* set rotationScaleFactor = 1
* thrust to player
* player in range?
* fire shot
*
***************************************************/
void doAI(BadGuy *badGuy){
int counter;
float distance;
float distanceToPlayer = FRAMEHEIGHT*FRAMEWIDTH; //highball the number so that the actual distance will be smaller
int playerToAttack = 0; //an invalid player number
Vector vectorToPlayer;
Vector badGuyNoseVector; //the direction the nose is pointing in
double angleBetweenBadGuyNoseAndDirection;
double angleToPlayer;
float shotSpeed; //in pixels per frame
float shotRange;
//find closest player
for(counter = 1; counter <= numberOfPlayers; counter++){
if(playerObjects[P(counter)].isEnabled() == true){
distance = distanceBetween(badGuy->position, playerObjects[P(counter)].spaceship.position);
if(distance < distanceToPlayer){
distanceToPlayer = distance;
playerToAttack = counter;
}
}
}//end minimum distance calculation
if(playerToAttack != 0){ //then a valid player does exist. Note that there may not always be a player on the screen!
//Get Angle Between ships
vectorToPlayer.x = playerObjects[P(playerToAttack)].spaceship.position.x - badGuy->position.x;
vectorToPlayer.y = playerObjects[P(playerToAttack)].spaceship.position.y - badGuy->position.y;
badGuyNoseVector.x = badGuy->radius * cos( radians(badGuy->rotationAngle) );
badGuyNoseVector.y = badGuy->radius * sin( radians(badGuy->rotationAngle) );
angleToPlayer = degrees( angleBetweenVectors(badGuyNoseVector, vectorToPlayer) );
angleBetweenBadGuyNoseAndDirection = degrees(angleBetweenVectors(badGuyNoseVector, badGuy->direction) );
//Rotate into alignment
if(angleToPlayer != 0){
badGuy->rotating = (short) -(badGuyNoseVector.x * vectorToPlayer.y - badGuyNoseVector.y * vectorToPlayer.x); //this is the k-term of a cross product. The direction it points is the opposite of my clockwise/counterclockwise convention!
if(badGuy->rotating != NOT_ROTATING)
badGuy->rotating = badGuy->rotating/abs(badGuy->rotating); //normalize to either 1 or -1
}
badGuy->rotationScaleFactor = 1 + levelNumber/100.0;
badGuy->rotationTimeToLive = (int) (angleToPlayer/(ROTATION_ANGLE_PER_FRAME*badGuy->rotationScaleFactor) * millisecondsPerStandardFrame);
//printf("Doing AI: angle to player %d: %f; rotating: %d, timeToRotate: %d\n", playerToAttack, angleToPlayer, badGuy->rotating, badGuy->rotationTimeToLive);
//Calculate shot range
shotSpeed = sqrt( 2*pow(badGuy->strength,2) );
shotRange = shotSpeed * FRAMES_PER_SECOND * SHOT_LIFESPAN / 1000; //the 1000 is because SHOT_LIFESPAN is in milliseconds
//Thrust to Player
if(distanceToPlayer > shotRange &&
angleToPlayer < 20 &&
(angleBetweenBadGuyNoseAndDirection > 10 ||
magnitudeOfVector(badGuy->direction) < 0.25*shotSpeed )
){
badGuy->thrustTimeToLive = 62 + rand()%62;
badGuy->thrusting = true;
}
//ATTACK!
if(1.25*shotRange > distanceToPlayer && angleToPlayer < 10){
fireShot(badGuy);
}
}//end valid player check
}//end AI function
/****************************************************
* fireShot
* fires a shot by the designated spaceship
***************************************************/
void fireShot(Spaceship * player){
Shot *newshot;
newshot = new Shot;
if(player->playerNumber > 0)
playSound(soundBuffer, POP_SOUND);
else
playSound(soundBuffer, POP_ALIEN_SOUND);
newshot->owner = player->playerNumber;
newshot->timeToLive = SHOT_LIFESPAN; //1 second
newshot->impacted = false;
newshot->position.x = player->position.x +
player->radius*cos(player->rotationAngle * PI/180 ) *1.125; //move the shot away from the ship
newshot->position.y = player->position.y +
player->radius*sin(player->rotationAngle * PI/180 ) *1.125;
newshot->direction.x = player->direction.x +
player->strength* cos(player->rotationAngle * PI/180);
newshot->direction.y = player->direction.y +
player->strength* sin(player->rotationAngle * PI/180);
newshot->mass = 1;
newshot->radius = SHOT_RADIUS;
newshot->color[0] = player->color[0];
newshot->color[1] = player->color[1];
newshot->color[2] = player->color[2];
if(player->playerNumber > 0)
playerObjects[P(player->playerNumber)].score -= levelNumber; //it costs you to shoot!
shotList.insertObject(newshot);
}
/****************************************************
* findShotCollisions
* test all shots for collisions with each other
* if your shot is hit, you get the points for firing it back
* creates explosions for impacted shots here
***************************************************/
void findShotCollisions(LinkedList<GameObject> *shots){
Shot *shotToTest;
Iterator<GameObject> shotListIterator(shots);
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
while(shotListIterator.atEnd() == false){
if(shotToTest->impacted == false)
isShotHitByShots(shotToTest, new Iterator<GameObject>(shots, shotListIterator.getCurrentNode()) ); //only tests this shot against shots that haven't been tested yet
if(shotToTest->impacted == true){
playSound(soundBuffer, SHOT_TUNK_SOUND);
spawnKerblooie(KERBLOOIE_INFINITESIMAL, shotToTest->radius, shotToTest->color, shotToTest->position, shotToTest->direction, &kerblooieList);
if(shotToTest->owner > 0)
playerObjects[P(shotToTest->owner)].score += levelNumber; //you get your deposit back
}
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
}
}
/****************************************************
* isShotHitByShots
* test this shot for collisions all the other shots in this iterator
* sets the impacted flag if it is hit
* also returns flag specifying a hit or not
***************************************************/
bool isShotHitByShots(Shot *shotToTest, Iterator<GameObject> *shotComparisonIterator){
Shot *shotToCompare;
bool isHit = false;
shotToCompare = static_cast<Shot *>(shotComparisonIterator->nextObject());
while(shotComparisonIterator->atEnd() == false){
// if(distanceBetween(shotToTest->position, shotToCompare->position) <= shotToCompare->radius*1.75){ //I let the shots enter each other a little bit for visual effect
if(shotToTest->intersectsWith(shotToCompare)){ //we could do it the old way above, but this is less apt to "miss"
shotToTest->impacted = true;
shotToCompare->impacted = true; //these two shots have collided
collideObjects(shotToTest, shotToCompare);
}
shotToCompare = static_cast<Shot *>(shotComparisonIterator->nextObject());
}
return isHit;
}
/****************************************************
* isCrystalHit
* returns true if the crystal has been hit by a shot
* the shot that hit the crystal is flagged for deletion from the list
***************************************************/
HitData isCrystalHit(Crystal *crystal, LinkedList<GameObject> *shots){
Shot *shotToTest;
HitData isHit;
Iterator<GameObject> shotListIterator(shots);
isHit.hitCode = false;
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
while(shotListIterator.atEnd() == false && isHit.hitCode == false){
if(crystal->intersectsWith(shotToTest) && shotToTest->impacted == false){
isHit.hitCode = CRYSTAL_IMPACTED;
isHit.mass = shotToTest->mass;
isHit.direction = shotToTest->direction;
shotToTest->impacted = true;
crystal->status = isHit;
collideObjects(shotToTest, crystal);
}
else
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
}
return isHit;
}
/****************************************************
* isAsteroidHit
* returns true if the asteroid has been hit by a shot
* the shot that hit the asteroid is flagged for deletion from the list
***************************************************/
HitData isAsteroidHit(Asteroid *asteroid, LinkedList<GameObject> *shots){
Shot *shotToTest;
HitData isHit;
int shotOwner;
Iterator<GameObject> shotListIterator(shots);
isHit.hitCode = false;
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
while(shotListIterator.atEnd() == false && isHit.hitCode == false){
if( asteroid->intersectsWith(shotToTest) ){ //a hit!
isHit.hitCode = true;
isHit.mass = shotToTest->mass;
isHit.direction = shotToTest->direction;
shotToTest->impacted = true;
asteroid->impacted = isHit;
#ifdef DEBUG_SHOTS
printf("Shot before impact: <%f, %f>\n", shotToTest->direction.x, shotToTest->direction.y);
#endif
collideObjects( shotToTest, asteroid );
#ifdef DEBUG_SHOTS
printf("Shot after impact: <%f, %f>\n", shotToTest->direction.x, shotToTest->direction.y);
#endif
//Scoring:
shotOwner = shotToTest->owner;
if(shotOwner > 0){
if(playerObjects[P(shotOwner)].spaceship.strength > 0)
playerObjects[P(shotOwner)].score +=
( abs(asteroid->size - 3) +
playerObjects[P(shotOwner)].spaceship.maxStrength /
playerObjects[P(shotOwner)].spaceship.strength )
* levelNumber;
else
playerObjects[P(shotOwner)].score +=
( abs(asteroid->size - 3) +
playerObjects[P(shotOwner)].spaceship.maxStrength )
* levelNumber;
}
}
else
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
}//end while
return isHit;
}
/****************************************************
* isShipHit
* returns int for amount by which to decrease ship strength
* -> 1 for a shot, otherwise dependent on asteroid size
* the shot that hit the ship is flagged for deletion from the list
***************************************************/
HitData isShipHit(Spaceship *shipPtr, LinkedList<GameObject> *asteroids, LinkedList<GameObject> *shots, LinkedList<GameObject> *crystals){
Crystal *crystalToTest;
Shot *shotToTest;
Asteroid *asteroidToTest;
HitData isHit; //how much impact did the ship absorb?
int shotOwner;
int playerNumber = shipPtr->playerNumber;
int scoreAssessed = 0;
Iterator<GameObject> shotListIterator(shots);
Iterator<GameObject> crystalListIterator(crystals);
Iterator<GameObject> asteroidListIterator(asteroids);
isHit.hitCode = 0; //Stores the number of impacts sustained; no hits yet
isHit.mass = 0;
isHit.direction.x = 0;
isHit.direction.y = 0;
//Test crystals for intersection
if( shipPtr->invinciblityTimeToLive <= 0 ){ //non-invincible players
crystalToTest = static_cast<Crystal *>(crystalListIterator.nextObject());
while(crystalListIterator.atEnd() == false && isHit.hitCode == false){
if(shipPtr->intersectsWith(crystalToTest)){
crystalToTest->status.hitCode = CRYSTAL_RETRIEVED;
//Assess result of crystal collection
switch(crystalToTest->crystalFlavor){
case CRYSTAL_SHIELDPOWER:
playSound(soundBuffer, RETRIEVE_CRYSTAL_SOUND);
shipPtr->strength++;
if(playerNumber > 0){
/*Code required to give extra life after exceeding max strength (not used)
if(playerObjects[P(playerNumber)].spaceship.strength > playerMaxStrength[P(playerNumber)]){
playerObjects[P(playerNumber)].spaceship.strength %= playerMaxStrength[P(playerNumber)];
playerObjects[P(playerNumber)].lives++;
}*/
if(playerObjects[P(playerNumber)].spaceship.strength > playerObjects[P(playerNumber)].spaceship.maxStrength*(1+OVERLOAD_FACTOR) )
isHit.hitCode = playerObjects[P(playerNumber)].spaceship.strength; //destroy players who overload their shields
}
break;
}
}
crystalToTest = static_cast<Crystal *>(crystalListIterator.nextObject());
}//end while
}//end crystal search
//Test shots for impact
shotToTest = static_cast<Shot *>(shotListIterator.nextObject());
while(shotListIterator.atEnd() == false && isHit.hitCode == false){
if(shipPtr->intersectsWith(shotToTest)){
collideObjects(shotToTest, shipPtr);
isHit.mass += shotToTest->mass;
isHit.hitCode++;
shotToTest->impacted = true;
//Scoring:
shotOwner = shotToTest->owner;
//Don't award points for shooting oneself.