Let’s move our project from the breadboard to strip-board to give it a more permanent home. You will need 30×30 hole strip-board (30 width is a common size). Strip-board is the prototyping board that has rows of copper strips as apposed to perf-board which just has copper pads. I prefer strip-board also sometimes referred to as veroboard (veroboard is a large manufacturer of strip-board). If you want to use perf-board then you will have to adopt the design below accordingly.
A video has been created to support this article
Below are three diagrams of the the same board (click to make full size). I’ve labeled the rows and columns with numbers to make it easier to transfer to you own board. We are going to build and test this in stages to hopefully minimise any errors. The first shows the track side of the board and where you need to make cuts. the second and third are the component (none track/solder side), with the middle showing just the wiring (solder them underneath where they go through the board).
Cutting the tracks
First job is to cut the tracks where indicated by the white circles. Turn you board so that you are looking at the copper tracks facing you. See this picture of the board I’m using (click to enlarge);
Cut the board to 30 holes across and 30 down. Orientate the board so the tracks are running vertically downwards as shown in the left most picture above (and in the photo just above). Cut the tracks where shown, being careful to double check you are doing it in the correct place. A track cutter is a good tool purpose built for this job but you can get by with a craft knife if required. After you’ve finished check every cut track to ensure there is NO continuity across the cuts (sometimes tiny bits of copper can remain). Here’s mine after completion.
Adding the jumper wires
Next we add the jumper wires on the reverse side to the one where you’ve just cut the tracks in the copper, this is called the component side. Look at the middle picture which shows where to place them. Again, care should be taken over their placement and double checked as errors here could result in the system not working or even the breaking of parts in the system. Here’s my board after adding the tracks;
Note : Due to last minute alterations the board shown here is a little bit different from the designs further up, follow the earlier designs and not these progress pictures.
Adding the components – Arduino Nano
Solder in the Arduino Nano taking care on the placement – see the right most image above. You need not solder every pin, only the ones being used, so for this it would be GND, 5V (Vcc), D10, D6, D5, D4, A4, A5. But by all means solder them all if you wish. Once the Nano has been added you should upload a test sketch to blink the on-board LED to ensure all is currently working. Here’s the blink test for a Arduino Nano, upload and test.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// the setup function runs once when you press reset or power the board void setup() { // initialize digital pin LED_BUILTIN as an output. pinMode(LED_BUILTIN, OUTPUT); } // the loop function runs over and over again forever void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } |
Adding the OLED screen
Position and solder in the OLED screen. To test we will need to bring in some libraries to our Arduino IDE. The first is the driver for 1306 OLED displays. Go to the Arduibo IDE library manager, “Sketch->Include Library->Manage Libraries”. Type “Adafruit SSD1306” into the search field. The first result should be the one you require titled “Adafruit SSD1306 by Adafruit”. Install this. The second library is an altered version of the Adafruit graphics library that I modified to work with graphics stored in dynamic rather than static RAM. I believe Adafruit have added this capability in since I wrote this addition but I’ve not had time to look into this and check if my Space Invaders code would work with it, so I’m sticking with what I know works. If you’ve already added the normal standard Adafruit Graphics library for other projects then you will need to remove whilst you install this version and use it in this project, here’s the link to the download, download and install into your IDE;
Altering the screen size definition in the Adafruit driver library
OLED screens come in various pixel definitions for both width and height, the library supports three different sizes at time of writing. Open Adafruit_SSD1306.h , which should be located within the libraries folder in the folder where your Arduino projects are stored, for example mine is located here;
My Documents\Arduino\libraries\Adafruit_SSD1306-master
At around line 70 you will see the following lines
1 2 3 |
// #define SSD1306_128_64 #define SSD1306_128_32 // #define SSD1306_96_16 |
By default #define SSD1306_128_32 is un-commented and the others commented out. For our purposes we have a 64 pixel height screen and this is the line we need to uncomment, so change the code to look as follows;
1 2 3 |
#define SSD1306_128_64 // #define SSD1306_128_32 // #define SSD1306_96_16 |
Ready to demo (still might not work!)
Enter or copy and paste the following code into a new Arduino Sketch. Ensure your port is set correctly and you have selected the correct board to upload to (in my case it’s the Nano).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> #define OLED_Address 0x3C Adafruit_SSD1306 oled(1); void setup() { oled.begin(SSD1306_SWITCHCAPVCC, OLED_Address); } void loop() { oled.clearDisplay(); oled.setTextColor(WHITE); oled.setCursor(0,0); oled.println("Hello XTronical!"); oled.display(); } |
Compile and upload the code. If it works then great, you’ve done it, if not then the most likely culprit(apart from bad wiring – please check!) is the I²C address of your display. These tend to be either 0x3C or 0x3D. So first try changing the line
#define OLED_Address 0x3C
to
#define OLED_Address 0x3D
and recompile/upload. If this doesn’t work it may be that your screen has an even different address to the most common ones. In this case you need to load a I²C address scanner onto your Arduino to get the screen to return its address and use that one in the code above. See this Link for a suitable scanner.
Once this is done you should be able to run the above code and see the message. As a further test to ensure all the screen is being written to correctly, open an example from Adafruit and upload it, use “File->Examples->Adafruit SSD1306->ssd1306_128x64_i2c”. When this is run you should see it going through several graphical demo’s and then stop at the end.
Adding the Space Invaders Code
Next we are going to upload the actual code, but before we do we need to add in the sound library otherwise it will give a compilation error. Download and add the following library to your Arduino IDE;
This is a modified version of the toneAC library to add in functionality I needed for this game.
The full space invaders code can now be uploaded and is available below, just expand the area and copy and paste into your IDE. When ran you should see the Space Invaders start screen but you currently have no way of starting a game, see after the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 |
#include <Adafruit_SSD1306.h> #include <Adafruit_GFX.h> #include <toneAC.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 // These two lines are for when bombs collide with the bases #define CHANCE_OF_BOMB_DAMAGE_TO_LEFT_OR_RIGHT 3 // higher more chance #define CHANCE_OF_BOMB_PENETRATING_DOWN 3 // higher more chance // 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 BASE_WIDTH 16 #define BASE_WIDTH_IN_BYTES 2 #define BASE_HEIGHT 8 #define BASE_Y 46 #define NUM_BASES 3 #define BASE_MARGINS 10 #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 // background dah dah dah sound setting #define NOTELENGTH 1 // larger means play note longer // 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 }; static const unsigned char PROGMEM BaseGfx [] = { B00011111,B11111000, B01111111,B11111110, B11111111,B11111111, B11111111,B11111111, B11111111,B11111111, B11111000,B00011111, B11100000,B00000111, B11100000,B00000111 }; // 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 BaseStruct { GameObjectStruct Ord; unsigned char Gfx[16]; }; 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; 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]; BaseStruct Base[NUM_BASES]; 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; // Sound settings and variables // music (dah dah dah sound) control, these are the "pitch" of the four basic notes const unsigned char Music[] = { 160,100,80,62 }; unsigned char MusicIndex; // index pointer to next note to play unsigned MusicCounter; // how long note plays for countdown timer, is set to // NOTELENGTH define above bool PlayerExplosionNoiseCompleted=false; // flag to indicate when noise has completed bool ShootCompleted=true; // stops music when this is false, so we can here shoot sound 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 toneAC((MotherShip.Ord.X % 8)*500,7,200,true); 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; noToneAC(); } } else // going right to left , check if off left hand side { if(MotherShip.Ord.X+MOTHERSHIP_WIDTH<0) { MotherShip.Ord.Status=DESTROYED; noToneAC(); } } } 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; noiseAC(200,10,&ShootCompleted); } } 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 } // play background music note if other higher priority sounds not playing if((ShootCompleted)&(MotherShip.Ord.Status!=ACTIVE)) { toneAC(Music[MusicIndex],2,100,true); MusicIndex++; if(MusicIndex==sizeof(Music)) MusicIndex=0; MusicCounter=NOTELENGTH; } // 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; } else BombAndBasesCollision(&AlienBomb[i]); } } } } } void BombAndBasesCollision(GameObjectStruct *Bomb) { // check and handle any bomb and base collision for(int i=0;i<NUM_BASES;i++) { if(Collision(*Bomb,BOMB_WIDTH,BOMB_HEIGHT,Base[i].Ord,BASE_WIDTH,BASE_HEIGHT)) { // Now get the position of the bomb within the structure so we can destroy it bit by bit // we first get the relative position from the left hand side of the base // then we divide this by 2 (X>>1) , this gives us a position with 2bit resolution unsigned char X=Bomb->X-Base[i].Ord.X; X=X>>1; // Because the bomb is 2 pixels wide it's X pos could have been less than the bases XPos, if this is the case the above substaction // on an unsigned char (byte) will cause a large number to occur (255), we check for this and if this large number has // resulted we just set X to 0 for the start of the bases structure if(X>7) X=0; // We now look at wether the bomb is hitting a part of the structure below it. // the bomb may be past the top of the base (even on first collision detection) as it moves in Y amounts greater than 1 pixel to give a higher speed // so we start from top of the base and destroy any structure of the base that comes before or equal to the // bombs Y pos, if we go past the bomb Y without finding any bit of base then stop looking and bomb is allowed to progress further down signed char Bomb_Y=(Bomb->Y+BOMB_HEIGHT)-Base[i].Ord.Y; unsigned char Base_Y=0; while((Base_Y<=Bomb_Y)&(Base_Y<BASE_HEIGHT)&(Bomb->Status==ACTIVE)) { unsigned char Idx=(Base_Y*BASE_WIDTH_IN_BYTES)+(X>>2); // this gets the index for the byte in question from the gfx array unsigned char TheByte=Base[i].Gfx[Idx]; // we now have the byte to inspect, but need to only look at the 2 bits where the bomb is colliding // now isolate the 2 bits in question, we have the correct byte and we only have need the bottom 2 bits of X now to denote which bits // we need to destroy in the byte itself unsigned char BitIdx=X & 3; // this preseves the bottom 2 bits and removes the rest // A value of X of 0 (zero) would mean we want to look at the first 2 bits of the byte // A value of X of 1 (zero) would mean we want to look at the second 2 bits of the byte // A value of X of 2 (zero) would mean we want to look at the third 2 bits of the byte // A value of X of 3 (zero) would mean we want to look at the fourth 2 bits of the byte // So we need an AND mask to isolate these bits depending on the value of X // Here it is and we initially set it to the first 2 bits unsigned char Mask=B11000000; // now we need to move those 2 "11"'s to the right depending on the value of X as noted above // the next line may look odd but all we're doing is multiplying X by 2 initially, so the values above would become,0,2,4,6 rather than 0,1,2,3 // Then we move the bits in the mask by this new amount, check it above,a value of X of 2 would shift the bits 4 places, whichis correct! Mask=Mask>>(BitIdx<<1); //now we peform a logical and to remove all bits (pixels) from around these two bits TheByte=TheByte & Mask; // and if there are any set pixels (bits) then they must be destroyed, else the bomb is allowed to continue if(TheByte>0) { // There are some pixels to destroy //We need to remove the pixels(bits) where there were "11"'s in the mask and leave those intact where there were 0's //easiest way, flip all 0's in the mask to ones and all 1's to 0's, the tilde "~" means invert (swap), reffered to as logical NOT Mask=~Mask; // we can then "AND" the byte with the Mask to remove the bits but leave the rest intact Base[i].Gfx[Idx]=Base[i].Gfx[Idx] & Mask; // now do some collateral damage to surrounding bricks, try left hand side first if(X>0){ // not at far left, if we were there would be nothing to destroy to this left if(random(CHANCE_OF_BOMB_DAMAGE_TO_LEFT_OR_RIGHT)) // if true blow some bricks to the left hand side { if(X!=4) // we not at start of second byte { Mask=(Mask<<1)|1; Base[i].Gfx[Idx]=Base[i].Gfx[Idx] & Mask; } else // we are at very start of second byte, so wipe out adjacent pixel first byte { Base[i].Gfx[Idx-1]=Base[i].Gfx[Idx-1] & B11111110; } } } // now do some collateral damage right hand side first if(X<7){ // not at far right, if we were there would be nothing to destroy to this right if(random(CHANCE_OF_BOMB_DAMAGE_TO_LEFT_OR_RIGHT)) // if true blow some bricks to the left hand side { if(X!=3) // not at last pixel of left of first byte { Mask=(Mask>>1)|128; Base[i].Gfx[Idx]=Base[i].Gfx[Idx] & Mask; } else // we are at last pixel of first byte so destroy pixil in adjacent byte { Base[i].Gfx[Idx+1]=Base[i].Gfx[Idx+1] & B01111111; } } } if(random(CHANCE_OF_BOMB_PENETRATING_DOWN)==false) // if false BOMB EXPLODES else carries on destroying more Bomb->Status=EXPLODING; } else Base_Y++; } } } } void MissileAndBasesCollisions() { // check and handle any player missile and base collision for(int i=0;i<NUM_BASES;i++) { if(Collision(Missile,MISSILE_WIDTH,MISSILE_HEIGHT,Base[i].Ord,BASE_WIDTH,BASE_HEIGHT)) { // Now get the position of the bomb within the structure so we can destroy it bit by bit // we first get the relative position from the left hand side of the base // then we divide this by 2 (X>>1) , this gives us a position with 2bit resolution unsigned char X=Missile.X-Base[i].Ord.X; X=X>>1; // Because the bomb is 2 pixels wide it's X pos could have been less than the bases XPos, if this is the case the above substaction // on an unsigned char (byte) will cause a large number to occur (255), we check for this and if this large number has // resulted we just set X to 0 for the start of the bases structure if(X>7) X=0; // We now look at wether the bomb is hitting a part of the structure above it. // the bomb may be past the top of the base (even on first collision detection) as it moves in Y amounts greater than 1 pixel to give a higher speed // so we start from top of the base and destroy any structure of the base that comes before or equal to the // bombs Y pos, if we go past the bomb Y without finding any bit of base then stop looking and bomb is allowed to progress further down signed char Missile_Y=Missile.Y-Base[i].Ord.Y; signed char Base_Y=BASE_HEIGHT-1; while((Base_Y>=Missile_Y)&(Base_Y>=0)&(Missile.Status==ACTIVE)) { // if(Base_Y<0) {Serial.println("oop"); delay(999999);} unsigned char Idx=(Base_Y*BASE_WIDTH_IN_BYTES)+(X>>2); // this gets the index for the byte in question from the gfx array unsigned char TheByte=Base[i].Gfx[Idx]; // we now have the byte to inspect, but need to only look at the 2 bits where the bomb is colliding // now isolate the 2 bits in question, we have the correct byte and we only have need the bottom 2 bits of X now to denote which bits // we need to destroy in the byte itself unsigned char BitIdx=X & 3; // this preseves the bottom 2 bits and removes the rest // A value of X of 0 (zero) would mean we want to look at the first 2 bits of the byte // A value of X of 1 (zero) would mean we want to look at the second 2 bits of the byte // A value of X of 2 (zero) would mean we want to look at the third 2 bits of the byte // A value of X of 3 (zero) would mean we want to look at the fourth 2 bits of the byte // So we need an AND mask to isolate these bits depending on the value of X // Here it is and we initially set it to the first 2 bits unsigned char Mask=B11000000; // now we need to move those 2 "11"'s to the right depending on the value of X as noted above // the next line may look odd but all we're doing is multiplying X by 2 initially, so the values above would become,0,2,4,6 rather than 0,1,2,3 // Then we move the bits in the mask by this new amount, check it above,a value of X of 2 would shift the bits 4 places, whichis correct! Mask=Mask>>(BitIdx<<1); //now we peform a logical AND to remove all bits (pixels) from around these two bits TheByte=TheByte & Mask; // and if there are any set pixels (bits) then they must be destroyed, else the bomb is allowed to continue if(TheByte>0) { // There are some pixels to destroy //We need to remove the pixels(bits) where there were "11"'s in the mask and leave those intact where there were 0's //easiest way, flip all 0's in the mask to ones and all 1's to 0's, the tilde "~" means invert (swap), reffered to as logical NOT Mask=~Mask; // we can then "AND" the byte with the Mask to remove the bits but leave the rest intact Base[i].Gfx[Idx]=Base[i].Gfx[Idx] & Mask; // now do some collateral damage to surrounding bricks, try left hand side first if(X>0){ // not at far left, if we were there would be nothing to destroy to this left if(random(CHANCE_OF_BOMB_DAMAGE_TO_LEFT_OR_RIGHT)) // if true blow some bricks to the left hand side { if(X!=4) // we not at start of second byte { Mask=(Mask<<1)|1; Base[i].Gfx[Idx]=Base[i].Gfx[Idx] & Mask; } else // we are at very start of second byte, so wipe out adjacent pixel first byte { Base[i].Gfx[Idx-1]=Base[i].Gfx[Idx-1] & B11111110; } } } // now do some collateral damage right hand side first if(X<7){ // not at far right, if we were there would be nothing to destroy to this right if(random(CHANCE_OF_BOMB_DAMAGE_TO_LEFT_OR_RIGHT)) // if true blow some bricks to the left hand side { if(X!=3) // not at last pixel of left of first byte { Mask=(Mask>>1)|128; Base[i].Gfx[Idx]=Base[i].Gfx[Idx] & Mask; } else // we are at last pixel of first byte so destroy pixil in adjacent byte { Base[i].Gfx[Idx+1]=Base[i].Gfx[Idx+1] & B01111111; } } } if(random(CHANCE_OF_BOMB_PENETRATING_DOWN)==false) // if false BOMB EXPLODES else carries on destroying more Missile.Status=EXPLODING; } else Base_Y--; } } } } void PlayerHit() { Player.Ord.Status=EXPLODING; Player.ExplosionGfxCounter=PLAYER_EXPLOSION_TIME; Missile.Status=DESTROYED; noiseAC(500,10,&PlayerExplosionNoiseCompleted); } void CheckCollisions() { MissileAndAlienCollisions(); MotherShipCollisions(); MissileAndBasesCollisions(); BombCollisions(); AlienAndBaseCollisions(); } char GetAlienBaseCollisionMask(int AlienX, int AlienWidth,int BaseX) { signed int DamageWidth; unsigned char LeftMask,RightMask,FullMask; // this routine uses a 1 to mean remove bit and 0 to preserve, this is kind of opposite of what we would // normally think of, but it's done this way as when we perform bit shifting to show which bits are preserved // it will shift in 0's in (as that's just was the C shift operater ">>" and "<<" does // at the end we will flip all the bits 0 becomes 1, 1 becomes 0 etc. so that the mask then works correctly // with the calling code LeftMask=B11111111; // initially set to remove all RightMask=B11111111; // unless change in code below // if Alien X more than base x then some start bits are unaffected if(AlienX>BaseX) { // we shift the bits above to the right by the amount unaffected, thus putting 0's into the bits // not to delete DamageWidth=AlienX-BaseX; LeftMask>>=DamageWidth; } // now work out how much of remaining byte is affected // if right hand side of alien is less than BaseX right hand side then some preserved at the right hand end if(AlienX+AlienWidth<BaseX+(BASE_WIDTH/2)) { DamageWidth=(BaseX+(BASE_WIDTH/2))-(AlienX+AlienWidth); RightMask<<=DamageWidth; } // we now have two masks, one showing which bits to preserve on left of the byte, the other the right hand side, // we need to combine them to one mask, the code in the brackets does this combining // at the moment a 0 means keep, 1 destroy, but this is actually makes it difficult to implement later on, so we flip // the bits to be a more logical 1= keep bit and 0 remove bit (pixel) and then return the mask // the tilde (~) flips the bits that resulted from combining the two masks return ~(LeftMask & RightMask); } void DestroyBase(GameObjectStruct *Alien,BaseStruct *Base,char Mask,int BaseByteOffset) { signed char Y; // go down "removing" bits to the depth that the alien is down into the base Y=(Alien->Y+ALIEN_HEIGHT)-Base->Ord.Y; if(Y>BASE_HEIGHT-1) Y=BASE_HEIGHT-1; for(;Y>=0;Y--){ Base->Gfx[(Y*2)+BaseByteOffset]=Base->Gfx[(Y*2)+BaseByteOffset] & Mask; } } void AlienAndBaseCollisions() { unsigned char Mask; // checks if aliens are in collision with the tank // start at bottom row as they are most likely to be in contact or not and if not then none further up are either for(int row=2;row>=0;row--) { for(int column=0;column<NUM_ALIEN_COLUMNS;column++) { if(Alien[column][row].Ord.Status==ACTIVE) { // now scan for a collision with each base in turn for(int BaseIdx=0;BaseIdx<NUM_BASES;BaseIdx++) { if(Collision(Alien[column][row].Ord,AlienWidth[row],ALIEN_HEIGHT,Base[BaseIdx].Ord,BASE_WIDTH,BASE_HEIGHT)) { // WE HAVE A COLLSISION, REMOVE BITS OF BUILDING // process left half (first byte) of base first Mask=GetAlienBaseCollisionMask(Alien[column][row].Ord.X,AlienWidth[row],Base[BaseIdx].Ord.X); DestroyBase(&Alien[column][row].Ord,&Base[BaseIdx],Mask,0); // do right half, second byte of base Mask=GetAlienBaseCollisionMask(Alien[column][row].Ord.X,AlienWidth[row],Base[BaseIdx].Ord.X+(BASE_WIDTH/2)); DestroyBase(&Alien[column][row].Ord,&Base[BaseIdx],Mask,1); } } } } } } 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; toneAC(700,10,100,true); 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) { toneAC(Alien[across][down].ExplosionGfxCounter*100,10,100,true); 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); } toneAC(MotherShip.ExplosionGfxCounter*50,10,100,true); MotherShip.ExplosionGfxCounter--; if(MotherShip.ExplosionGfxCounter==0) { MotherShip.Ord.Status=DESTROYED; } } } // plot bases for(i=0;i<NUM_BASES;i++) { if(Base[i].Ord.Status==ACTIVE) display.drawBitmap(Base[i].Ord.X, Base[i].Ord.Y, Base[i].Gfx, BASE_WIDTH, BASE_HEIGHT,WHITE,true); } 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); PlayRewardMusic(); } delay(2500); } void PlayRewardMusic() { unsigned char Notes[] = { 26, 20, 18, 22, 20, 0, 26, 0, 26 }; unsigned char NoteDurations[] = { 40, 20, 20, 40, 30, 50, 30, 10,30 }; for(int i=0;i<9;i++) { toneAC(Notes[i]*10,10,0,true); delay(NoteDurations[i]*10); // time not plays for noToneAC(); // stop note delay(20); // small delay between notes } noToneAC(); } 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); InitBases(); DisplayPlayerAndLives(Player); MusicIndex=0; MusicCounter=NOTELENGTH; } void InitBases() { // Bases need to be re-built! uint8_t TheByte; int Spacing=(SCREEN_WIDTH-(NUM_BASES*BASE_WIDTH))/NUM_BASES; for(int i=0;i<NUM_BASES;i++) { for(int DataIdx=0;DataIdx<BASE_HEIGHT*BASE_WIDTH_IN_BYTES;DataIdx++) { TheByte = pgm_read_byte(BaseGfx + DataIdx); Base[i].Gfx[DataIdx]=TheByte; } Base[i].Ord.X=(i*Spacing)+(i*BASE_WIDTH)+(Spacing/2); Base[i].Ord.Y=BASE_Y; Base[i].Ord.Status=ACTIVE; } } 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; } |
Adding Controls
Solder in the three buttons below the Nano, making sure that they are orientated so that the push connection is made connecting the left hand side of the button to the right, use a multi-meter if you are unsure or sometimes it is marked on the bottom of the switches with some sort of diagram. Test by playing the game, the fire (far right) should start a game and the others are left and right direction control.
Adding Sound
Add the two resistors (ensure they are in the correct locations or you will probably damage something) and then the PAM8403 module and speaker itself. The last item is the volume control, which I mounted as shown and connected the three outputs to the tracks. You may have to be inventive in mounting yours due to difference in what I’ve got and what you have, just ensure the three connections go to the correct track.
The completed project
Here’s my completed board, note that at time of the build the correct speaker was unavailable so I made do with a temporary one that is slightly oversized but will be replaced when the correct one arrives.
Power Up
Power up again and now you should have sound with volume control. That’s it for this article, next time in this series we’ll present an actual printed circuit board design that you can use for home production or indeed send off to be manufactured. It may even be able to purchase it from this site if I get the shop up and running but files will be available for download so that you don’t have to purchase it to have it.
Hi Sorvad (Stardot friend), I saw your post there which lead me here.
I have now built your space invadershardware and compiled the .ino with the libraries as you havve described them. I have it working 95%, but the screen is only showing the invaders, but not the lower third, ie the baracades, nor the launcher. I suspect the error is in changes to the adafruit Adafruit SSD1306 library (in the last 20 days), do you have an complete ino file with the libries you used attached (in tabs) ? Or any other help you can offer ? cheers, Roger
Yes, you are correct in the fact that since this code was originally written (over a year ago now) the Adafruit library did change. All you need to do is either alter the “.h” header file for the SS1306 library to un-comment the 128×64 screen size an comment out the 128×32 default setting. Or change the line that creates the screen object to
Adafruit_SSD1306 oled(128, 64); // create our screen object setting resolution to 128×64
They changed it to above as so many people didn’t remember or know to change the header file for the appropriate display, You should be good to go once you’ve done this.
SOLVED: I had multipul versions of the SS1306 library and my sketch was pinking up from one I was NOT amending. Thanks for your help.
Roger
Great stuff, fell for that myself. More than once [embarrassed].