FabGL2 2.0.0
ESP32 Display Controller and Graphics Library for ESP-IDF
Loading...
Searching...
No Matches
SpaceInvaders

A complete arcade shoot-'em-up game (320x200, 64 colors) with sprites, collision detection and sampled sounds. Watch it on YouTube.

How to play

Destroy the waves of aliens before they reach the ground. Hide behind the four shields (they are damaged by both your shots and the aliens' bombs). A mystery ship crosses the top of the screen from time to time.

Target Points
Mystery ship ? (random bonus)
Top row aliens 30
Middle row aliens 20
Bottom row aliens 10

You start with 3 lives. When a wave is destroyed the next level starts; the hi-score is kept until the board is reset.

Controls

On the intro screen press Space to play with the keyboard, or click to play with the mouse (only the available device is proposed).

Device Move Fire
Keyboard Left / Right arrows Space
Mouse Move the mouse horizontally Left button

After GAME OVER press Space (or click) to return to the intro.

What it demonstrates

  • fabgl::Scene game loop, sprites with several frames, pixel-precise collision detection
  • Drawing on the background bitmap (the shields are eroded pixel by pixel)
  • fabgl::SoundGenerator::playSamples() for sampled sound effects
  • Reading the keyboard state (isVKDown()) and the mouse (getNextDelta(), updateAbsolutePosition()) as game controllers

Hardware

  • VGA output (default pins)
  • Audio output on GPIO25
  • PS/2 keyboard on port 0 and/or PS/2 mouse on port 1

Build

See Building the examples.

Source code

Main file of the example, main/SpaceInvaders.cpp. The complete project is in the examples/VGA/SpaceInvaders folder.

1/*
2 Created by Fabrizio Di Vittorio (fdivitto2013@gmail.com) - <http://www.fabgl.com>
3 Copyright (c) 2019-2026 Fabrizio Di Vittorio.
4 All rights reserved.
5
6
7* Please contact fdivitto2013@gmail.com if you need a commercial license.
8
9
10* This library and related software is available under GPL v3.
11
12 FabGL is free software: you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation, either version 3 of the License, or
15 (at your option) any later version.
16
17 FabGL is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with FabGL. If not, see <http://www.gnu.org/licenses/>.
24 */
25
26
27#include "esp_random.h"
28#include "fabgl.h"
29
30
31// random integer in the range [0, max)
32static inline int randomInt(int max) { return max > 0 ? (int) (esp_random() % (uint32_t) max) : 0; }
33// random integer in the range [min, max)
34static inline int randomInt(int min, int max) { return max > min ? min + (int) (esp_random() % (uint32_t) (max - min)) : min; }
35
36#include "fabutils.h"
37
38#include "sprites.h"
39#include "sounds.h"
40
41
42
43
44using fabgl::iclamp;
45
46
47fabgl::VGAController DisplayController;
48fabgl::Canvas canvas(&DisplayController);
49fabgl::PS2Controller PS2Controller;
50SoundGenerator soundGenerator;
51
52
55// IntroScene
56
57struct IntroScene : public Scene {
58
59 static const int TEXTROWS = 4;
60 static const int TEXT_X = 130;
61 static const int TEXT_Y = 122;
62
63 static int controller_; // 1 = keyboard, 2 = mouse
64
65 int textRow_ = 0;
66 int textCol_ = 0;
67 int starting_ = 0;
68
69 SamplesGenerator * music_ = nullptr;
70
71 IntroScene()
72 : Scene(0, 20, DisplayController.getViewPortWidth(), DisplayController.getViewPortHeight())
73 {
74 }
75
76 void init()
77 {
78 canvas.setBrushColor(Color::Black);
79 canvas.clear();
80 canvas.setGlyphOptions(GlyphOptions().FillBackground(true));
81 canvas.selectFont(&fabgl::FONT_8x8);
82 canvas.setPenColor(Color::BrightWhite);
83 canvas.setGlyphOptions(GlyphOptions().DoubleWidth(1));
84 canvas.drawText(50, 15, "SPACE INVADERS");
85 canvas.setGlyphOptions(GlyphOptions().DoubleWidth(0));
86
87 canvas.setPenColor(Color::Green);
88 canvas.drawText(10, 40, "ESP32 version by Fabrizio Di Vittorio");
89 canvas.drawText(105, 55, "www.fabgl.com");
90
91 canvas.setPenColor(Color::Yellow);
92 canvas.drawText(72, 97, "* SCORE ADVANCE TABLE *");
93 canvas.drawBitmap(TEXT_X - 20 - 2, TEXT_Y, &bmpEnemyD);
94 canvas.drawBitmap(TEXT_X - 20, TEXT_Y + 15, &bmpEnemyA[0]);
95 canvas.drawBitmap(TEXT_X - 20, TEXT_Y + 30, &bmpEnemyB[0]);
96 canvas.drawBitmap(TEXT_X - 20, TEXT_Y + 45, &bmpEnemyC[0]);
97
98 canvas.setBrushColor(Color::Black);
99
100 controller_ = 0;
101
102 music_ = soundGenerator.playSamples(themeSoundSamples, sizeof(themeSoundSamples), 100, -1);
103 }
104
105 void update(int updateCount)
106 {
107 static const char * scoreText[] = {"= ? MISTERY", "= 30 POINTS", "= 20 POINTS", "= 10 POINTS" };
108
109 auto keyboard = PS2Controller.keyboard();
110 auto mouse = PS2Controller.mouse();
111
112 if (starting_) {
113
114 if (starting_ > 50) {
115 // stop music
116 soundGenerator.detach(music_);
117 // stop scene
118 stop();
119 }
120
121 ++starting_;
122 canvas.scroll(0, -5);
123
124 } else {
125 if (updateCount > 30 && updateCount % 5 == 0 && textRow_ < 4) {
126 int x = TEXT_X + textCol_ * canvas.getFontInfo()->width;
127 int y = TEXT_Y + textRow_ * 15 - 4;
128 canvas.setPenColor(Color::White);
129 canvas.drawChar(x, y, scoreText[textRow_][textCol_]);
130 ++textCol_;
131 if (scoreText[textRow_][textCol_] == 0) {
132 textCol_ = 0;
133 ++textRow_;
134 }
135 }
136
137 if (updateCount % 20 == 0) {
138 canvas.setPenColor(randomInt(256), randomInt(256), randomInt(256));
139 if (keyboard && keyboard->isKeyboardAvailable() && mouse && mouse->isMouseAvailable())
140 canvas.drawText(45, 75, "Press [SPACE] or CLICK to Play");
141 else if (keyboard && keyboard->isKeyboardAvailable())
142 canvas.drawText(80, 75, "Press [SPACE] to Play");
143 else if (mouse && mouse->isMouseAvailable())
144 canvas.drawText(105, 75, "Click to Play");
145 }
146
147 // handle keyboard or mouse (after two seconds)
148 if (updateCount > 50) {
149 if (keyboard && keyboard->isKeyboardAvailable() && keyboard->isVKDown(fabgl::VK_SPACE))
150 controller_ = 1; // select keyboard as controller
151 else if (mouse && mouse->isMouseAvailable() && mouse->deltaAvailable() && mouse->getNextDelta(nullptr, 0) && mouse->status().buttons.left)
152 controller_ = 2; // select mouse as controller
153 starting_ = (controller_ > 0); // start only when a controller has been selected
154 }
155 }
156 }
157
158 void collisionDetected(Sprite * spriteA, Sprite * spriteB, Point collisionPoint)
159 {
160 }
161
162};
163
164
165int IntroScene::controller_ = 0;
166
167
170// GameScene
171
172
173struct GameScene : public Scene {
174
175 enum SpriteType { TYPE_PLAYERFIRE, TYPE_ENEMIESFIRE, TYPE_ENEMY, TYPE_PLAYER, TYPE_SHIELD, TYPE_ENEMYMOTHER };
176
177 struct SISprite : Sprite {
178 SpriteType type;
179 uint8_t enemyPoints;
180 };
181
182 enum GameState { GAMESTATE_PLAYING, GAMESTATE_PLAYERKILLED, GAMESTATE_ENDGAME, GAMESTATE_GAMEOVER, GAMESTATE_LEVELCHANGING, GAMESTATE_LEVELCHANGED };
183
184 static const int PLAYERSCOUNT = 1;
185 static const int SHIELDSCOUNT = 4;
186 static const int ROWENEMIESCOUNT = 11;
187 static const int PLAYERFIRECOUNT = 1;
188 static const int ENEMIESFIRECOUNT = 1;
189 static const int ENEMYMOTHERCOUNT = 1;
190 static const int SPRITESCOUNT = PLAYERSCOUNT + SHIELDSCOUNT + 5 * ROWENEMIESCOUNT + PLAYERFIRECOUNT + ENEMIESFIRECOUNT + ENEMYMOTHERCOUNT;
191
192 static const int ENEMIES_X_SPACE = 16;
193 static const int ENEMIES_Y_SPACE = 10;
194 static const int ENEMIES_START_X = 0;
195 static const int ENEMIES_START_Y = 30;
196 static const int ENEMIES_STEP_X = 6;
197 static const int ENEMIES_STEP_Y = 8;
198
199 static const int PLAYER_Y = 170;
200
201 static int lives_;
202 static int score_;
203 static int level_;
204 static int hiScore_;
205
206 SISprite * sprites_ = new SISprite[SPRITESCOUNT];
207 SISprite * player_ = sprites_;
208 SISprite * shields_ = player_ + PLAYERSCOUNT;
209 SISprite * enemies_ = shields_ + SHIELDSCOUNT;
210 SISprite * enemiesR1_ = enemies_;
211 SISprite * enemiesR2_ = enemiesR1_ + ROWENEMIESCOUNT;
212 SISprite * enemiesR3_ = enemiesR2_ + ROWENEMIESCOUNT;
213 SISprite * enemiesR4_ = enemiesR3_ + ROWENEMIESCOUNT;
214 SISprite * enemiesR5_ = enemiesR4_ + ROWENEMIESCOUNT;
215 SISprite * playerFire_ = enemiesR5_ + ROWENEMIESCOUNT;
216 SISprite * enemiesFire_ = playerFire_ + PLAYERFIRECOUNT;
217 SISprite * enemyMother_ = enemiesFire_ + ENEMIESFIRECOUNT;
218
219 int playerVelX_ = 0; // used when controller is keyboard (0 = no move)
220 int playerAbsX_ = -1; // used when controller is mouse (-1 = no move)
221 int enemiesX_ = ENEMIES_START_X;
222 int enemiesY_ = ENEMIES_START_Y;
223
224 // enemiesDir_
225 // bit 0 : if 1 moving left
226 // bit 1 : if 1 moving right
227 // bit 2 : if 1 moving down
228 // bit 3 : if 0 before was moving left, if 1 before was moving right
229 // Allowed cases:
230 // 1 = moving left
231 // 2 = moving right
232 // 4 = moving down (before was moving left)
233 // 12 = moving down (before was moving right)
234
235 static constexpr int ENEMY_MOV_LEFT = 1;
236 static constexpr int ENEMY_MOV_RIGHT = 2;
237 static constexpr int ENEMY_MOV_DOWN_BEFORE_LEFT = 4;
238 static constexpr int ENEMY_MOV_DOWN_BEFORE_RIGHT = 12;
239
240 int enemiesDir_ = ENEMY_MOV_RIGHT;
241
242 int enemiesAlive_ = ROWENEMIESCOUNT * 5;
243 int enemiesSoundCount_ = 0;
244 SISprite * lastHitEnemy_ = nullptr;
245 GameState gameState_ = GAMESTATE_PLAYING;
246
247 bool updateScore_ = true;
248 int64_t pauseStart_;
249
250 Bitmap bmpShield[4] = { Bitmap(22, 16, shield_data, PixelFormat::Mask, RGB888(0, 255, 0), true),
251 Bitmap(22, 16, shield_data, PixelFormat::Mask, RGB888(0, 255, 0), true),
252 Bitmap(22, 16, shield_data, PixelFormat::Mask, RGB888(0, 255, 0), true),
253 Bitmap(22, 16, shield_data, PixelFormat::Mask, RGB888(0, 255, 0), true), };
254
255 GameScene()
256 : Scene(SPRITESCOUNT, 20, DisplayController.getViewPortWidth(), DisplayController.getViewPortHeight())
257 {
258 }
259
260 ~GameScene()
261 {
262 delete [] sprites_;
263 }
264
265 void initEnemy(Sprite * sprite, int points)
266 {
267 SISprite * s = (SISprite*) sprite;
268 s->addBitmap(&bmpEnemyExplosion);
269 s->type = TYPE_ENEMY;
270 s->enemyPoints = points;
271 addSprite(s);
272 }
273
274 void init()
275 {
276 // setup player
277 player_->addBitmap(&bmpPlayer)->addBitmap(&bmpPlayerExplosion[0])->addBitmap(&bmpPlayerExplosion[1]);
278 player_->moveTo(152, PLAYER_Y);
279 player_->type = TYPE_PLAYER;
280 addSprite(player_);
281 // setup player fire
282 playerFire_->addBitmap(&bmpPlayerFire);
283 playerFire_->visible = false;
284 playerFire_->type = TYPE_PLAYERFIRE;
285 addSprite(playerFire_);
286 // setup shields
287 for (int i = 0; i < 4; ++i) {
288 shields_[i].addBitmap(&bmpShield[i])->moveTo(35 + i * 75, 150);
289 shields_[i].isStatic = true;
290 shields_[i].type = TYPE_SHIELD;
291 addSprite(&shields_[i]);
292 }
293 // setup enemies
294 for (int i = 0; i < ROWENEMIESCOUNT; ++i) {
295 initEnemy( enemiesR1_[i].addBitmap(&bmpEnemyA[0])->addBitmap(&bmpEnemyA[1]), 30 );
296 initEnemy( enemiesR2_[i].addBitmap(&bmpEnemyB[0])->addBitmap(&bmpEnemyB[1]), 20 );
297 initEnemy( enemiesR3_[i].addBitmap(&bmpEnemyB[0])->addBitmap(&bmpEnemyB[1]), 20 );
298 initEnemy( enemiesR4_[i].addBitmap(&bmpEnemyC[0])->addBitmap(&bmpEnemyC[1]), 10 );
299 initEnemy( enemiesR5_[i].addBitmap(&bmpEnemyC[0])->addBitmap(&bmpEnemyC[1]), 10 );
300 }
301 // setup enemies fire
302 enemiesFire_->addBitmap(&bmpEnemiesFire[0])->addBitmap(&bmpEnemiesFire[1]);
303 enemiesFire_->visible = false;
304 enemiesFire_->type = TYPE_ENEMIESFIRE;
305 addSprite(enemiesFire_);
306 // setup enemy mother ship
307 enemyMother_->addBitmap(&bmpEnemyD)->addBitmap(&bmpEnemyExplosionRed);
308 enemyMother_->visible = false;
309 enemyMother_->type = TYPE_ENEMYMOTHER;
310 enemyMother_->enemyPoints = 100;
311 enemyMother_->moveTo(getWidth(), ENEMIES_START_Y);
312 addSprite(enemyMother_);
313
314 DisplayController.setSprites(sprites_, SPRITESCOUNT);
315
316 canvas.setBrushColor(Color::Black);
317 canvas.clear();
318
319 canvas.setPenColor(Color::Green);
320 canvas.drawLine(0, 180, 320, 180);
321
322 //canvas.setPenColor(Color::Yellow);
323 //canvas.drawRectangle(0, 0, getWidth() - 1, getHeight() - 1);
324
325 canvas.setGlyphOptions(GlyphOptions().FillBackground(true));
326 canvas.selectFont(&fabgl::FONT_4x6);
327 canvas.setPenColor(Color::White);
328 canvas.drawText(125, 20, "WE COME IN PEACE");
329 canvas.selectFont(&fabgl::FONT_8x8);
330 canvas.setPenColor(0, 255, 255);
331 canvas.drawText(2, 2, "SCORE");
332 canvas.setPenColor(0, 0, 255);
333 canvas.drawText(254, 2, "HI-SCORE");
334 canvas.setPenColor(255, 255, 255);
335 canvas.drawTextFmt(254, 181, "Level %02d", level_);
336
337 if (IntroScene::controller_ == 2) {
338 // setup mouse controller
339 auto mouse = PS2Controller.mouse();
340 mouse->setSampleRate(40); // reduce number of samples from mouse to reduce delays
341 mouse->setupAbsolutePositioner(getWidth() - player_->getWidth(), 0, false); // take advantage of mouse acceleration
342 }
343
344 showLives();
345 }
346
347 void drawScore()
348 {
349 canvas.setPenColor(255, 255, 255);
350 canvas.drawTextFmt(2, 14, "%05d", score_);
351 if (score_ > hiScore_)
352 hiScore_ = score_;
353 canvas.setPenColor(255, 255, 255);
354 canvas.drawTextFmt(266, 14, "%05d", hiScore_);
355 }
356
357 void moveEnemy(SISprite * enemy, int x, int y, bool * touchSide)
358 {
359 if (enemy->visible) {
360 if (x <= 0 || x >= getWidth() - enemy->getWidth())
361 *touchSide = true;
362 enemy->moveTo(x, y);
363 enemy->setFrame(enemy->getFrameIndex() ? 0 : 1);
364 updateSprite(enemy);
365 if (y >= PLAYER_Y) {
366 // enemies reach earth!
367 gameState_ = GAMESTATE_ENDGAME;
368 }
369 }
370 }
371
372 void gameOver()
373 {
374 // disable enemies drawing, so text can be over them
375 for (int i = 0; i < ROWENEMIESCOUNT * 5; ++i)
376 enemies_[i].allowDraw = false;
377 // show game over
378 canvas.setPenColor(0, 255, 0);
379 canvas.setBrushColor(0, 0, 0);
380 canvas.fillRectangle(80, 60, 240, 130);
381 canvas.drawRectangle(80, 60, 240, 130);
382 canvas.setGlyphOptions(GlyphOptions().DoubleWidth(1));
383 canvas.setPenColor(255, 255, 255);
384 canvas.drawText(90, 80, "GAME OVER");
385 canvas.setGlyphOptions(GlyphOptions().DoubleWidth(0));
386 canvas.setPenColor(0, 255, 0);
387 if (IntroScene::controller_ == 1)
388 canvas.drawText(110, 100, "Press [SPACE]");
389 else if (IntroScene::controller_ == 2)
390 canvas.drawText(93, 100, "Click to continue");
391 // change state
392 gameState_ = GAMESTATE_GAMEOVER;
393 level_ = 1;
394 lives_ = 3;
395 score_ = 0;
396 }
397
398 void levelChange()
399 {
400 ++level_;
401 // show game over
402 canvas.setPenColor(0, 255, 0);
403 canvas.drawRectangle(80, 80, 240, 110);
404 canvas.setGlyphOptions(GlyphOptions().DoubleWidth(1));
405 canvas.drawTextFmt(105, 88, "LEVEL %d", level_);
406 canvas.setGlyphOptions(GlyphOptions().DoubleWidth(0));
407 // change state
408 gameState_ = GAMESTATE_LEVELCHANGED;
409 pauseStart_ = esp_timer_get_time();
410 }
411
412 void update(int updateCount)
413 {
414 auto keyboard = PS2Controller.keyboard();
415 auto mouse = PS2Controller.mouse();
416
417 if (updateScore_) {
418 updateScore_ = false;
419 drawScore();
420 }
421
422 if (gameState_ == GAMESTATE_PLAYING || gameState_ == GAMESTATE_PLAYERKILLED) {
423
424 // move enemies and shoot
425 if ((updateCount % std::max(3, 21 - level_ * 2)) == 0) {
426 // handle enemy explosion
427 if (lastHitEnemy_) {
428 lastHitEnemy_->visible = false;
429 lastHitEnemy_ = nullptr;
430 }
431 // handle enemies movement
432 enemiesX_ += (-1 * (enemiesDir_ & 1) + (enemiesDir_ >> 1 & 1)) * ENEMIES_STEP_X;
433 enemiesY_ += (enemiesDir_ >> 2 & 1) * ENEMIES_STEP_Y;
434 bool touchSide = false;
435 for (int i = 0; i < ROWENEMIESCOUNT; ++i) {
436 moveEnemy(&enemiesR1_[i], enemiesX_ + i * ENEMIES_X_SPACE, enemiesY_ + 0 * ENEMIES_Y_SPACE, &touchSide);
437 moveEnemy(&enemiesR2_[i], enemiesX_ + i * ENEMIES_X_SPACE, enemiesY_ + 1 * ENEMIES_Y_SPACE, &touchSide);
438 moveEnemy(&enemiesR3_[i], enemiesX_ + i * ENEMIES_X_SPACE, enemiesY_ + 2 * ENEMIES_Y_SPACE, &touchSide);
439 moveEnemy(&enemiesR4_[i], enemiesX_ + i * ENEMIES_X_SPACE, enemiesY_ + 3 * ENEMIES_Y_SPACE, &touchSide);
440 moveEnemy(&enemiesR5_[i], enemiesX_ + i * ENEMIES_X_SPACE, enemiesY_ + 4 * ENEMIES_Y_SPACE, &touchSide);
441 }
442 switch (enemiesDir_) {
443 case ENEMY_MOV_DOWN_BEFORE_LEFT:
444 enemiesDir_ = ENEMY_MOV_RIGHT;
445 break;
446 case ENEMY_MOV_DOWN_BEFORE_RIGHT:
447 enemiesDir_ = ENEMY_MOV_LEFT;
448 break;
449 default:
450 if (touchSide)
451 enemiesDir_ = (enemiesDir_ == ENEMY_MOV_LEFT ? ENEMY_MOV_DOWN_BEFORE_LEFT : ENEMY_MOV_DOWN_BEFORE_RIGHT);
452 break;
453 }
454 // sound
455 ++enemiesSoundCount_;
456 soundGenerator.playSamples(invadersSoundSamples[enemiesSoundCount_ % 4], invadersSoundSamplesSize[enemiesSoundCount_ % 4]);
457 // handle enemies fire generation
458 if (!enemiesFire_->visible) {
459 int shottingEnemy = randomInt(enemiesAlive_);
460 for (int i = 0, a = 0; i < ROWENEMIESCOUNT * 5; ++i) {
461 if (enemies_[i].visible) {
462 if (a == shottingEnemy) {
463 enemiesFire_->x = enemies_[i].x + enemies_[i].getWidth() / 2;
464 enemiesFire_->y = enemies_[i].y + enemies_[i].getHeight() / 2;
465 enemiesFire_->visible = true;
466 break;
467 }
468 ++a;
469 }
470 }
471 }
472 }
473
474 if (gameState_ == GAMESTATE_PLAYERKILLED) {
475 // animate player explosion or restart playing other lives
476 if ((updateCount % 20) == 0) {
477 if (player_->getFrameIndex() == 1)
478 player_->setFrame(2);
479 else {
480 player_->setFrame(0);
481 gameState_ = GAMESTATE_PLAYING;
482 }
483 }
484 } else if (IntroScene::controller_ == 1 && playerVelX_ != 0) {
485 // move player using Keyboard
486 player_->x += playerVelX_;
487 player_->x = iclamp(player_->x, 0, getWidth() - player_->getWidth());
488 updateSprite(player_);
489 } else if (IntroScene::controller_ == 2 && playerAbsX_ != -1) {
490 // move player using Mouse
491 player_->x = playerAbsX_;
492 playerAbsX_ = -1;
493 updateSprite(player_);
494 }
495
496 // move player fire
497 if (playerFire_->visible) {
498 playerFire_->y -= 3;
499 if (playerFire_->y < ENEMIES_START_Y)
500 playerFire_->visible = false;
501 else
502 updateSpriteAndDetectCollisions(playerFire_);
503 }
504
505 // move enemies fire
506 if (enemiesFire_->visible) {
507 enemiesFire_->y += 2;
508 enemiesFire_->setFrame( enemiesFire_->getFrameIndex() ? 0 : 1 );
509 if (enemiesFire_->y > PLAYER_Y + player_->getHeight())
510 enemiesFire_->visible = false;
511 else
512 updateSpriteAndDetectCollisions(enemiesFire_);
513 }
514
515 // move enemy mother ship
516 if (enemyMother_->visible && enemyMother_->getFrameIndex() == 0) {
517 enemyMother_->x -= 1;
518 if (enemyMother_->x < -enemyMother_->getWidth())
519 enemyMother_->visible = false;
520 else
521 updateSprite(enemyMother_);
522 }
523
524 // start enemy mother ship
525 if ((updateCount % 800) == 0) {
526 soundGenerator.playSamples(motherShipSoundSamples, sizeof(motherShipSoundSamples), 100, 7000);
527 enemyMother_->x = getWidth();
528 enemyMother_->setFrame(0);
529 enemyMother_->visible = true;
530 }
531
532 // handle fire and movement from controller
533 if (IntroScene::controller_ == 1) {
534 // KEYBOARD controller
535 if (keyboard->isVKDown(fabgl::VK_LEFT))
536 playerVelX_ = -1;
537 else if (keyboard->isVKDown(fabgl::VK_RIGHT))
538 playerVelX_ = +1;
539 else
540 playerVelX_ = 0;
541 if (keyboard->isVKDown(fabgl::VK_SPACE) && !playerFire_->visible) // player fire?
542 fire();
543 } else if (IntroScene::controller_ == 2) {
544 // MOUSE controller
545 if (mouse->deltaAvailable()) {
546 MouseDelta delta;
547 mouse->getNextDelta(&delta);
548 mouse->updateAbsolutePosition(&delta);
549 playerAbsX_ = mouse->status().X;
550 if (delta.buttons.left && !playerFire_->visible) // player fire?
551 fire();
552 }
553 }
554 }
555
556 if (gameState_ == GAMESTATE_ENDGAME)
557 gameOver();
558
559 if (gameState_ == GAMESTATE_LEVELCHANGING)
560 levelChange();
561
562 if (gameState_ == GAMESTATE_LEVELCHANGED && esp_timer_get_time() >= pauseStart_ + 2500000) {
563 stop(); // restart from next level
564 DisplayController.removeSprites();
565 }
566
567 if (gameState_ == GAMESTATE_GAMEOVER) {
568
569 // animate player burning
570 if ((updateCount % 20) == 0)
571 player_->setFrame( player_->getFrameIndex() == 1 ? 2 : 1);
572
573 // wait for SPACE or click from mouse
574 if ((IntroScene::controller_ == 1 && keyboard->isVKDown(fabgl::VK_SPACE)) ||
575 (IntroScene::controller_ == 2 && mouse->deltaAvailable() && mouse->getNextDelta(nullptr, 0) && mouse->status().buttons.left)) {
576 stop();
577 DisplayController.removeSprites();
578 }
579
580 }
581
582 DisplayController.refreshSprites();
583 }
584
585 // player shoots
586 void fire()
587 {
588 playerFire_->moveTo(player_->x + 7, player_->y - 1)->visible = true;
589 soundGenerator.playSamples(fireSoundSamples, sizeof(fireSoundSamples));
590 }
591
592 // shield has been damaged
593 void damageShield(SISprite * shield, Point collisionPoint)
594 {
595 Bitmap * shieldBitmap = shield->getFrame();
596 int x = collisionPoint.X - shield->x;
597 int y = collisionPoint.Y - shield->y;
598 shieldBitmap->setPixel(x, y, 0);
599 for (int i = 0; i < 32; ++i) {
600 int px = iclamp(x + randomInt(-4, 5), 0, shield->getWidth() - 1);
601 int py = iclamp(y + randomInt(-4, 5), 0, shield->getHeight() - 1);
602 shieldBitmap->setPixel(px, py, 0);
603 }
604 }
605
606 void showLives()
607 {
608 canvas.fillRectangle(1, 181, 100, 195);
609 canvas.setPenColor(Color::White);
610 canvas.drawTextFmt(5, 181, "%d", lives_);
611 for (int i = 0; i < lives_; ++i)
612 canvas.drawBitmap(15 + i * (bmpPlayer.width + 5), 183, &bmpPlayer);
613 }
614
615 void collisionDetected(Sprite * spriteA, Sprite * spriteB, Point collisionPoint)
616 {
617 SISprite * sA = (SISprite*) spriteA;
618 SISprite * sB = (SISprite*) spriteB;
619 if (!lastHitEnemy_ && sA->type == TYPE_PLAYERFIRE && sB->type == TYPE_ENEMY) {
620 // player fire hits an enemy
621 soundGenerator.playSamples(shootSoundSamples, sizeof(shootSoundSamples));
622 sA->visible = false;
623 sB->setFrame(2);
624 lastHitEnemy_ = sB;
625 --enemiesAlive_;
626 score_ += sB->enemyPoints;
627 updateScore_ = true;
628 if (enemiesAlive_ == 0)
629 gameState_ = GAMESTATE_LEVELCHANGING;
630 }
631 if (sB->type == TYPE_SHIELD) {
632 // something hits a shield
633 sA->visible = false;
634 damageShield(sB, collisionPoint);
635 sB->allowDraw = true;
636 }
637 if (gameState_ == GAMESTATE_PLAYING && sA->type == TYPE_ENEMIESFIRE && sB->type == TYPE_PLAYER) {
638 // enemies fire hits player
639 soundGenerator.playSamples(explosionSoundSamples, sizeof(explosionSoundSamples));
640 --lives_;
641 gameState_ = lives_ ? GAMESTATE_PLAYERKILLED : GAMESTATE_ENDGAME;
642 player_->setFrame(1);
643 showLives();
644 }
645 if (sB->type == TYPE_ENEMYMOTHER) {
646 // player fire hits enemy mother ship
647 soundGenerator.playSamples(mothershipexplosionSoundSamples, sizeof(mothershipexplosionSoundSamples));
648 sA->visible = false;
649 sB->setFrame(1);
650 lastHitEnemy_ = sB;
651 score_ += sB->enemyPoints;
652 updateScore_ = true;
653 }
654 }
655
656};
657
658int GameScene::hiScore_ = 0;
659int GameScene::level_ = 1;
660int GameScene::lives_ = 3;
661int GameScene::score_ = 0;
662
663
666
667
668
669void setup()
670{
671 PS2Controller.begin(PS2Preset::KeyboardPort0_MousePort1, KbdMode::GenerateVirtualKeys);
672
673 DisplayController.begin();
674 DisplayController.setResolution(VGA_320x200_75Hz);
675
676 // adjust this to center screen in your monitor
677 //DisplayController.moveScreen(20, -2);
678}
679
680
681void loop()
682{
683 if (GameScene::level_ == 1) {
684 IntroScene introScene;
685 introScene.start();
686 }
687 GameScene gameScene;
688 gameScene.start();
689}
690
691
692extern "C" void app_main()
693{
694 setup();
695 while (true)
696 loop();
697}
Samples generator.
Definition soundgen.h:338
Scene is an abstract class that encapsulates the functionality of a scene (sprites,...
Definition scene.h:59
void detach(WaveformGenerator *value)
Detaches a waveform generator.
Definition soundgen.cpp:717
SamplesGenerator * playSamples(int8_t const *data, int length, int volume=100, int durationMS=0)
Plays the specified samples.
Definition soundgen.cpp:689
SoundGenerator handles audio output.
Definition soundgen.h:382
void setSprites(T *sprites, int count)
Sets the list of active sprites.
void removeSprites()
Empties the list of active sprites.
void refreshSprites()
Forces the sprites to be updated.
Provides a set of drawing methods.
Definition canvas.h:73
bool setSampleRate(int value)
Sets the maximum rate at which the mouse reports movements.
Definition mouse.cpp:209
static Mouse * mouse()
Returns the Mouse object automatically created by PS2Controller.
static Keyboard * keyboard()
Returns the Keyboard object automatically created by PS2Controller.
static void begin(gpio_num_t port0_clkGPIO, gpio_num_t port0_datGPIO, gpio_num_t port1_clkGPIO=GPIO_UNUSED, gpio_num_t port1_datGPIO=GPIO_UNUSED)
Initializes the PS/2 device controller.
PS/2 device controller.
void begin(gpio_num_t redGPIO, gpio_num_t greenGPIO, gpio_num_t blueGPIO, gpio_num_t HSyncGPIO, gpio_num_t VSyncGPIO)
Initializer for 8 colors (5 GPIOs).
VGA bitmapped display controller (64 colors).
Single include file of the FabGL library.
#define VGA_320x200_75Hz
Definition fabglconf.h:183
This file contains utility classes and functions.
@ VK_SPACE
Definition fabutils.h:1377
@ VK_LEFT
Definition fabutils.h:1537
@ VK_RIGHT
Definition fabutils.h:1539
MouseButtons buttons
Definition mouse.h:61
int16_t X
Definition fabutils.h:244
int16_t Y
Definition fabutils.h:245
Specifies glyph painting options.