-
Notifications
You must be signed in to change notification settings - Fork 0
/
spacewar.cpp
1323 lines (1128 loc) · 40.2 KB
/
spacewar.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
// Programming 2D Games
// Copyright (c) 2011 by:
// Charles Kelly
// spacewar.cpp Scrolling Bitmap Demo
// This class is the core of the game
#include "spaceWar.h"
//=============================================================================
// Constructor
//=============================================================================
Spacewar::Spacewar()
{
menuOn = true;
countDownOn = false;
roundOver = false;
myfile.open("spacewar.log");
}
//=============================================================================
// Destructor
//=============================================================================
Spacewar::~Spacewar()
{
releaseAll(); // call onLostDevice() for every graphics item
myfile.close();
}
//=============================================================================
// Initializes the game
// Throws GameError on error
//=============================================================================
void Spacewar::initialize(HWND hwnd)
{
Game::initialize(hwnd); // throws GameError
// initialize DirectX fonts
fontBig.initialize(graphics, spacewarNS::FONT_BIG_SIZE, false, false, spacewarNS::FONT);
fontBig.setFontColor(spacewarNS::FONT_COLOR);
// menu texture
if (!menuTexture.initialize(graphics,MENU_IMAGE))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing menu texture"));
// space texture
if (!spaceTexture.initialize(graphics,SPACE_IMAGE))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing space texture"));
// planet texture
if (!planetTexture.initialize(graphics, PLANET_IMAGE))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing planet texture"));
// game textures
if (!textures1.initialize(graphics,TEXTURES1_IMAGE))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing game textures1"));
if (!textures2.initialize(graphics,TEXTURES2_IMAGE))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing game textures2"));
// boss1 textures
if(!boss1Texture.initialize(graphics, BOSS_IMAGE))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing boss1 texture"));
// menu image
if (!menu.initialize(graphics,0,0,0,&menuTexture))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing menu"));
// space image
if (!space.initialize(graphics,0,0,0,&spaceTexture))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing space"));
space.setScale((float)SPACE_SCALE);
// planet image
if (!planetSurface.initialize(graphics,0,0,0,&planetTexture))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing planet surface"));
//planetSurface.setScale((float)SPACE_SCALE);
// todo: please remove this after testing
if(!powerUp.initialize(this,powerUpNS::WIDTH,powerUpNS::HEIGHT,powerUpNS::TEXTURE_COLS,&textures2))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing asteroid"));
// asteroid image. todo: remove this. For testing purposes only
/*if(!asteroid.initialize(this,asteroidNS::WIDTH,asteroidNS::HEIGHT,asteroidNS::TEXTURE_COLS,&textures1))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing asteroid"));
asteroid.setFrames(asteroidNS::ASTEROID1_START_FRAME, asteroidNS::ASTEROID1_END_FRAME);
asteroid.setCurrentFrame(asteroidNS::ASTEROID1_START_FRAME);*/
// ship1
if (!ship1.initialize(this,shipNS::WIDTH,shipNS::HEIGHT,shipNS::TEXTURE_COLS,&textures1))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing ship1"));
ship1.setFrames(shipNS::SHIP1_START_FRAME, shipNS::SHIP1_END_FRAME);
ship1.setCurrentFrame(shipNS::SHIP1_START_FRAME);
ship1.setColorFilter(SETCOLOR_ARGB(255,230,230,255)); // light blue, used for shield and torpedo
ship1.setMass(shipNS::MASS);
// Start ship in center
ship1.setX(GAME_WIDTH/2 - shipNS::WIDTH);
ship1.setY(GAME_HEIGHT - shipNS::HEIGHT);
ship1.setDegrees(270);
fireTimer = 0;
rushTimer = spacewarNS::RUSH_TIMER_MAX;
////////////////////////////////////////
// todo: for testing purposes
/*if (!missile.initialize(this, missileNS::WIDTH, missileNS::HEIGHT, missileNS::TEXTURE_COLS, &textures1))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing missile"));
missile.setFrames(missileNS::START_FRAME, missileNS::END_FRAME);
missile.setCurrentFrame(missileNS::START_FRAME);
missile.setColorFilter(SETCOLOR_ARGB(255,230,230,255)); // light blue, used for shield and torpedo
// Start missile at top
missile.setX(GAME_WIDTH/2);
missile.setY(GAME_HEIGHT/2);
missile.setTarget(GAME_WIDTH/2, GAME_HEIGHT/2, &ship1);
*/
////////////////////////////////////////////
// have this set to false, then to true when appropriate
asteroidsOn = false;
asteroidSpawnTimer = 0.0f;
asteroidDuration = 0.0f;
// keeps track of which obstacle we are on
obstacleInd = 0;
nextWaveReady = true;
enemySpawnSide = spacewarNS::RIGHT;
enemyMissileSpawnSide = spacewarNS::LEFT;
shipSpawnXLoc = 0.0f;
blackHoleTimer = spacewarNS::MAX_BLACK_HOLE_TIME;
// todo: this is here for testing. Change it so it spawns the planet when necessary
//initiatePlanet();
initiateBlackHole();
// todo: temporary. For proof of concept. Modify later
// todo: comment back in. Commented out to test asteroid functionality
//initiateEnemyShips(1/*16*/);
// todo: temporary. For proof of concept. Modify later
//initiateEnemyMissileShips(8);
// todo: just for testing. Remove once randomization is in place
//worldSequence.push_back(spacewarNS::ASTEROIDS);
//worldSequence.push_back(spacewarNS::SHIPS);
//worldSequence.push_back(spacewarNS::SHIPS);
//worldSequence.push_back(spacewarNS::ASTEROIDS);
//worldSequence.push_back(spacewarNS::PLANET);
//worldSequence.push_back(spacewarNS::SHIPS);
generator = std::default_random_engine(static_cast<unsigned int>(time(0)));
distributionObstacle = std::uniform_int_distribution<int>(1, 100);
distributionEnemySpawnLoc = std::uniform_int_distribution<int>(1,4);
generateWorldSequence(10);
currObstacle = worldSequence[obstacleInd];
planetSurfaceMode = false;
}
//=============================================================================
// Start a new round of play
//=============================================================================
void Spacewar::roundStart()
{
space.setX(0);
space.setY(0);
// Start ship in center
ship1.setX(GAME_WIDTH/2 - shipNS::WIDTH);
ship1.setY(GAME_HEIGHT - shipNS::HEIGHT);
countDownTimer = spacewarNS::COUNT_DOWN;
countDownOn = true;
roundOver = false;
}
//=============================================================================
// Update all game items
//=============================================================================
void Spacewar::update()
{
if (menuOn)
{
if (input->anyKeyPressed())
{
menuOn = false;
input->clearAll();
roundStart();
}
}
else if(countDownOn)
{
countDownTimer -= frameTime;
if(countDownTimer <= 0)
{
countDownOn = false;
}
}
else // here check if planet flag is true or not. If not, do the below, else if it is then get next obstacle for planet
{
if(obstacleInd < worldSequence.size())
{
if(planetSurfaceMode)
{
if(planetObstacleInd < planetSequence.size())
{
if(currPlanetObstacle == spacewarNS::PLANET_SHIPS)
{
if(nextWaveReady)
{
initiateEnemyShips(16);
nextWaveReady = false;
}
else if(enemyShips.empty())
{
// this obstacle is finished. Tell spacewar to move onto the next one
planetObstacleInd++;
if(planetObstacleInd < planetSequence.size())
{
currPlanetObstacle = planetSequence[planetObstacleInd];
}
nextWaveReady = true;
}
}
// note: more planet obstacles put here later
}
else
{
// clean up any loose objects
// note: may be more to clean up later
deleteAllLasers();
// planet traversing is done. Go back to space
planetSurfaceMode = false;
nextWaveReady = false;
}
}
else
{
// check which new obstacle to create if any yet
if (currObstacle == spacewarNS::SHIPS)
{
if(nextWaveReady)
{
initiateEnemyShips(16);
initiateEnemyMissileShips(8);
nextWaveReady = false;
}
else if(enemyShips.empty())
{
// if LEVELS_BEFORE_POWER_UP obstacles have been generated and the player has no power ups and there is no powere up pellet on the screen,
// then there is a chance to initiate a new power up
if ((obstacleInd + 1) % spacewarNS::LEVELS_BEFORE_POWER_UP == 0 && !ship1.getShieldOn() && !blackHole.getActive() && !powerUp.getActive())
{
if(!powerUp.initialize(this,powerUpNS::WIDTH,powerUpNS::HEIGHT,powerUpNS::TEXTURE_COLS,&textures2))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing asteroid"));
}
// this obstacle is finished. Tell spacewar to move onto the next one
obstacleInd++;
if(obstacleInd < worldSequence.size())
{
currObstacle = worldSequence[obstacleInd];
}
nextWaveReady = true;
}
}
else if (currObstacle == spacewarNS::ASTEROIDS)
{
if(nextWaveReady)
{
asteroidsOn = true;
nextWaveReady = false;
asteroidDuration = spacewarNS::ASTEROID_TOTAL_DURATION;
}
else if(asteroidDuration <= 0.0f)
{
// if LEVELS_BEFORE_POWER_UP obstacles have been generated and the player has no power ups and there is no powere up pellet on the screen,
// then there is a chance to initiate a new power up
if ((obstacleInd + 1) % spacewarNS::LEVELS_BEFORE_POWER_UP == 0 && !ship1.getShieldOn() && !blackHole.getActive() && !powerUp.getActive())
{
if(!powerUp.initialize(this,powerUpNS::WIDTH,powerUpNS::HEIGHT,powerUpNS::TEXTURE_COLS,&textures2))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing asteroid"));
}
// this obstacle is finished. Tell spacewar to move onto the next one
obstacleInd++;
if(obstacleInd < worldSequence.size())
{
currObstacle = worldSequence[obstacleInd];
}
asteroidsOn = false;
nextWaveReady = true;
}
}
else if(currObstacle == spacewarNS::PLANET)
{
if(nextWaveReady)
{
initiatePlanet();
nextWaveReady = false;
}
else if(!planet.getActive())
{
// if LEVELS_BEFORE_POWER_UP obstacles have been generated and the player has no power ups and there is no powere up pellet on the screen,
// then there is a chance to initiate a new power up
if ((obstacleInd + 1) % spacewarNS::LEVELS_BEFORE_POWER_UP == 0 && !ship1.getShieldOn() && !blackHole.getActive() && !powerUp.getActive())
{
if(!powerUp.initialize(this,powerUpNS::WIDTH,powerUpNS::HEIGHT,powerUpNS::TEXTURE_COLS,&textures2))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing asteroid"));
}
// this obstacle is finished. Tell spacewar to move onto the next one
obstacleInd++;
if(obstacleInd < worldSequence.size())
{
currObstacle = worldSequence[obstacleInd];
}
nextWaveReady = true;
}
}
}
}
if(rushTimer <= 0.0f)
{
// rush timer should be reset
rushTimer = spacewarNS::RUSH_TIMER_MAX;
// set one of the ships' rush mode to true if any are eligible for this
findAndSetRushReadyShip();
}
else
{
// time remaining until one of the enemy ships should rush the player
rushTimer -= frameTime;
}
// set all the rushing enemy ship's direction with respect to the player's ship
setAllEnemyShipRushDirection();
if (ship1.getActive())
{
if(fireTimer >= 0)
{
fireTimer -= frameTime; // time remaining until fire enabled
}
if (input->isKeyDown(W_KEY) || input->getGamepadDPadUp(0)) // if thrust forward
{
ship1.setForwardThrustOn(true);
}
else
{
ship1.setForwardThrustOn(false);
}
if(input->isKeyDown(A_KEY) || input->getGamepadDPadLeft(0)) // if move left
{
ship1.setLeftThrustOn(true);
}
else
{
ship1.setLeftThrustOn(false);
}
if(input->isKeyDown(D_KEY) || input->getGamepadDPadRight(0)) // if move right
{
ship1.setRightThrustOn(true);
}
else
{
ship1.setRightThrustOn(false);
}
if(input->isKeyDown(S_KEY) || input->getGamepadDPadDown(0))
{
ship1.setBackwardThrustOn(true);
}
else
{
ship1.setBackwardThrustOn(false);
}
if(input->isKeyDown(SHIP1_FIRE_KEY2))
{
if(fireTimer <= 0.0f) // if ready to fire
{
Laser* newPlayerLaser = new Laser();
initializeLaser(newPlayerLaser);
newPlayerLaser->fire(&ship1);
playerLasers.push_back(newPlayerLaser);
fireTimer = spacewarNS::FIRE_DELAY; // delay firing
}
}
}
//initialize asteroid if enough time has passed
if(asteroidsOn)
{
asteroidSpawnTimer -= frameTime;
if(asteroidSpawnTimer <= 0.0f)
{
initiateAnAsteroid();
asteroidSpawnTimer = spacewarNS::ASTEROID_SPAWN_DELAY;
}
asteroidDuration -= frameTime;
}
// check if any of the enemy ships are ready to fire
for(std::list<EnemyShip*>::iterator it=enemyShips.begin(); it != enemyShips.end(); /*++it*/)
{
// check which enemy ships have been destroyed or todo: left the screen
if(!(*it)->getActive() && !(*it)->getVisible())
{
SAFE_DELETE(*it);
it = enemyShips.erase(it);
}
// check which enemy ships are ready to fire
else
{
if( (*it)->getAmmoReady() )
{
// todo: if statement to initialize based on weapon type
if((*it)->getWeaponType() == 0)
{
// initiate a laser
Laser* newEnemyLaser = new Laser();
initializeLaser(newEnemyLaser, false);
// fire the enemy laser
newEnemyLaser->fire(*it, &ship1);
// store this laser in the list so we can update it, along with the other lasers, later
enemyProjectiles.push_back(newEnemyLaser);
(*it)->setFireTimer(shipNS::FIRE_DELAY);
}
else if((*it)->getWeaponType() == 1)
{
// initiate a missile
Missile* newEnemyMissile = new Missile();
initializeMissile(newEnemyMissile);
// fire the enemy missile
newEnemyMissile->setTarget((*it)->getCenterX(), (*it)->getCenterY(), &ship1);
// store this missile in the list so we can update it, along with the other missiles, later
enemyProjectiles.push_back(newEnemyMissile);
(*it)->setFireTimer(enemyMissileShipNS::FIRE_DELAY);
}
// reset the fire delay for this enemy ship
(*it)->setAmmoReady(false);
}
++it;
}
}
ship1.setVelocity(VECTOR2(0,0));
ship1.gravityConstantForce(&planet, frameTime);
// Update the entities
ship1.update(frameTime);
for(std::list<EnemyShip*>::iterator it=enemyShips.begin(); it != enemyShips.end(); ++it)
{
(*it)->gravityConstantForce(&blackHole, frameTime);
(*it)->update(frameTime);
}
for(std::list<Laser*>::iterator it=playerLasers.begin(); it != playerLasers.end(); ++it)
{
(*it)->update(frameTime);
}
for(std::list<Entity*>::iterator it=enemyProjectiles.begin(); it != enemyProjectiles.end(); ++it)
{
(*it)->update(frameTime);
}
for(std::list<Asteroid*>::iterator it=asteroids.begin(); it != asteroids.end(); /*++it*/)
{
if((*it)->getY() > GAME_HEIGHT)
{
SAFE_DELETE(*it);
it = asteroids.erase(it);
}
else
{
(*it)->update(frameTime);
++it;
}
}
planet.update(frameTime);
if (blackHole.getActive())
{
blackHoleTimer -= frameTime;
if(blackHoleTimer <= 0.0f)
{
blackHole.setActive(false);
blackHole.setVisible(false);
EnemyShip::setBlackHoleActive(false);
}
}
blackHole.update(frameTime);
powerUp.update(frameTime);
if(planetSurfaceMode)
{
wrapImage(planetSurface, PLANET_SURFACE_WIDTH, PLANET_SURFACE_HEIGHT);
}
else
{
wrapImage(space, SPACE_WIDTH, SPACE_HEIGHT);
}
deleteDestroyedLasers();
deleteOutOfBoundsShips();
if(roundOver)
{
roundTimer -= frameTime;
if(roundTimer <= 0)
roundStart();
}
}
}
//=============================================================================
// Artificial Intelligence
//=============================================================================
void Spacewar::ai()
{}
//=============================================================================
// Handle collisions
//=============================================================================
void Spacewar::collisions()
{
VECTOR2 collisionVector;
powerUpNS::POWER_UP_TYPE powerType;
// detect if the enemy's ship has been hit with a player's laser
for(std::list<Laser*>::iterator itPlayerLaser=playerLasers.begin(); itPlayerLaser != playerLasers.end(); ++itPlayerLaser)
{
for(std::list<EnemyShip*>::iterator itEnemyShip=enemyShips.begin(); itEnemyShip != enemyShips.end(); ++itEnemyShip)
{
// if collision between a player laser and an enemy ship
if((*itPlayerLaser)->collidesWith(**itEnemyShip, collisionVector))
{
(*itEnemyShip)->explode();
(*itPlayerLaser)->setActive(false);
// ??? maybe need this for optimization???: since this laser has been destroyed, break out of this loop to check with the next laser
//break;
}
}
for(std::list<Entity*>::iterator itEnemyProjectiles=enemyProjectiles.begin(); itEnemyProjectiles != enemyProjectiles.end(); ++itEnemyProjectiles)
{
if((*itPlayerLaser)->collidesWith(**itEnemyProjectiles, collisionVector) && (*itEnemyProjectiles)->getDestroyable())
{
(*itEnemyProjectiles)->setHealth((*itEnemyProjectiles)->getHealth() - 50.0f);
(*itPlayerLaser)->setActive(false);
}
}
}
// detect if the player's ship has been hit with an enemy laser
for(std::list<Entity*>::iterator itEnemyLaser=enemyProjectiles.begin(); itEnemyLaser != enemyProjectiles.end(); ++itEnemyLaser)
{
// if collision between ship1 and an enemy laser
if((*itEnemyLaser)->collidesWith(ship1, collisionVector))
{
ship1.explode();
(*itEnemyLaser)->setActive(false);
// ??? maybe need this for optimization???: since this laser has been destroyed, break out of this loop to check with the next laser
//break;
}
}
// check if an enemy ship has collided with the player ship or if any enemy ships have collided with a black hole
for(std::list<EnemyShip*>::iterator itEnemyShip=enemyShips.begin(); itEnemyShip != enemyShips.end(); ++itEnemyShip)
{
// if collision between player ship and enemy ship
if((*itEnemyShip)->collidesWith(ship1, collisionVector))
{
ship1.explode();
(*itEnemyShip)->explode();
}
// check if collision between enemy ship and black hole
if((*itEnemyShip)->collidesWith(blackHole, collisionVector))
{
(*itEnemyShip)->explode();
}
}
// check if an asteroid collided with the player ship
for(std::list<Asteroid*>::iterator itAsteroids=asteroids.begin(); itAsteroids != asteroids.end(); ++itAsteroids)
{
// if collision between player ship and asteroids
if((*itAsteroids)->collidesWith(ship1, collisionVector))
{
ship1.explode();
}
}
// check for collisions between asteroids
for(std::list<Asteroid*>::iterator itAsteroids=asteroids.begin(); itAsteroids != asteroids.end(); ++itAsteroids)
{
std::list<Asteroid*>::iterator itOtherAsteroids = itAsteroids;
++itOtherAsteroids;
for(; itOtherAsteroids != asteroids.end(); ++itOtherAsteroids)
{
if((*itAsteroids)->collidesWith(**itOtherAsteroids, collisionVector))
{
if((*itAsteroids)->bounce(collisionVector, **itOtherAsteroids))
{
(*itOtherAsteroids)->bounce(collisionVector*-1, **itAsteroids);
}
}
}
}
// check if the player's ship is colliding with the planet
if(ship1.collidesWith(planet, collisionVector))
{
// signal to transition to flying in planet's atmosphere
planetSurfaceMode = true;
planetObstacleInd = 0;
// set the next wave to be ready, i.e. the signal that the first wave on the planet is ready to come out
nextWaveReady = true;
//move planet off screen and deactivate it
planet.setY((float)GAME_HEIGHT);
planet.setActive(false);
// clean up any remaining objects before transitioning if there are any
deleteAllLasers();
deleteAllAsteroids();
// generate planet's sequence of obstacles
generatePlanetSequence(2); // todo: change value. 5 is just for testing for now.
// position ship at middle bottom of screen to avoid enemies spawning on top of the ship
ship1.setX((GAME_WIDTH/2.0f) - (ship1.getWidth()/2.0f));
ship1.setY(GAME_HEIGHT*0.90f);
currPlanetObstacle = planetSequence[planetObstacleInd];
}
// check if the player ship has collided with a power up pellet
if (ship1.collidesWith(powerUp, collisionVector))
{
powerType = powerUp.getType();
if(powerType == powerUpNS::INVINCIBILITY)
{
// invincibility shield
ship1.setInvincibilityTimer(shipNS::MAX_INVINCIBILITY_TIME);
ship1.setShieldOn(true);
}
else
{
// black hole
blackHole.setActive(true);
blackHole.setVisible(true);
EnemyShip::setBlackHoleActive(true);
blackHoleTimer = spacewarNS::MAX_BLACK_HOLE_TIME;
}
// deactivate power up pellet
powerUp.setActive(false);
powerUp.setVisible(false);
}
}
//=============================================================================
// Render game items
//=============================================================================
void Spacewar::render()
{
graphics->spriteBegin(); // begin drawing sprites
if(planetSurfaceMode)
{
fillRestOfBackdrop(planetSurface, PLANET_SURFACE_WIDTH, PLANET_SURFACE_HEIGHT);
}
else
{
fillRestOfBackdrop(space, SPACE_WIDTH, SPACE_HEIGHT);
}
for(std::list<Laser*>::iterator it=playerLasers.begin(); it != playerLasers.end(); ++it)
{
(*it)->draw(graphicsNS::FILTER); // draw the player lasers using colorFilter
}
for(std::list<Entity*>::iterator it=enemyProjectiles.begin(); it != enemyProjectiles.end(); ++it)
{
/*time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time (&rawtime);
timeinfo = localtime (&rawtime);
strftime (buffer,80,"%I:%M:%S%p.",timeinfo);
myfile << buffer;
myfile << " - drawing enemy projectile\n";
*/
(*it)->draw(); // draw the enemy projectiles using colorFilter
}
for(std::list<EnemyShip*>::iterator it=enemyShips.begin(); it != enemyShips.end(); ++it)
{
(*it)->draw(); // draw the enemy ships
}
for(std::list<Asteroid*>::iterator it=asteroids.begin(); it != asteroids.end(); ++it)
{
(*it)->draw(); // draw the asteroids
}
planet.draw();
blackHole.draw();
powerUp.draw();
ship1.draw(); // draw the spaceship
if(menuOn)
menu.draw();
if(countDownOn)
{
_snprintf_s(buffer, spacewarNS::BUF_SIZE, "%d", (int)(ceil(countDownTimer)));
fontBig.print(buffer,spacewarNS::COUNT_DOWN_X,spacewarNS::COUNT_DOWN_Y);
}
graphics->spriteEnd(); // end drawing sprites
}
//=============================================================================
// The graphics device was lost.
// Release all reserved video memory so graphics device may be reset.
//=============================================================================
void Spacewar::releaseAll()
{
menuTexture.onLostDevice();
spaceTexture.onLostDevice();
textures1.onLostDevice();
fontScore.onLostDevice();
fontBig.onLostDevice();
deleteAllLasers();
deleteAllEnemyShips();
deleteAllAsteroids();
EnemyShip::deleteEnemyShipGrid();
Game::releaseAll();
return;
}
//=============================================================================
// The grahics device has been reset.
// Recreate all surfaces.
//=============================================================================
void Spacewar::resetAll()
{
fontBig.onResetDevice();
fontScore.onResetDevice();
textures1.onResetDevice();
spaceTexture.onResetDevice();
menuTexture.onResetDevice();
Game::resetAll();
return;
}
//=============================================================================
// remove enemy lasers that leave the screen.
//=============================================================================
void Spacewar::deleteDestroyedLasers()
{
float xPos, yPos;
for(std::list<Laser*>::iterator it=playerLasers.begin(); it != playerLasers.end(); ++it)
{
xPos = (*it)->getX();
yPos = (*it)->getY();
if(xPos > GAME_WIDTH || yPos > GAME_HEIGHT || xPos < -laserNS::WIDTH || yPos < -laserNS::HEIGHT || !(*it)->getActive())
{
SAFE_DELETE(*it);
}
}
// remove all the deleted lasers from the list
playerLasers.remove(NULL);
for(std::list<Entity*>::iterator it=enemyProjectiles.begin(); it != enemyProjectiles.end(); ++it)
{
xPos = (*it)->getX();
yPos = (*it)->getY();
if(xPos > GAME_WIDTH || yPos > GAME_HEIGHT || xPos < -laserNS::WIDTH || yPos < -laserNS::HEIGHT || !(*it)->getActive())
{
SAFE_DELETE(*it);
}
}
// remove all the deleted lasers from the list
enemyProjectiles.remove(NULL);
}
//=============================================================================
// remove enemy ships that leave the screen.
//=============================================================================
void Spacewar::deleteOutOfBoundsShips()
{
float xPos, yPos;
bool isInFormingFormation;
for(std::list<EnemyShip*>::iterator it=enemyShips.begin(); it != enemyShips.end();)
{
xPos = (*it)->getX();
yPos = (*it)->getY();
isInFormingFormation = (*it)->getFormingFormationMode();
// check if the ship is no longer in forming formation mode and if the ship is out of bounds
if(!isInFormingFormation && (xPos > GAME_WIDTH || yPos > GAME_HEIGHT || xPos < -shipNS::WIDTH || yPos < -shipNS::HEIGHT))
{
SAFE_DELETE(*it);
it = enemyShips.erase(it);
}
else
{
++it;
}
}
}
//=============================================================================
// Deletes all lasers from the playerLasers and enemyProjectiles lists.
//=============================================================================
void Spacewar::deleteAllLasers()
{
for(std::list<Laser*>::iterator it=playerLasers.begin(); it != playerLasers.end(); ++it)
{
SAFE_DELETE(*it);
}
// remove all the deleted lasers from the list
playerLasers.remove(NULL);
for(std::list<Entity*>::iterator it=enemyProjectiles.begin(); it != enemyProjectiles.end(); ++it)
{
SAFE_DELETE(*it);
}
// remove all the deleted lasers from the list
enemyProjectiles.remove(NULL);
}
//=============================================================================
// deactivate power up pellet so it is no longer updated on the screen (until it is reinitialized again)
//=============================================================================
void Spacewar::deleteOutOfBoundPowerUp()
{
float xPos = powerUp.getX();
float yPos = powerUp.getY();
if (xPos > GAME_WIDTH || yPos > GAME_HEIGHT || xPos < -shipNS::WIDTH || yPos < -shipNS::HEIGHT)
{
// deactivate power up pellet
powerUp.setActive(false);
powerUp.setVisible(false);
}
}
void Spacewar::deleteAllAsteroids()
{
for(std::list<Asteroid*>::iterator it=asteroids.begin(); it != asteroids.end(); ++it)
{
SAFE_DELETE(*it);
}
}
void Spacewar::initializeLaser(Laser* aLaser, bool isPlayers)
{
if (!aLaser->initialize(this, laserNS::WIDTH, laserNS::HEIGHT, laserNS::TEXTURE_COLS, &textures1))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing laser"));
if ( isPlayers )
{
aLaser->setFrames(laserNS::START_FRAME, laserNS::END_FRAME);
aLaser->setCurrentFrame(laserNS::START_FRAME);
}
else
{
aLaser->setFrames(laserNS::START_ENEMY_FRAME, laserNS::END_ENEMY_FRAME);
aLaser->setCurrentFrame(laserNS::START_ENEMY_FRAME);
}
aLaser->setColorFilter(SETCOLOR_ARGB(255,128,128,255)); // light blue
}
//=============================================================================
// initializes enemy missiles
//=============================================================================
void Spacewar::initializeMissile(Missile* aMissile)
{
if (!aMissile->initialize(this, missileNS::WIDTH, missileNS::HEIGHT, missileNS::TEXTURE_COLS, &textures2))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing missile"));
aMissile->setFrames(missileNS::START_FRAME, missileNS::END_FRAME);
aMissile->setCurrentFrame(missileNS::START_FRAME);
aMissile->setColorFilter(SETCOLOR_ARGB(255,230,230,255)); // light blue
}
//=============================================================================
// initializes multiple enemy ships
//=============================================================================
void Spacewar::initiateEnemyShips(short numShips)
{
int probability;
float xPos = 0;
float yPos = 0;
short maxNumEnemyShips = enemyShipNS::GRID_WIDTH*2;
if(enemySpawnSide == spacewarNS::LEFT)
{
shipSpawnXLoc = -shipNS::WIDTH;
}
else
{
shipSpawnXLoc = GAME_WIDTH;
}
if(numShips > maxNumEnemyShips)
{
numShips = maxNumEnemyShips;
}
for (int i=0; i < numShips; i++)
{
// create a new ship
EnemyShip* enemyShip = new EnemyShip();
// initialize the new ship
if (!enemyShip->initialize(this,shipNS::WIDTH,shipNS::HEIGHT,shipNS::TEXTURE_COLS,&textures1))
throw(GameError(gameErrorNS::FATAL_ERROR, "Error initializing an enemy ship"));
enemyShip->setFrames(shipNS::ENEMY_SHIP_START_FRAME, shipNS::ENEMY_SHIP_END_FRAME);
enemyShip->setCurrentFrame(shipNS::ENEMY_SHIP_START_FRAME);
enemyShip->setColorFilter(SETCOLOR_ARGB(255,230,230,255)); // light blue, used for shield and torpedo
enemyShip->setMass(shipNS::MASS);
// find their spawn locations
probability = distributionEnemySpawnLoc(generator);
enemyShip->setRadians((float)PI/2.0f);
enemyShip->setY(GAME_WIDTH/3.0f);
if(enemySpawnSide == spacewarNS::LEFT)
{
// spawn the ship off screen to the left
enemyShip->setX(shipSpawnXLoc);
enemyShip->setSpawnMovementDirection(enemyShipNS::SPAWN_MOVING_RIGHT);
shipSpawnXLoc -= shipNS::WIDTH;
}
else
{
// spawn the ship off screen to the right