We have a lot to get through and in this article we are going to now start moving away from the nitty gritty line be line explanations as hopefully you are becoming more competent in game coding by now. I will outline the changes, present the code and, apart from highlighting any specifics, we will leave it at that. You are free to examine the code to see how the latest instalment was implemented. This should also mean we’ll get through more content from now on with more frequent articles.
Changes in this release
- You can now die if an Invader’s bomb hits you (but not by any other means yet).
- Lives will be decremented and if it gets to zero then it’s game over
- An attract screen
- Congratulations screen for beating high score
- Reset of high score
- Invader and level difficulty, i.e. Invaders move faster the less of them there are and the start lower down per level.
A video covering these changes is available as well as this article, see below:
Highlights – difficulty
As in the arcade game the invaders speed increases as less of them are on screen. Famously this was not an intended game mechanic (i.e. not in any intentional design) but was a by-product of the speed of the available processor at the time. When there were a lot of Invaders to move on screen it took time to plot them to screen. But as their numbers declined the processor didn’t have to plot as many so wasn’t working quite so hard, meaning it could get round to moving and plotting those that were left much sooner than normal – hence they moved faster. This proved an excellent difficulty factor during any one level.
We have very fast processors (compared to the late 70’s early 80’s) and as such we have to deliberately code speeding up. The code that handles this is in the routine MissileAndAlienCollisions. Its in this routine as this is where an Invader would be destroyed and thus they would be slightly less. Here’s the code extract:
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 |
// calc new speed of aliens, note (float) must be before TOTAL_ALIENS to force float calc else // you will get an incorrect result Player.AlienSpeed=((1-(Player.AliensDestroyed/(float)TOTAL_ALIENS))*INVADERS_SPEED); // for very last alien make to fast! if(Player.AliensDestroyed==TOTAL_ALIENS-2) if(AlienXMoveAmount>0) AlienXMoveAmount=ALIEN_X_MOVE_AMOUNT*2; else AlienXMoveAmount=-(ALIEN_X_MOVE_AMOUNT*2); // for very last alien make to super fast! if(Player.AliensDestroyed==TOTAL_ALIENS-1) if(AlienXMoveAmount>0) AlienXMoveAmount=ALIEN_X_MOVE_AMOUNT*4; else AlienXMoveAmount=-(ALIEN_X_MOVE_AMOUNT*4); |
We have a general speed calculation for most of the game (line 584) but then some specific code where we get to the last couple where we increase the speed dramatically.
Level Difficulty
In addition (an intended designed in game mechanic) was that for every level the Invaders would start a little lower down, up until a certain level (perhaps level 4 I cannot remember at time of writing). Then the start height position would revert to the level 1 screen increasing as the levels progressed again until another four levels had passed etc. etc. In this way Space Invaders as no real designed end as such. The code in the NextLevel routine handles this, here’s the extract:
862 |
YStart=((Player->Level-1) % LEVEL_TO_RESET_TO_START_HEIGHT)*AMOUNT_TO_DROP_BY_PER_LEVEL; |
Looks complex perhaps but all it’s doing is setting the Invaders Y start position per level. The Amount to drop per level is defined in the constant AMOUNT_TO_DROP_BY_PER_LEVEL. 4 pixels seems about right for this screen. In essence all we need to do is multiply the level number by this amount to get the Y position. However that would make the game technically impossible for higher level numbers as it could result with the Invaders starting on top of the players tank! So ( as it did in the original) we do this on a repeating cycle of levels. i.e. levels 1-4 they come down more and more then they reset back to the start for level 5 getting lower and lower again etc. etc. The part that accomplishes this is this:
((Player->Level-1) % LEVEL_TO_RESET_TO_START_HEIGHT+1)
The constant LEVEL_TO_RESET_TO_START_HEIGHT contains the level that we reset the Y start position back to the top. In this case I chose level 5. So the Invaders get lower and lower for levels 1 to 4 and start again at the top for level 5 etc. But how is this achieved? Well it’s all in the % (percentage). This is the modulus operator. It’s purpose is to return the remainder of an integer division. i.e. of I divide 4 by 3, then 3 would go in once and 1 would be left over, so 4 % 3 would give me 1 as the answer.
So in our code we divide the current level by 4 and then multiply this remainder by the amount to move down per level to get the Y Position for the Invaders. Look at this table of examples.
Player Level | Player level -1 | LEVEL_TO_RESET_TO_START_HEIGHT | Remainder of : (Player level-1) % LEVEL_TO_RESET_TO_START_HEIGHT | Multiply remainder by AMOUNT_TO_DROP_BY_PER_LEVEL to get Y Position |
---|---|---|---|---|
1 | 0 | 4 | 0 | 0 |
2 | 1 | 4 | 1 | 4 |
3 | 2 | 4 | 2 | 8 |
4 | 3 | 4 | 3 | 12 |
5 | 4 | 4 | 0 | 0 |
6 | 5 | 4 | 1 | 4 |
7 | 6 | 4 | 2 | 8 |
Resetting the high score
If you wish to reset the high score it is implemented by pressing both the left and right buttons at once when on the attract screen. If you look back at previous articles and code it was originally intended to have it’s own button but at the last minute I’ve decided to reduce the button count and do it this way instead.
That’s it for this article, all that remains is to list the full source code for you to paste into your current Invaders project,
Enjoy 🙂
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 |
#include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #include <EEPROM.h> // DISPLAY SETTINGS #define OLED_ADDRESS 0x3C #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 64 // Input settings #define FIRE_BUT 6 #define RIGHT_BUT 5 #define LEFT_BUT 4 // Mothership #define MOTHERSHIP_HEIGHT 4 #define MOTHERSHIP_WIDTH 16 #define MOTHERSHIP_SPEED 2 #define MOTHERSHIP_SPAWN_CHANCE 250 //HIGHER IS LESS CHANCE OF SPAWN #define DISPLAY_MOTHERSHIP_BONUS_TIME 20 // how long bonus stays on screen for displaying mothership // Alien Settings #define ALIEN_HEIGHT 8 #define NUM_ALIEN_COLUMNS 7 #define NUM_ALIEN_ROWS 3 #define X_START_OFFSET 6 #define SPACE_BETWEEN_ALIEN_COLUMNS 5 #define LARGEST_ALIEN_WIDTH 11 #define SPACE_BETWEEN_ROWS 9 #define INVADERS_DROP_BY 4 // pixel amount that invaders move down by #define INVADERS_SPEED 12 // speed of movement, lower=faster. #define INVADER_HEIGHT 8 #define EXPLOSION_GFX_TIME 7 // How long an ExplosionGfx remains on screen before dissapearing #define INVADERS_Y_START MOTHERSHIP_HEIGHT-1 #define AMOUNT_TO_DROP_BY_PER_LEVEL 4 //NEW How much farther down aliens start per new level #define LEVEL_TO_RESET_TO_START_HEIGHT 4 // EVERY MULTIPLE OF THIS LEVEL THE ALIEN y START POSITION WILL RESET TO TOP #define ALIEN_X_MOVE_AMOUNT 1 //number of pixels moved at start of wave #define CHANCEOFBOMBDROPPING 20 // Higher the number the rarer the bomb drop, #define BOMB_HEIGHT 4 #define BOMB_WIDTH 2 #define MAXBOMBS 3 // Max number of bombs allowed to drop at a time // Player settingsc #define TANKGFX_WIDTH 13 #define TANKGFX_HEIGHT 8 #define PLAYER_X_MOVE_AMOUNT 2 #define LIVES 3 //NEW #define PLAYER_EXPLOSION_TIME 10 // How long an ExplosionGfx remains on screen before dissapearing #define PLAYER_Y_START 56 #define PLAYER_X_START 0 #define MISSILE_HEIGHT 4 #define MISSILE_WIDTH 1 #define MISSILE_SPEED 4 // Status of a game object constants #define ACTIVE 0 #define EXPLODING 1 #define DESTROYED 2 // graphics // aliens const unsigned char MotherShipGfx [] PROGMEM = { B00111111,B11111100, B01101101,B10110110, B11111111,B11111111, B00111001,B10011100 }; const unsigned char InvaderTopGfx [] PROGMEM = { B00011000, B00111100, B01111110, B11011011, B11111111, B00100100, B01011010, B10100101 }; const unsigned char InvaderTopGfx2 [] PROGMEM = { B00011000, B00111100, B01111110, B11011011, B11111111, B01011010, B10000001, B01000010 }; const unsigned char PROGMEM InvaderMiddleGfx []= { B00100000,B10000000, B00010001,B00000000, B00111111,B10000000, B01101110,B11000000, B11111111,B11100000, B10111111,B10100000, B10100000,B10100000, B00011011,B00000000 }; const unsigned char PROGMEM InvaderMiddleGfx2 [] = { B00100000,B10000000, B00010001,B00000000, B10111111,B10100000, B10101110,B10100000, B11111111,B11100000, B00111111,B10000000, B00100000,B10000000, B01000000,B01000000 }; const unsigned char PROGMEM InvaderBottomGfx [] = { B00001111,B00000000, B01111111,B11100000, B11111111,B11110000, B11100110,B01110000, B11111111,B11110000, B00111001,B11000000, B01100110,B01100000, B00110000,B11000000 }; const unsigned char PROGMEM InvaderBottomGfx2 [] = { B00001111,B00000000, B01111111,B11100000, B11111111,B11110000, B11100110,B01110000, B11111111,B11110000, B00111001,B11000000, B01000110,B00100000, B10000000,B00010000 }; static const unsigned char PROGMEM ExplosionGfx [] = { B00001000,B10000000, B01000101,B00010000, B00100000,B00100000, B00010000,B01000000, B11000000,B00011000, B00010000,B01000000, B00100101,B00100000, B01001000,B10010000 }; // Player grafix const unsigned char PROGMEM TankGfx [] = { B00000010,B00000000, B00000111,B00000000, B00000111,B00000000, B01111111,B11110000, B11111111,B11111000, B11111111,B11111000, B11111111,B11111000, B11111111,B11111000, }; static const unsigned char PROGMEM MissileGfx [] = { B10000000, B10000000, B10000000, B10000000 }; static const unsigned char PROGMEM AlienBombGfx [] = { B10000000, B01000000, B10000000, B01000000 }; // Game structures struct GameObjectStruct { // base object which most other objects will include signed int X; signed int Y; unsigned char Status; //0 active, 1 exploding, 2 destroyed }; struct AlienStruct { GameObjectStruct Ord; unsigned char ExplosionGfxCounter; // how long we want the ExplosionGfx to last }; struct PlayerStruct { GameObjectStruct Ord; unsigned int Score; unsigned char Lives; //NEW unsigned char Level; unsigned char AliensDestroyed; // count of how many killed so far unsigned char AlienSpeed; // higher the number slower they go, calculated when ever alien destroyed unsigned char ExplosionGfxCounter; // how long we want the ExplosionGfx to last }; // general global variables Adafruit_SSD1306 display(1); //alien global vars //The array of aliens across the screen AlienStruct Alien[NUM_ALIEN_COLUMNS][NUM_ALIEN_ROWS]; AlienStruct MotherShip; GameObjectStruct AlienBomb[MAXBOMBS]; static const int TOTAL_ALIENS=NUM_ALIEN_COLUMNS*NUM_ALIEN_ROWS; //NEW // widths of aliens // as aliens are the same type per row we do not need to store their graphic width per alien in the structure above // that would take a byte per alien rather than just three entries here, 1 per row, saving significnt memory byte AlienWidth[]={8,11,12}; // top, middle ,bottom widths char AlienXMoveAmount=2; signed char InvadersMoveCounter; // counts down, when 0 move invaders, set according to how many aliens on screen bool AnimationFrame=false; // two frames of animation, if true show one if false show the other // Mothership signed char MotherShipSpeed; unsigned int MotherShipBonus; signed int MotherShipBonusXPos; // pos to display bonus at unsigned char MotherShipBonusCounter; // how long bonus amount left on screen // Player global variables PlayerStruct Player; GameObjectStruct Missile; // game variables unsigned int HiScore; bool GameInPlay=false; void setup() { display.begin(SSD1306_SWITCHCAPVCC,OLED_ADDRESS); InitAliens(0); InitPlayer(); pinMode(RIGHT_BUT, INPUT_PULLUP); pinMode(LEFT_BUT, INPUT_PULLUP); pinMode(FIRE_BUT, INPUT_PULLUP); display.setTextSize(1); display.setTextColor(WHITE); EEPROM.get(0,HiScore); if(HiScore==65535) // new unit never written to { HiScore=0; EEPROM.put(0,HiScore); } } void loop() { //NEW if(GameInPlay) { Physics(); UpdateDisplay(); } else AttractScreen(); } void AttractScreen() { display.clearDisplay(); CentreText("Play",0); CentreText("Space Invaders",12); CentreText("Press Fire to start",24); CentreText("Hi Score ",36); display.setCursor(80,36); display.print(HiScore); display.display(); if(digitalRead(FIRE_BUT)==0){ GameInPlay=true; NewGame(); } // CHECK FOR HIGH SCORE RESET, PLAYER MUST HOLD LEFT AND RIGHT TOGETHER if((digitalRead(LEFT_BUT)==0)&(digitalRead(RIGHT_BUT)==0)) { // Reset high score, don't need to worry about debounce as will ony write to EEPROM if changed, so writes a 0 then won't write again // if hiscore still 0 which it will be HiScore=0; EEPROM.put(0,HiScore); } } void Physics() { if(Player.Ord.Status==ACTIVE) { AlienControl(); MotherShipPhysics(); PlayerControl(); MissileControl(); CheckCollisions(); } } unsigned char GetScoreForAlien(int RowNumber) { // returns value for killing and alien at the row indicated switch (RowNumber) { case 0:return 30; case 1:return 20; case 2:return 10; } } void MotherShipPhysics() { if(MotherShip.Ord.Status==ACTIVE) {// spawned, move it MotherShip.Ord.X+=MotherShipSpeed; if(MotherShipSpeed>0) // going left to right , check if off right hand side { if(MotherShip.Ord.X>=SCREEN_WIDTH) { MotherShip.Ord.Status=DESTROYED; } } else // going right to left , check if off left hand side { if(MotherShip.Ord.X+MOTHERSHIP_WIDTH<0) { MotherShip.Ord.Status=DESTROYED; } } } else { // try to spawn mothership if(random(MOTHERSHIP_SPAWN_CHANCE)==1) { // Spawn a mother ship, starts just off screen at top MotherShip.Ord.Status=ACTIVE; // need to set direction if(random(2)==1) // values between 0 and 1 { MotherShip.Ord.X=SCREEN_WIDTH; MotherShipSpeed=-MOTHERSHIP_SPEED; // if we go in here swaps to right to left } else { MotherShip.Ord.X=-MOTHERSHIP_WIDTH; MotherShipSpeed=MOTHERSHIP_SPEED; // set to go left ot right } } } } void PlayerControl() { // user input checks if((digitalRead(RIGHT_BUT)==0)&(Player.Ord.X+TANKGFX_WIDTH<SCREEN_WIDTH)) Player.Ord.X+=PLAYER_X_MOVE_AMOUNT; if((digitalRead(LEFT_BUT)==0)&(Player.Ord.X>0)) Player.Ord.X-=PLAYER_X_MOVE_AMOUNT; if((digitalRead(FIRE_BUT)==0)&(Missile.Status!=ACTIVE)) { Missile.X=Player.Ord.X+(TANKGFX_WIDTH/2); Missile.Y=PLAYER_Y_START; Missile.Status=ACTIVE; } } void MissileControl() { if(Missile.Status==ACTIVE) { Missile.Y-=MISSILE_SPEED; if(Missile.Y+MISSILE_HEIGHT<0) // If off top of screen destroy so can be used again Missile.Status=DESTROYED; } } void AlienControl() { if((InvadersMoveCounter--)<0) { bool Dropped=false; if((RightMostPos()+AlienXMoveAmount>=SCREEN_WIDTH) |(LeftMostPos()+AlienXMoveAmount<0)) // at edge of screen { AlienXMoveAmount=-AlienXMoveAmount; // reverse direction Dropped=true; // and indicate we are dropping } // update the alien postions for(int Across=0;Across<NUM_ALIEN_COLUMNS;Across++) { for(int Down=0;Down<3;Down++) { if(Alien[Across][Down].Ord.Status==ACTIVE) { if(Dropped==false) Alien[Across][Down].Ord.X+=AlienXMoveAmount; else Alien[Across][Down].Ord.Y+=INVADERS_DROP_BY; } } } InvadersMoveCounter=Player.AlienSpeed; AnimationFrame=!AnimationFrame; ///swap to other frame } // should the alien drop a bomb if(random(CHANCEOFBOMBDROPPING)==1) DropBomb(); MoveBombs(); } void MoveBombs(){ for(int i=0;i<MAXBOMBS;i++){ if(AlienBomb[i].Status==ACTIVE) AlienBomb[i].Y+=2; } } void DropBomb() { // if there is a free bomb slot then drop a bomb else nothing happens bool Free=false; unsigned char ActiveCols[NUM_ALIEN_COLUMNS]; unsigned char BombIdx=0; // find a free bomb slot while((Free==false)&(BombIdx<MAXBOMBS)){ if(AlienBomb[BombIdx].Status==DESTROYED) Free=true; else BombIdx++; } if(Free) { unsigned char Columns=0; // now pick and alien at random to drop the bomb // we first pick a column, obviously some columns may not exist, so we count number of remaining cols // first, this adds time but then also picking columns randomly that don't exist may take time also unsigned char ActiveColCount=0; signed char Row; unsigned char ChosenColumn; while(Columns<NUM_ALIEN_COLUMNS){ Row=2; while(Row>=0) { if(Alien[Columns][Row].Ord.Status==ACTIVE) { ActiveCols[ActiveColCount]=Columns; ActiveColCount++; break; } Row--; } Columns++; } // we have ActiveCols array filled with the column numbers of the active cols and we have how many // in ActiveColCount, now choose a column at random ChosenColumn=random(ActiveColCount); // random number between 0 and the amount of columns // we now find the first available alien in this column to drop the bomb from Row=2; while(Row>=0) { if(Alien[ActiveCols[ChosenColumn]][Row].Ord.Status==ACTIVE) { // Set the bomb from this alien AlienBomb[BombIdx].Status=ACTIVE; AlienBomb[BombIdx].X=Alien[ActiveCols[ChosenColumn]][Row].Ord.X+int(AlienWidth[Row]/2); // above sets bomb to drop around invaders centre, here we add a litrle randomness around this pos AlienBomb[BombIdx].X=(AlienBomb[BombIdx].X-2)+random(0,4); AlienBomb[BombIdx].Y=Alien[ActiveCols[ChosenColumn]][Row].Ord.Y+4; break; } Row--; } } } void BombCollisions() { //check bombs collisions for(int i=0;i<MAXBOMBS;i++) { if(AlienBomb[i].Status==ACTIVE) { if(AlienBomb[i].Y>64) // gone off bottom of screen AlienBomb[i].Status=DESTROYED; else { // HAS IT HIT PLAYERS missile if(Collision(AlienBomb[i],BOMB_WIDTH,BOMB_HEIGHT,Missile,MISSILE_WIDTH,MISSILE_HEIGHT)) { // destroy missile and bomb AlienBomb[i].Status=EXPLODING; Missile.Status=DESTROYED; } else { // has it hit players ship if(Collision(AlienBomb[i],BOMB_WIDTH,BOMB_HEIGHT,Player.Ord,TANKGFX_WIDTH,TANKGFX_HEIGHT)) { PlayerHit(); AlienBomb[i].Status=DESTROYED; } } } } } } void PlayerHit() { Player.Ord.Status=EXPLODING; Player.ExplosionGfxCounter=PLAYER_EXPLOSION_TIME; Missile.Status=DESTROYED; } void CheckCollisions() { MissileAndAlienCollisions(); MotherShipCollisions(); BombCollisions(); } void MotherShipCollisions() { if((Missile.Status==ACTIVE)&(MotherShip.Ord.Status==ACTIVE)) { if(Collision(Missile,MISSILE_WIDTH,MISSILE_HEIGHT,MotherShip.Ord,MOTHERSHIP_WIDTH,MOTHERSHIP_HEIGHT)) { MotherShip.Ord.Status=EXPLODING; MotherShip.ExplosionGfxCounter=EXPLOSION_GFX_TIME; Missile.Status=DESTROYED; // generate the score for the mothership hit, note in the real arcade space invaders the score was not random but // just appeared so, a player could infulence its value with clever play, but we'll keep it a little simpler MotherShipBonus=random(4); // a random number between 0 and 3 switch(MotherShipBonus) { case 0:MotherShipBonus=50;break; case 1:MotherShipBonus=100;break; case 2:MotherShipBonus=150;break; case 3:MotherShipBonus=300;break; } Player.Score+=MotherShipBonus; MotherShipBonusXPos=MotherShip.Ord.X; if(MotherShipBonusXPos>100) // to ensure isn't half off right hand side of screen MotherShipBonusXPos=100; if(MotherShipBonusXPos<0) // to ensure isn't half off right hand side of screen MotherShipBonusXPos=0; MotherShipBonusCounter=DISPLAY_MOTHERSHIP_BONUS_TIME; } } } void MissileAndAlienCollisions() { for(int across=0;across<NUM_ALIEN_COLUMNS;across++) { for(int down=0;down<NUM_ALIEN_ROWS;down++) { if(Alien[across][down].Ord.Status==ACTIVE) { if(Missile.Status==ACTIVE) { if(Collision(Missile,MISSILE_WIDTH,MISSILE_HEIGHT,Alien[across][down].Ord,AlienWidth[down],INVADER_HEIGHT)) { // missile hit Alien[across][down].Ord.Status=EXPLODING; Missile.Status=DESTROYED; Player.Score+=GetScoreForAlien(down); Player.AliensDestroyed++; // calc new speed of aliens, note (float) must be before TOTAL_ALIENS to force float calc else // you will get an incorrect result Player.AlienSpeed=((1-(Player.AliensDestroyed/(float)TOTAL_ALIENS))*INVADERS_SPEED); // for very last alien make to fast! if(Player.AliensDestroyed==TOTAL_ALIENS-2) if(AlienXMoveAmount>0) AlienXMoveAmount=ALIEN_X_MOVE_AMOUNT*2; else AlienXMoveAmount=-(ALIEN_X_MOVE_AMOUNT*2); // for very last alien make to super fast! if(Player.AliensDestroyed==TOTAL_ALIENS-1) if(AlienXMoveAmount>0) AlienXMoveAmount=ALIEN_X_MOVE_AMOUNT*4; else AlienXMoveAmount=-(ALIEN_X_MOVE_AMOUNT*4); if(Player.AliensDestroyed==TOTAL_ALIENS) NextLevel(&Player); } } if(Alien[across][down].Ord.Status==ACTIVE) // double check still active afer above code { // check if this alien is in contact with TankGfx if(Collision(Player.Ord,TANKGFX_WIDTH,TANKGFX_HEIGHT,Alien[across][down].Ord,AlienWidth[down],ALIEN_HEIGHT)) PlayerHit(); else { // check if alien is below bottom of screen if(Alien[across][down].Ord.Y+8>SCREEN_HEIGHT) PlayerHit(); } } } } } } bool Collision(GameObjectStruct Obj1,unsigned char Width1,unsigned char Height1,GameObjectStruct Obj2,unsigned char Width2,unsigned char Height2) { return ((Obj1.X+Width1>Obj2.X)&(Obj1.X<Obj2.X+Width2)&(Obj1.Y+Height1>Obj2.Y)&(Obj1.Y<Obj2.Y+Height2)); } int RightMostPos() { //returns x pos of right most alien int Across=NUM_ALIEN_COLUMNS-1; int Down; int Largest=0; int RightPos; while(Across>=0){ Down=0; while(Down<NUM_ALIEN_ROWS){ if(Alien[Across][Down].Ord.Status==ACTIVE) { // different aliens have different widths, add to x pos to get rightpos RightPos= Alien[Across][Down].Ord.X+AlienWidth[Down]; if(RightPos>Largest) Largest=RightPos; } Down++; } if(Largest>0) // we have found largest for this coloum return Largest; Across--; } return 0; // should never get this far } int LeftMostPos() { //returns x pos of left most alien int Across=0; int Down; int Smallest=SCREEN_WIDTH*2; while(Across<NUM_ALIEN_COLUMNS){ Down=0; while(Down<3){ if(Alien[Across][Down].Ord.Status==ACTIVE) if(Alien[Across][Down].Ord.X<Smallest) Smallest=Alien[Across][Down].Ord.X; Down++; } if(Smallest<SCREEN_WIDTH*2) // we have found smalest for this coloum return Smallest; Across++; } return 0; // should nevr get this far } void UpdateDisplay() { int i; display.clearDisplay(); // Mothership bonus display if required if(MotherShipBonusCounter>0) { // mothership bonus display.setCursor(MotherShipBonusXPos,0); display.print(MotherShipBonus); MotherShipBonusCounter--; } else { // draw score and lives, anything else can go above them display.setCursor(0,0); display.print(Player.Score); display.setCursor(SCREEN_WIDTH-7,0); display.print(Player.Lives); } //BOMBS // draw bombs next as aliens have priority of overlapping them for(i=0;i<MAXBOMBS;i++) { if(AlienBomb[i].Status==ACTIVE) display.drawBitmap(AlienBomb[i].X, AlienBomb[i].Y, AlienBombGfx, 2, 4,WHITE); else {// must be destroyed if(AlienBomb[i].Status==EXPLODING) display.drawBitmap(AlienBomb[i].X-4, AlienBomb[i].Y, ExplosionGfx, 4, 8,WHITE); // Ensure on next draw that ExplosionGfx dissapears AlienBomb[i].Status=DESTROYED; } } //Invaders for(int across=0;across<NUM_ALIEN_COLUMNS;across++) { for(int down=0;down<NUM_ALIEN_ROWS;down++) { if(Alien[across][down].Ord.Status==ACTIVE){ switch(down) { case 0: if(AnimationFrame) display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, InvaderTopGfx, AlienWidth[down],INVADER_HEIGHT,WHITE); else display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, InvaderTopGfx2, AlienWidth[down],INVADER_HEIGHT,WHITE); break; case 1: if(AnimationFrame) display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, InvaderMiddleGfx, AlienWidth[down],INVADER_HEIGHT,WHITE); else display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, InvaderMiddleGfx2, AlienWidth[down],INVADER_HEIGHT,WHITE); break; default: if(AnimationFrame) display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, InvaderBottomGfx, AlienWidth[down],INVADER_HEIGHT,WHITE); else display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, InvaderBottomGfx2, AlienWidth[down],INVADER_HEIGHT,WHITE); } } else { if(Alien[across][down].Ord.Status==EXPLODING){ Alien[across][down].ExplosionGfxCounter--; if(Alien[across][down].ExplosionGfxCounter>0) { display.drawBitmap(Alien[across][down].Ord.X, Alien[across][down].Ord.Y, ExplosionGfx, 13, 8,WHITE); } else Alien[across][down].Ord.Status=DESTROYED; } } } } // player if(Player.Ord.Status==ACTIVE) display.drawBitmap(Player.Ord.X, Player.Ord.Y, TankGfx, TANKGFX_WIDTH, TANKGFX_HEIGHT,WHITE); else { if(Player.Ord.Status==EXPLODING) { for(i=0;i<TANKGFX_WIDTH;i+=2) { display.drawBitmap(Player.Ord.X+i, Player.Ord.Y, ExplosionGfx, random(4)+2, 8,WHITE); } Player.ExplosionGfxCounter--; if(Player.ExplosionGfxCounter==0) { Player.Ord.Status=DESTROYED; LoseLife(); } } } //missile if(Missile.Status==ACTIVE) display.drawBitmap(Missile.X, Missile.Y, MissileGfx, MISSILE_WIDTH, MISSILE_HEIGHT,WHITE); // mothership (not bonus if hit) if(MotherShip.Ord.Status==ACTIVE) display.drawBitmap(MotherShip.Ord.X, MotherShip.Ord.Y, MotherShipGfx, MOTHERSHIP_WIDTH, MOTHERSHIP_HEIGHT,WHITE); else { if(MotherShip.Ord.Status==EXPLODING) { for(i=0;i<MOTHERSHIP_WIDTH;i+=2) { display.drawBitmap(MotherShip.Ord.X+i, MotherShip.Ord.Y, ExplosionGfx, random(4)+2, MOTHERSHIP_HEIGHT,WHITE); } MotherShip.ExplosionGfxCounter--; if(MotherShip.ExplosionGfxCounter==0) { MotherShip.Ord.Status=DESTROYED; } } } display.display(); } void LoseLife() { Player.Lives--; if(Player.Lives>0) { DisplayPlayerAndLives(&Player); // clear alien missiles for(int i=0;i<MAXBOMBS;i++) { AlienBomb[i].Status=DESTROYED; AlienBomb[i].Y=0; } // ENABLE PLAYER Player.Ord.Status=ACTIVE; Player.Ord.X=0; } else { GameOver(); } } void GameOver() { GameInPlay=false; display.clearDisplay(); CentreText("Player 1",0); CentreText("Game Over",12); CentreText("Score ",24); display.print(Player.Score); if(Player.Score>HiScore) { CentreText("NEW HIGH SCORE!!!",36); CentreText("**CONGRATULATIONS**",48); } display.display(); if(Player.Score>HiScore){ HiScore=Player.Score; EEPROM.put(0,HiScore); } delay(2500); } void DisplayPlayerAndLives(PlayerStruct *Player) { display.clearDisplay(); CentreText("Player 1",0); CentreText("Score ",12); display.print(Player->Score); CentreText("Lives ",24); display.print(Player->Lives); CentreText("Level ",36); display.print(Player->Level); display.display(); delay(2000); Player->Ord.X=PLAYER_X_START; } void CentreText(const char *Text,unsigned char Y) { // centres text on screen display.setCursor(int((float)(SCREEN_WIDTH)/2-((strlen(Text)*6)/2)),Y); display.print(Text); } void InitPlayer() { Player.Ord.Y=PLAYER_Y_START; Player.Ord.X=PLAYER_X_START; Player.Ord.Status=ACTIVE; Player.Lives=LIVES; Player.Level=0; Missile.Status=DESTROYED; Player.Score=0; } void NextLevel(PlayerStruct *Player) { // reset any dropping bombs int YStart; for(int i=0;i<MAXBOMBS;i++) AlienBomb[i].Status=DESTROYED; AnimationFrame=false; Player->Level++; YStart=((Player->Level-1) % LEVEL_TO_RESET_TO_START_HEIGHT)*AMOUNT_TO_DROP_BY_PER_LEVEL; InitAliens(YStart); AlienXMoveAmount=ALIEN_X_MOVE_AMOUNT; Player->AlienSpeed=INVADERS_SPEED; Player->AliensDestroyed=0; MotherShip.Ord.X=-MOTHERSHIP_WIDTH; MotherShip.Ord.Status=DESTROYED; Missile.Status=DESTROYED; randomSeed(100); DisplayPlayerAndLives(Player); } void NewGame(){ InitPlayer(); NextLevel(&Player); } void InitAliens(int YStart) { for(int across=0;across<NUM_ALIEN_COLUMNS;across++) { for(int down=0;down<3;down++) { // we add down to centralise the aliens, just happens to be the right value we need per row! // we need to adjust a little as row zero should be 2, row 1 should be 1 and bottom row 0 Alien[across][down].Ord.X=X_START_OFFSET+(across*(LARGEST_ALIEN_WIDTH+SPACE_BETWEEN_ALIEN_COLUMNS))-(AlienWidth[down]/2); Alien[across][down].Ord.Y=YStart+(down*SPACE_BETWEEN_ROWS); Alien[across][down].Ord.Status=ACTIVE; Alien[across][down].ExplosionGfxCounter=EXPLOSION_GFX_TIME; } } MotherShip.Ord.Y=0; MotherShip.Ord.X=-MOTHERSHIP_WIDTH; MotherShip.Ord.Status=DESTROYED; } |