- Ignore all input for ~1.2 s after power-up/reset (INPUT_GRACE_MS): the keyboard controller can emit stale bytes and pins can float, which used to start a game right after a restart. - High score + volume survive power cycles: Preferences (NVS, 'mc' namespace) loaded in setup(), saved on game over and on every volume key (U/V/M). arduino-esp32 commits NVS in end(), so savePrefs() does putUInt x2 + end() + begin() reopen. - SoundEngine::setVolume() restores a saved level (0 = stay muted, lastVol_ keeps unmute working). - Emulator: file-backed Preferences shim (mc-prefs.cfg, gitignored) so persistence is testable on the desktop.
1638 lines
49 KiB
Arduino
1638 lines
49 KiB
Arduino
/**
|
|
* @file MissileCommand.ino
|
|
* @brief Classic Missile Command for the LilyGo T-Deck (ESP32-S3).
|
|
*
|
|
* Controls
|
|
* Trackball : move the aiming crosshair
|
|
* Trackball press : fire from the closest battery with ammo
|
|
* Screen tap : move crosshair + fire
|
|
* Keyboard A / S / D : fire from left / center / right battery
|
|
*
|
|
* Rendering: incremental drawing with TFT_eSPI (no full frame buffer).
|
|
* Missile trails are persistent lines, explosions are animated circles
|
|
* that repair the terrain underneath when they clear.
|
|
*
|
|
* Sound: I2S speaker via sound_engine (see sound_engine.cpp). Each wave
|
|
* opens with the original-style attack alarm (four falling tones), then
|
|
* layered sweeps/noise effects for launches, explosions and city hits.
|
|
*/
|
|
|
|
#include <Arduino.h>
|
|
#include <SPI.h>
|
|
#include <TFT_eSPI.h>
|
|
#include <Wire.h>
|
|
#include <Preferences.h>
|
|
#include "utilities.h"
|
|
#include "TouchDrvGT911.hpp"
|
|
#include "sound_engine.h"
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Hardware
|
|
// ---------------------------------------------------------------------------
|
|
TFT_eSPI tft;
|
|
TouchDrvGT911 touch;
|
|
SoundEngine sound;
|
|
|
|
static bool touchAvail = false;
|
|
static bool kbAvail = false;
|
|
|
|
// Screen metrics (filled in during setup, rotation 1 -> 320x240)
|
|
static int scrW, scrH, groundY;
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Tunables
|
|
// ---------------------------------------------------------------------------
|
|
static const int FRAME_MS = 33; // ~30 fps
|
|
static const int CITY_COUNT = 6;
|
|
static const int AMMO_MAX = 10;
|
|
static const int MAX_BOMBS = 20;
|
|
static const int MAX_ROCKETS = 8;
|
|
static const int MAX_EXPL = 12;
|
|
static const int CROSS_STEP = 14; // px per trackball pulse
|
|
static const int CROSS_MAX_STEP = 48; // px/frame cap: fast rolls accelerate
|
|
static const float ROCKET_SPEED = 6.0f; // px / frame
|
|
static const float ROCKET_RADIUS = 24.0f;
|
|
static const uint32_t BANNER_MS = 1500;
|
|
static const uint32_t BONUS_MS = 3400;
|
|
// Ignore all input during the first moments after power-up/reset: the
|
|
// keyboard controller may still emit stale bytes and pins may float, which
|
|
// used to start a game right after a restart.
|
|
static const uint32_t INPUT_GRACE_MS = 1200;
|
|
static const float ROCKET_SPEED_SIDE = 3.4f; // side batteries fire slow rockets;
|
|
// only the center battery is fast
|
|
static const int MAX_CRAFTS = 2; // bombers + satellites
|
|
static const float WIGGLE_AMP = 2.2f; // smart bomb wiggle amplitude (px)
|
|
static const float WIGGLE_FREQ = 0.07f; // wave number (wavelength ~90 px)
|
|
|
|
static const uint16_t EXPL_COLORS[3] = { TFT_WHITE, TFT_ORANGE, TFT_YELLOW };
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Entities
|
|
// ---------------------------------------------------------------------------
|
|
struct Bomb {
|
|
bool alive;
|
|
float x, y; // current tip position
|
|
float hx, hy; // last head-dot position (for clean overpainting)
|
|
float d; // distance travelled along the flight path
|
|
float len; // total path length to the target
|
|
float sx, sy; // origin
|
|
float tx, ty; // target
|
|
float dirx, diry; // unit direction (basis of the path)
|
|
float speed; // px per frame
|
|
float wob; // wiggle phase offset (smart bombs)
|
|
bool smart;
|
|
};
|
|
|
|
struct Rocket {
|
|
bool alive;
|
|
float x, y;
|
|
float tx, ty;
|
|
float dirx, diry;
|
|
float speed;
|
|
};
|
|
|
|
struct Explosion {
|
|
bool alive;
|
|
float x, y;
|
|
float r, maxR, vel;
|
|
int hold;
|
|
};
|
|
|
|
// Bomber planes and satellites cross the sky and drop bombs of their own
|
|
// (arcade rule). Shooting them down pays a bonus: plane 100x, satellite
|
|
// 250x the current multiplier.
|
|
struct Craft {
|
|
bool alive;
|
|
bool sat; // false: bomber plane, true: satellite
|
|
int x, y;
|
|
int dir; // -1: left, +1: right
|
|
uint32_t lastDrop;
|
|
};
|
|
|
|
static Bomb bombs[MAX_BOMBS];
|
|
static Rocket rockets[MAX_ROCKETS];
|
|
static Explosion expls[MAX_EXPL];
|
|
static Craft crafts[MAX_CRAFTS];
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Game state
|
|
// ---------------------------------------------------------------------------
|
|
enum GameState { ST_TITLE, ST_BANNER, ST_PLAYING, ST_BONUS, ST_GAMEOVER };
|
|
static GameState gameState = ST_TITLE;
|
|
static uint32_t stateT0 = 0;
|
|
static uint32_t frameCount = 0;
|
|
|
|
static int cityX[CITY_COUNT];
|
|
static bool cityAlive[CITY_COUNT];
|
|
static int BATX[3];
|
|
static bool batAlive[3];
|
|
static int batAmmo[3];
|
|
|
|
static int score = 0;
|
|
static int highScore = 0;
|
|
static int wave = 1;
|
|
|
|
static int bombsSpawned = 0;
|
|
static int waveQuota = 0;
|
|
static float bombSpeed = 0.5f; // px per frame
|
|
static uint32_t spawnIntervalMs = 1400;
|
|
static uint32_t lastSpawnMs = 0;
|
|
static int waveKills = 0;
|
|
static bool spawningStopped = false;
|
|
static int citiesLostWave = 0; // classic rule: max 3 city kills per wave
|
|
|
|
// Bonus cities: earned at preset score intervals (arcade: every 10,000),
|
|
// kept in reserve and automatically deployed between waves as needed.
|
|
static int reserveCities = 0;
|
|
static int nextCityAt = 10000;
|
|
static uint32_t cityOSDUntil = 0;
|
|
|
|
static struct {
|
|
int x, y; // current
|
|
int dx, dy; // last drawn position (erase here, NOT at px/py: several
|
|
// moves can happen per frame and would leave ghosts)
|
|
bool drawn;
|
|
bool moved;
|
|
} cross;
|
|
|
|
static uint32_t volOSDUntil = 0; // volume bar overlay timer
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Forward declarations
|
|
// ---------------------------------------------------------------------------
|
|
static void drawWorld();
|
|
static void drawHUD();
|
|
static void drawAmmoPyramid(int bat);
|
|
static void redrawGroundArea(float cx, float cy, float r);
|
|
static void spawnBombAt(float sx, float sy, bool smart, bool fromCraft);
|
|
static void resetGame();
|
|
static void startWave(int n);
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Sound helpers
|
|
// ---------------------------------------------------------------------------
|
|
static void sfx(SndType t, uint16_t f0, uint16_t f1, uint16_t d, uint16_t a)
|
|
{
|
|
SndEvent e;
|
|
e.type = t;
|
|
e.freq = f0;
|
|
e.freq2 = f1;
|
|
e.dur = d;
|
|
e.amp = a;
|
|
sound.play(e);
|
|
}
|
|
|
|
static void sfxTone(uint16_t f, uint16_t d, uint16_t a) { sfx(SND_TONE, f, f, d, a); }
|
|
static void sfxSweep(uint16_t f0, uint16_t f1, uint16_t d, uint16_t a) { sfx(SND_SWEEP, f0, f1, d, a); }
|
|
static void sfxNoise(uint16_t d, uint16_t a) { sfx(SND_NOISE, 0, 0, d, a); }
|
|
|
|
static void sfxDeny() { sfxTone(220, 90, 8000); }
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Persistent settings (NVS): high score + volume survive power cycles
|
|
// ---------------------------------------------------------------------------
|
|
static Preferences prefs;
|
|
|
|
static void savePrefs()
|
|
{
|
|
prefs.putUInt("hi", (uint32_t)highScore);
|
|
prefs.putUInt("vol", (uint32_t)sound.volume());
|
|
prefs.end(); // commit to NVS
|
|
prefs.begin("mc", false); // reopen for the next save
|
|
}
|
|
|
|
// Attack alarm, played once as a wave-start intro (like the original):
|
|
// four falling tones, then gameplay begins and the alarm is done.
|
|
static void sfxSirenIntro()
|
|
{
|
|
for (int i = 0; i < 4; i++) {
|
|
sfxSweep(760 - i * 40, 330, 280, 12000);
|
|
}
|
|
}
|
|
|
|
static void sfxFire()
|
|
{
|
|
sfxSweep(280, 1100, 70, 8000); // rising "pew"
|
|
sfxNoise(50, 9000); // launch puff
|
|
}
|
|
|
|
static void sfxKill() // enemy warhead destroyed
|
|
{
|
|
sfxNoise(150, 20000);
|
|
sfxSweep(500, 120, 150, 12000);
|
|
}
|
|
|
|
static void sfxBoom() // counter-missile explosion
|
|
{
|
|
sfxNoise(260, 24000);
|
|
sfxSweep(200, 55, 260, 16000); // deep rumble tail
|
|
}
|
|
|
|
static void sfxCityBoom()
|
|
{
|
|
sfxSweep(150, 40, 420, 22000); // very deep boom
|
|
sfxNoise(380, 24000);
|
|
}
|
|
|
|
static void sfxWaveClear()
|
|
{
|
|
sfxTone(800, 90, 9000);
|
|
sfxTone(1000, 90, 9000);
|
|
sfxTone(1300, 140, 9000);
|
|
}
|
|
|
|
static void sfxGameOver()
|
|
{
|
|
sfxSweep(600, 300, 220, 12000);
|
|
sfxSweep(450, 200, 220, 12000);
|
|
sfxSweep(300, 90, 420, 14000);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Layout / terrain drawing
|
|
// ---------------------------------------------------------------------------
|
|
static void layout()
|
|
{
|
|
BATX[0] = 18;
|
|
BATX[1] = scrW / 2;
|
|
BATX[2] = scrW - 18;
|
|
float frac[CITY_COUNT] = { 0.18f, 0.30f, 0.42f, 0.58f, 0.70f, 0.82f };
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
cityX[i] = (int)(scrW * frac[i]);
|
|
}
|
|
}
|
|
|
|
static void drawGround()
|
|
{
|
|
tft.fillRect(0, groundY, scrW, scrH - groundY, TFT_DARKGREEN);
|
|
tft.drawFastHLine(0, groundY, scrW, TFT_GREEN);
|
|
}
|
|
|
|
static void drawCity(int i)
|
|
{
|
|
int x = cityX[i];
|
|
if (cityAlive[i]) {
|
|
tft.fillRect(x - 10, groundY - 12, 7, 12, TFT_WHITE);
|
|
tft.fillRect(x - 2, groundY - 9, 5, 9, TFT_WHITE);
|
|
tft.fillRect(x + 4, groundY - 14, 6, 14, TFT_WHITE);
|
|
} else {
|
|
tft.fillRect(x - 10, groundY - 4, 20, 4, TFT_DARKGREY);
|
|
}
|
|
}
|
|
|
|
static void drawBattery(int i)
|
|
{
|
|
int x = BATX[i];
|
|
if (batAlive[i]) {
|
|
tft.fillTriangle(x - 5, groundY, x + 5, groundY, x, groundY - 7, TFT_BLUE);
|
|
} else {
|
|
tft.fillRect(x - 4, groundY - 3, 9, 3, TFT_DARKGREY);
|
|
}
|
|
drawAmmoPyramid(i);
|
|
}
|
|
|
|
// Classic pyramid of up-pointing triangles above each battery
|
|
static void drawAmmoPyramid(int bat)
|
|
{
|
|
int x = BATX[bat];
|
|
tft.fillRect(x - 12, groundY - 32, 25, 24, TFT_BLACK);
|
|
if (!batAlive[bat]) return;
|
|
|
|
int n = batAmmo[bat];
|
|
int drawn = 0;
|
|
for (int row = 0; row < 4 && drawn < n; row++) {
|
|
int count = 4 - row; // bottom row has 4
|
|
int rowY = groundY - 9 - row * 5; // base line of this row
|
|
for (int t = 0; t < count && drawn < n; t++, drawn++) {
|
|
int cx = x - (count - 1) * 3 + t * 6;
|
|
tft.fillTriangle(cx - 2, rowY, cx + 2, rowY, cx, rowY - 4, TFT_CYAN);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void stars(int n)
|
|
{
|
|
for (int i = 0; i < n; i++) {
|
|
int x = random(0, scrW);
|
|
int y = random(0, groundY - 50);
|
|
tft.drawPixel(x, y, random(10) < 8 ? TFT_DARKGREY : TFT_WHITE);
|
|
}
|
|
}
|
|
|
|
static void drawWorld()
|
|
{
|
|
tft.fillScreen(TFT_BLACK);
|
|
stars(70);
|
|
drawGround();
|
|
for (int i = 0; i < CITY_COUNT; i++) drawCity(i);
|
|
for (int i = 0; i < 3; i++) drawBattery(i);
|
|
drawHUD();
|
|
cross.drawn = false;
|
|
}
|
|
|
|
// Redraw the part of the terrain that an explosion circle just erased.
|
|
static void redrawGroundArea(float cx, float cy, float r)
|
|
{
|
|
(void)cy; // the strip is redrawn at ground level regardless of blast height
|
|
int x0 = (int)(cx - r) - 2;
|
|
int x1 = (int)(cx + r) + 2;
|
|
if (x0 < 0) x0 = 0;
|
|
if (x1 > scrW - 1) x1 = scrW - 1;
|
|
if (x1 < x0) return;
|
|
tft.fillRect(x0, groundY, x1 - x0 + 1, scrH - groundY, TFT_DARKGREEN);
|
|
tft.drawFastHLine(x0, groundY, x1 - x0 + 1, TFT_GREEN);
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
if (cityX[i] + 10 >= x0 && cityX[i] - 10 <= x1) drawCity(i);
|
|
}
|
|
for (int i = 0; i < 3; i++) {
|
|
if (BATX[i] + 12 >= x0 && BATX[i] - 12 <= x1) drawBattery(i);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// HUD
|
|
// ---------------------------------------------------------------------------
|
|
static int scoreMult()
|
|
{
|
|
int m = 1 + (wave - 1) / 2;
|
|
return m > 6 ? 6 : m;
|
|
}
|
|
|
|
// All scoring goes through here: at preset score intervals the player
|
|
// earns a bonus city that is kept in reserve (deployed between waves).
|
|
static void addScore(int pts)
|
|
{
|
|
score += pts;
|
|
while (score >= nextCityAt) {
|
|
reserveCities++;
|
|
nextCityAt += 10000;
|
|
cityOSDUntil = millis() + 1400;
|
|
drawHUD(); // show the new reserve count
|
|
sfxTone(1500, 60, 9000);
|
|
sfxTone(1900, 80, 9000);
|
|
}
|
|
if (score > highScore) highScore = score;
|
|
drawHUD(); // callers may go on drawing; HUD stays current
|
|
}
|
|
|
|
static void drawHUD()
|
|
{
|
|
tft.fillRect(0, 0, scrW, 16, TFT_BLACK);
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(TFT_WHITE, TFT_BLACK);
|
|
tft.setTextDatum(TL_DATUM);
|
|
tft.drawString("WAVE " + String(wave), 4, 2);
|
|
tft.setTextDatum(TC_DATUM);
|
|
tft.drawString(String(score), scrW / 2, 2);
|
|
tft.setTextDatum(TR_DATUM);
|
|
String hud = "x" + String(scoreMult()) + " HI " + String(highScore);
|
|
if (reserveCities > 0) hud = hud + " +" + String(reserveCities);
|
|
tft.drawString(hud, scrW - 4, 2);
|
|
tft.setTextDatum(MC_DATUM);
|
|
}
|
|
|
|
// Brief volume bar shown after U / V / M keypresses
|
|
static void drawVolumeOSD()
|
|
{
|
|
static bool shown = false;
|
|
bool want = millis() < volOSDUntil;
|
|
int bx = scrW - 108, by = 20;
|
|
if (want) {
|
|
shown = true;
|
|
tft.fillRect(bx, by, 104, 14, TFT_BLACK);
|
|
tft.drawRect(bx, by, 104, 14, TFT_DARKGREY);
|
|
int vol = sound.volume();
|
|
if (vol == 0) {
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(TFT_RED, TFT_BLACK);
|
|
tft.setTextDatum(MC_DATUM);
|
|
tft.drawString("MUTE", bx + 52, by + 7);
|
|
} else {
|
|
for (int i = 0; i < SoundEngine::VOL_MAX; i++) {
|
|
if (i < vol) {
|
|
tft.fillRect(bx + 3 + i * 12, by + 3, 9, 8, TFT_GREEN);
|
|
}
|
|
}
|
|
}
|
|
} else if (shown) {
|
|
shown = false;
|
|
tft.fillRect(bx - 2, by - 2, 108, 18, TFT_BLACK);
|
|
}
|
|
}
|
|
|
|
// Brief notice when a bonus city is earned (like the original's award)
|
|
static void drawBonusCityOSD()
|
|
{
|
|
static bool shown = false;
|
|
bool want = millis() < cityOSDUntil;
|
|
int by = 20;
|
|
if (want) {
|
|
shown = true;
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(TFT_GOLD, TFT_BLACK);
|
|
tft.setTextDatum(TL_DATUM);
|
|
tft.drawString("BONUS CITY EARNED", 4, by);
|
|
tft.setTextDatum(MC_DATUM);
|
|
} else if (shown) {
|
|
shown = false;
|
|
tft.fillRect(0, by - 2, 140, 18, TFT_BLACK);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Crosshair
|
|
// ---------------------------------------------------------------------------
|
|
static void drawCrossAt(int x, int y, uint16_t c)
|
|
{
|
|
tft.drawFastHLine(x - 5, y, 4, c);
|
|
tft.drawFastHLine(x + 1, y, 4, c);
|
|
tft.drawFastVLine(x, y - 5, 4, c);
|
|
tft.drawFastVLine(x, y + 1, 4, c);
|
|
}
|
|
|
|
static void renderCross()
|
|
{
|
|
if (!cross.drawn || cross.moved) {
|
|
if (cross.drawn) drawCrossAt(cross.dx, cross.dy, TFT_BLACK);
|
|
drawCrossAt(cross.x, cross.y, TFT_GREEN);
|
|
cross.dx = cross.x;
|
|
cross.dy = cross.y;
|
|
cross.drawn = true;
|
|
cross.moved = false;
|
|
}
|
|
}
|
|
|
|
static void clampCross()
|
|
{
|
|
if (cross.x < 2) cross.x = 2;
|
|
if (cross.x > scrW - 3) cross.x = scrW - 3;
|
|
if (cross.y < 18) cross.y = 18;
|
|
if (cross.y > groundY - 3) cross.y = groundY - 3;
|
|
}
|
|
|
|
static void nudgeCross(int dx, int dy)
|
|
{
|
|
if (gameState != ST_PLAYING && gameState != ST_BANNER) return;
|
|
cross.x += dx;
|
|
cross.y += dy;
|
|
clampCross();
|
|
cross.moved = true;
|
|
}
|
|
|
|
static void setCross(int x, int y)
|
|
{
|
|
if (gameState != ST_PLAYING && gameState != ST_BANNER) return;
|
|
cross.x = x;
|
|
cross.y = y;
|
|
clampCross();
|
|
cross.moved = true;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Entities
|
|
// ---------------------------------------------------------------------------
|
|
static void spawnExpl(float x, float y, float maxR, float vel)
|
|
{
|
|
for (int i = 0; i < MAX_EXPL; i++) {
|
|
if (!expls[i].alive) {
|
|
expls[i].alive = true;
|
|
expls[i].x = x;
|
|
expls[i].y = y;
|
|
expls[i].r = 0;
|
|
expls[i].maxR = maxR;
|
|
expls[i].vel = vel;
|
|
expls[i].hold = 0;
|
|
return;
|
|
}
|
|
}
|
|
// no free slot: replace the smallest one
|
|
int best = 0;
|
|
for (int i = 1; i < MAX_EXPL; i++) {
|
|
if (expls[i].r < expls[best].r) best = i;
|
|
}
|
|
expls[best].x = x;
|
|
expls[best].y = y;
|
|
expls[best].maxR = maxR;
|
|
expls[best].vel = vel;
|
|
expls[best].r = 0;
|
|
expls[best].hold = 0;
|
|
}
|
|
|
|
static int pickTargetX()
|
|
{
|
|
int cand[9];
|
|
int n = 0;
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
if (cityAlive[i]) cand[n++] = cityX[i];
|
|
}
|
|
for (int i = 0; i < 3; i++) {
|
|
if (batAlive[i]) cand[n++] = BATX[i];
|
|
}
|
|
if (n == 0) return random(10, scrW - 10);
|
|
int tx = cand[random(0, n)] + random(-6, 7);
|
|
if (tx < 4) tx = 4;
|
|
if (tx > scrW - 5) tx = scrW - 5;
|
|
return tx;
|
|
}
|
|
|
|
static void spawnBombAt(float sx, float sy, bool smart, bool fromCraft)
|
|
{
|
|
for (int i = 0; i < MAX_BOMBS; i++) {
|
|
Bomb &b = bombs[i];
|
|
if (b.alive) continue;
|
|
|
|
b.smart = smart;
|
|
b.sx = sx;
|
|
b.sy = sy;
|
|
b.tx = pickTargetX();
|
|
b.ty = groundY;
|
|
float dx = b.tx - b.sx;
|
|
float dy = b.ty - b.sy;
|
|
float len = sqrtf(dx * dx + dy * dy);
|
|
b.dirx = dx / len;
|
|
b.diry = dy / len;
|
|
b.len = len;
|
|
b.d = 0;
|
|
b.speed = bombSpeed * (b.smart ? 1.25f : 1.0f);
|
|
b.x = b.sx;
|
|
b.y = b.sy;
|
|
b.hx = b.sx;
|
|
b.hy = b.sy;
|
|
b.wob = random(0, 628) * 0.01f;
|
|
b.alive = true;
|
|
if (!fromCraft) bombsSpawned++; // craft bombs don't use the quota
|
|
return;
|
|
}
|
|
}
|
|
|
|
static void spawnBomb()
|
|
{
|
|
// spawn below the HUD band so trails never touch the score text
|
|
bool smart = random(100) < (wave >= 3 ? (2 + wave > 28 ? 28 : 2 + wave) : 0);
|
|
spawnBombAt(random(4, scrW - 4), 22, smart, false);
|
|
}
|
|
|
|
static bool anyBombAlive()
|
|
{
|
|
for (int i = 0; i < MAX_BOMBS; i++) if (bombs[i].alive) return true;
|
|
return false;
|
|
}
|
|
|
|
static bool anyRocketAlive()
|
|
{
|
|
for (int i = 0; i < MAX_ROCKETS; i++) if (rockets[i].alive) return true;
|
|
return false;
|
|
}
|
|
|
|
static bool anyExplAlive()
|
|
{
|
|
for (int i = 0; i < MAX_EXPL; i++) if (expls[i].alive) return true;
|
|
return false;
|
|
}
|
|
|
|
static bool waveDone()
|
|
{
|
|
return bombsSpawned >= waveQuota && !anyBombAlive() && !anyRocketAlive() && !anyExplAlive();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Firing
|
|
// ---------------------------------------------------------------------------
|
|
static void launch(int bat, int tx, int ty)
|
|
{
|
|
if (!batAlive[bat] || batAmmo[bat] <= 0) {
|
|
sfxDeny();
|
|
return;
|
|
}
|
|
for (int i = 0; i < MAX_ROCKETS; i++) {
|
|
Rocket &r = rockets[i];
|
|
if (r.alive) continue;
|
|
batAmmo[bat]--;
|
|
drawAmmoPyramid(bat);
|
|
|
|
r.x = BATX[bat];
|
|
r.y = groundY - 8;
|
|
r.tx = tx;
|
|
r.ty = ty;
|
|
float dx = tx - r.x;
|
|
float dy = ty - r.y;
|
|
float len = sqrtf(dx * dx + dy * dy);
|
|
if (len < 1) len = 1;
|
|
r.dirx = dx / len;
|
|
r.diry = dy / len;
|
|
// classic rule: the center battery fires much faster rockets; only
|
|
// these can realistically catch smart bombs
|
|
r.speed = (bat == 1) ? ROCKET_SPEED : ROCKET_SPEED_SIDE;
|
|
r.alive = true;
|
|
sfxFire();
|
|
return;
|
|
}
|
|
sfxDeny(); // no free rocket slot
|
|
}
|
|
|
|
static void fireAuto()
|
|
{
|
|
int best = -1;
|
|
int bestD = 1 << 30;
|
|
for (int i = 0; i < 3; i++) {
|
|
if (batAlive[i] && batAmmo[i] > 0) {
|
|
int d = abs(BATX[i] - cross.x);
|
|
if (d < bestD) {
|
|
bestD = d;
|
|
best = i;
|
|
}
|
|
}
|
|
}
|
|
if (best < 0) {
|
|
sfxDeny();
|
|
return;
|
|
}
|
|
launch(best, cross.x, cross.y);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Trails (the 2600 look: flashing streaks behind a bright steady dot)
|
|
// ---------------------------------------------------------------------------
|
|
// Thick line: `w` parallel lines offset perpendicular to the dominant axis.
|
|
static void drawThickLine(int x0, int y0, int x1, int y1, int w, uint16_t c)
|
|
{
|
|
int dx = (x1 > x0) ? x1 - x0 : x0 - x1;
|
|
int dy = (y1 > y0) ? y1 - y0 : y0 - y1;
|
|
if (dx >= dy) {
|
|
for (int i = 0; i < w; i++) {
|
|
int off = i - w / 2;
|
|
tft.drawLine(x0, y0 + off, x1, y1 + off, c);
|
|
}
|
|
} else {
|
|
for (int i = 0; i < w; i++) {
|
|
int off = i - w / 2;
|
|
tft.drawLine(x0 + off, y0, x1 + off, y1, c);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Deterministic bomb position along its flight path:
|
|
// pos(d) = start + dir*d (+ perp * A*sin(freq*d + phase) for smart bombs)
|
|
// Because the wiggle is a pure function of the distance travelled, the whole
|
|
// path can be replayed at any time; painting and erasing therefore cover
|
|
// exactly the same pixels.
|
|
static void bombPos(const Bomb &b, float d, float &px, float &py)
|
|
{
|
|
px = b.sx + b.dirx * d;
|
|
py = b.sy + b.diry * d;
|
|
if (!b.smart) return;
|
|
float p = WIGGLE_AMP * sinf(WIGGLE_FREQ * d + b.wob);
|
|
px += -b.diry * p;
|
|
py += b.dirx * p;
|
|
}
|
|
|
|
#define TRAIL_W 3 // trail band when painting (joint dots r=1)
|
|
#define TRAIL_ERASE 7 // erase band: symmetric ±3, strictly wider than paint.
|
|
// Why 7 and not 6: an even width (6) covers -3..+2, and
|
|
// the erase line's integer endpoints differ slightly
|
|
// from the paint line's (erase runs to a later d), so
|
|
// the Bresenham slope can shift the band by ±1px
|
|
// mid-line. The asymmetric +2 side then misses paint
|
|
// ink at +3. Odd width = symmetric, always covers.
|
|
|
|
// Blink pattern shared by all trails (the 2600 streaks shimmer in sync with
|
|
// the playfield clock): 6-frame cycle, trail dark on the last 2 frames.
|
|
#define BLINK_CYCLE 6
|
|
#define BLINK_OFF 4 // first "dark" frame of the cycle
|
|
|
|
// Paint (or erase) a bomb's whole trail by replaying its flight path.
|
|
// Normal bombs are straight single segments; smart bombs are walked in
|
|
// chords (the curve is gentle, so joint dots fill the chord gaps).
|
|
static void trailWalk(const Bomb &b, float dEnd, int w, uint16_t c)
|
|
{
|
|
int br = (c == TFT_BLACK) ? 3 : 1; // erase dots overshoot the paint dots
|
|
float px, py, qx, qy;
|
|
bombPos(b, 0, px, py);
|
|
// dot the path start too: the bright head dot paints one row/col beyond
|
|
// the first centerline pixel, and a near-vertical erase band (offsets
|
|
// perpendicular to a steep path) would miss it otherwise
|
|
tft.fillCircle((int)px, (int)py, br, c);
|
|
if (!b.smart) {
|
|
bombPos(b, dEnd, qx, qy);
|
|
drawThickLine((int)px, (int)py, (int)qx, (int)qy, w, c);
|
|
tft.fillCircle((int)qx, (int)qy, br, c);
|
|
return;
|
|
}
|
|
float step = (c == TFT_BLACK) ? 15.0f : 10.0f;
|
|
for (float d = step; ; d += step) {
|
|
if (d > dEnd) d = dEnd;
|
|
bombPos(b, d, qx, qy);
|
|
drawThickLine((int)px, (int)py, (int)qx, (int)qy, w, c);
|
|
tft.fillCircle((int)qx, (int)qy, br, c);
|
|
px = qx;
|
|
py = qy;
|
|
if (d >= dEnd) break;
|
|
}
|
|
}
|
|
|
|
// Does the segment (x0,y0)-(x1,y1) pass within `rad` of (px,py)?
|
|
static bool linePassesNear(int x0, int y0, int x1, int y1, int px, int py, int rad)
|
|
{
|
|
long dx = x1 - x0, dy = y1 - y0;
|
|
long len2 = dx * dx + dy * dy;
|
|
if (len2 == 0) {
|
|
long ddx = px - x0, ddy = py - y0;
|
|
return ddx * ddx + ddy * ddy <= (long)rad * rad;
|
|
}
|
|
long t = (long)(px - x0) * dx + (long)(py - y0) * dy;
|
|
if (t < 0) t = 0;
|
|
if (t > len2) t = len2;
|
|
int cx = x0 + (int)((long)t * dx / len2);
|
|
int cy = y0 + (int)((long)t * dy / len2);
|
|
long ddx = px - cx, ddy = py - cy;
|
|
return ddx * ddx + ddy * ddy <= (long)rad * rad;
|
|
}
|
|
|
|
// after an erase pass: repair everything the erase band may have swept over
|
|
static void trailRepair(const Bomb &b, float dEnd)
|
|
{
|
|
if (cross.drawn) {
|
|
float px, py;
|
|
bombPos(b, 0, px, py);
|
|
for (float d = 6.0f; d <= dEnd; d += 6.0f) {
|
|
float qx, qy;
|
|
bombPos(b, d, qx, qy);
|
|
if (linePassesNear((int)px, (int)py, (int)qx, (int)qy,
|
|
cross.dx, cross.dy, 8)) {
|
|
drawCrossAt(cross.dx, cross.dy, TFT_BLACK);
|
|
cross.drawn = false; // redrawn next frame
|
|
break;
|
|
}
|
|
px = qx;
|
|
py = qy;
|
|
}
|
|
}
|
|
if (dEnd >= b.len - 14) { // trail reached into the terrain strip
|
|
redrawGroundArea(b.tx, (float)groundY, 14.0f);
|
|
}
|
|
}
|
|
|
|
// Enemy trails persist while the bomb falls (classic look) but vanish the
|
|
// moment the bomb is destroyed or reaches the ground, like the Atari 2600.
|
|
static void eraseBombTrail(const Bomb &b)
|
|
{
|
|
trailWalk(b, b.d, TRAIL_ERASE, TFT_BLACK);
|
|
trailRepair(b, b.d);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Bomber planes & satellites
|
|
// ---------------------------------------------------------------------------
|
|
static void drawCraftAt(const Craft &cr, uint16_t c)
|
|
{
|
|
if (cr.sat) {
|
|
tft.fillRect(cr.x - 5, cr.y - 1, 3, 3, c); // solar panels
|
|
tft.fillRect(cr.x + 3, cr.y - 1, 3, 3, c);
|
|
tft.drawFastHLine(cr.x - 2, cr.y, 5, c);
|
|
tft.fillCircle(cr.x, cr.y, 1, c); // body
|
|
} else {
|
|
tft.fillRect(cr.x - 5, cr.y - 1, 10, 2, c); // fuselage
|
|
tft.fillRect(cr.x - 4, cr.y - 3, 2, 5, c); // tail fin
|
|
tft.fillRect(cr.x, cr.y - 3, 3, 6, c); // wing
|
|
}
|
|
}
|
|
|
|
static void spawnCraft(bool sat)
|
|
{
|
|
for (int i = 0; i < MAX_CRAFTS; i++) {
|
|
Craft &cr = crafts[i];
|
|
if (cr.alive) continue;
|
|
cr.alive = true;
|
|
cr.sat = sat;
|
|
cr.dir = random(0, 2) ? 1 : -1;
|
|
cr.x = cr.dir > 0 ? -8 : scrW + 8;
|
|
cr.y = sat ? 26 + random(0, 10) : 44 + random(0, 18);
|
|
cr.lastDrop = millis() + 600;
|
|
if (sat) sfxSweep(900, 500, 350, 7000);
|
|
else sfxSweep(480, 290, 420, 7000);
|
|
return;
|
|
}
|
|
}
|
|
|
|
static void updateCrafts()
|
|
{
|
|
for (int k = 0; k < MAX_CRAFTS; k++) {
|
|
Craft &cr = crafts[k];
|
|
if (!cr.alive) continue;
|
|
|
|
// erase previous sprite, cross the screen, redraw
|
|
drawCraftAt(cr, TFT_BLACK);
|
|
// if the erase cut the crosshair, have it redrawn
|
|
if (cross.drawn &&
|
|
cross.dx > cr.x - 8 && cross.dx < cr.x + 8 &&
|
|
cross.dy > cr.y - 5 && cross.dy < cr.y + 5) {
|
|
drawCrossAt(cross.dx, cross.dy, TFT_BLACK);
|
|
cross.drawn = false;
|
|
}
|
|
cr.x += cr.dir * (cr.sat ? 1 : 2);
|
|
if (cr.x < -14 || cr.x > scrW + 14) {
|
|
cr.alive = false;
|
|
continue;
|
|
}
|
|
// satellites blink on and off as they move
|
|
if (cr.sat && (frameCount & 1)) continue;
|
|
drawCraftAt(cr, cr.sat ? TFT_ORANGE : TFT_WHITE);
|
|
|
|
// drop bombs on the defenses below
|
|
uint32_t now = millis();
|
|
uint32_t every = cr.sat ? 2200 : 1400;
|
|
if (now - cr.lastDrop >= every) {
|
|
cr.lastDrop = now;
|
|
spawnBombAt((float)cr.x, (float)cr.y + 6, false, true);
|
|
sfxTone(650, 45, 6000);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void shootCraft(int k)
|
|
{
|
|
Craft &cr = crafts[k];
|
|
if (!cr.alive) return;
|
|
float cx = cr.x, cy = cr.y;
|
|
bool sat = cr.sat;
|
|
cr.alive = false;
|
|
drawCraftAt(cr, TFT_BLACK);
|
|
addScore((sat ? 250 : 100) * scoreMult());
|
|
spawnExpl(cx, cy, 16.0f, 1.5f);
|
|
sfxKill();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Updates
|
|
// ---------------------------------------------------------------------------
|
|
static void updateRockets()
|
|
{
|
|
for (int i = 0; i < MAX_ROCKETS; i++) {
|
|
Rocket &r = rockets[i];
|
|
if (!r.alive) continue;
|
|
|
|
// AA rockets have no trail (like the 2600): just a moving dot.
|
|
// Erase the previous dot, then draw the new position.
|
|
tft.fillCircle((int)r.x, (int)r.y, 2, TFT_BLACK);
|
|
|
|
float dx = r.tx - r.x;
|
|
float dy = r.ty - r.y;
|
|
float d = sqrtf(dx * dx + dy * dy);
|
|
if (d <= r.speed) {
|
|
r.alive = false;
|
|
spawnExpl(r.tx, r.ty, ROCKET_RADIUS, 1.6f);
|
|
sfxBoom();
|
|
} else {
|
|
r.x += r.dirx * r.speed;
|
|
r.y += r.diry * r.speed;
|
|
tft.fillCircle((int)r.x, (int)r.y, 2, TFT_CYAN);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void killCity(int i)
|
|
{
|
|
// classic rule: enemy weapons are only able to destroy three cities
|
|
// during one wave
|
|
if (!cityAlive[i] || citiesLostWave >= 3) return;
|
|
citiesLostWave++;
|
|
cityAlive[i] = false;
|
|
drawCity(i);
|
|
sfxCityBoom();
|
|
}
|
|
|
|
static void killBattery(int i)
|
|
{
|
|
batAlive[i] = false;
|
|
batAmmo[i] = 0;
|
|
drawBattery(i);
|
|
}
|
|
|
|
static void updateBombs()
|
|
{
|
|
int phase = frameCount % BLINK_CYCLE;
|
|
bool dark = (phase >= BLINK_OFF); // trails are erased right now
|
|
bool cameOn = (phase == 0); // trails were just repainted
|
|
|
|
for (int i = 0; i < MAX_BOMBS; i++) {
|
|
Bomb &b = bombs[i];
|
|
if (!b.alive) continue;
|
|
|
|
uint16_t col = b.smart ? TFT_MAGENTA : TFT_RED;
|
|
|
|
// advance along the analytic path: position is exact for any d,
|
|
// independent of the blink phase (no history, no drift)
|
|
float dOld = b.d;
|
|
float dNew = dOld + b.speed;
|
|
|
|
if (cameOn) {
|
|
// repaint the whole streak from the start (covers the head dot
|
|
// last drawn before the dark frames)
|
|
trailWalk(b, dNew, TRAIL_W, col);
|
|
} else if (!dark) {
|
|
// steady-on frame: clean the last bright head dot by
|
|
// overpainting it with trail color, then extend the streak
|
|
tft.fillCircle((int)b.hx, (int)b.hy, 1, col);
|
|
float px, py, qx, qy;
|
|
bombPos(b, dOld, px, py);
|
|
bombPos(b, dNew, qx, qy);
|
|
drawThickLine((int)px, (int)py, (int)qx, (int)qy, TRAIL_W, col);
|
|
} else if (phase == BLINK_OFF) {
|
|
// streak just went dark: erase it along its exact path
|
|
trailWalk(b, dNew, TRAIL_ERASE, TFT_BLACK);
|
|
trailRepair(b, dNew);
|
|
}
|
|
|
|
b.d = dNew;
|
|
if (b.d > b.len) b.d = b.len;
|
|
bombPos(b, b.d, b.x, b.y);
|
|
|
|
// the bright missile dot itself: steady while the trail flashes
|
|
if (!dark && b.d < b.len) {
|
|
tft.fillCircle((int)b.x, (int)b.y, 1, TFT_WHITE);
|
|
b.hx = b.x;
|
|
b.hy = b.y;
|
|
}
|
|
|
|
// caught by an explosion?
|
|
for (int e = 0; e < MAX_EXPL; e++) {
|
|
Explosion &ex = expls[e];
|
|
if (!ex.alive || ex.r < 2) continue;
|
|
float ddx = b.x - ex.x;
|
|
float ddy = b.y - ex.y;
|
|
if (ddx * ddx + ddy * ddy < ex.r * ex.r) {
|
|
b.alive = false;
|
|
waveKills++;
|
|
addScore(25 * scoreMult());
|
|
eraseBombTrail(b); // also refreshes the HUD with the new score
|
|
spawnExpl(b.x, b.y, 14.0f, 1.4f);
|
|
sfxKill();
|
|
break;
|
|
}
|
|
}
|
|
if (!b.alive) continue;
|
|
|
|
// reached the target?
|
|
if (b.d >= b.len) {
|
|
b.alive = false;
|
|
eraseBombTrail(b);
|
|
spawnExpl(b.x, groundY - 4, 11.0f, 1.3f);
|
|
sfxBoom();
|
|
}
|
|
}
|
|
}
|
|
|
|
static void updateExpls()
|
|
{
|
|
for (int i = 0; i < MAX_EXPL; i++) {
|
|
Explosion &e = expls[i];
|
|
if (!e.alive) continue;
|
|
|
|
float oldR = e.r;
|
|
if (e.hold > 0) {
|
|
e.hold--;
|
|
} else {
|
|
e.r += e.vel;
|
|
if (e.r >= e.maxR) {
|
|
e.r = e.maxR;
|
|
e.hold = 5;
|
|
e.vel = -1.6f;
|
|
} else if (e.r <= 0.5f && e.vel < 0) {
|
|
e.r = 0;
|
|
e.alive = false;
|
|
}
|
|
}
|
|
|
|
// erase old circle and repair the terrain it covered
|
|
if (oldR > 0.5f) {
|
|
tft.fillCircle((int)e.x, (int)e.y, (int)oldR, TFT_BLACK);
|
|
redrawGroundArea(e.x, e.y, oldR);
|
|
// if the crosshair was inside the erased circle, remove the
|
|
// remaining arms and redraw it next frame
|
|
float cdx = cross.dx - e.x;
|
|
float cdy = cross.dy - e.y;
|
|
if (cross.drawn && cdx * cdx + cdy * cdy < (oldR + 6) * (oldR + 6)) {
|
|
drawCrossAt(cross.dx, cross.dy, TFT_BLACK);
|
|
cross.drawn = false;
|
|
}
|
|
}
|
|
|
|
if (e.alive && e.r > 0.5f) {
|
|
// flickering fireball
|
|
tft.fillCircle((int)e.x, (int)e.y, (int)e.r, EXPL_COLORS[frameCount % 3]);
|
|
|
|
// burn cities and batteries caught inside
|
|
for (int c = 0; c < CITY_COUNT; c++) {
|
|
if (!cityAlive[c]) continue;
|
|
float dx = cityX[c] - e.x;
|
|
float dy = (groundY - 6) - e.y;
|
|
if (dx * dx + dy * dy < e.r * e.r) killCity(c);
|
|
}
|
|
for (int b = 0; b < 3; b++) {
|
|
if (!batAlive[b]) continue;
|
|
float dx = BATX[b] - e.x;
|
|
float dy = (groundY - 4) - e.y;
|
|
if (dx * dx + dy * dy < e.r * e.r) killBattery(b);
|
|
}
|
|
|
|
// bombers / satellites caught in the fireball pay a bonus
|
|
for (int k = 0; k < MAX_CRAFTS; k++) {
|
|
Craft &cr = crafts[k];
|
|
if (!cr.alive) continue;
|
|
float dx = cr.x - e.x;
|
|
float dy = cr.y - e.y;
|
|
if (dx * dx + dy * dy < e.r * e.r) shootCraft(k);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Waves / game flow
|
|
// ---------------------------------------------------------------------------
|
|
// Host hook: the desktop emulator can request skipping straight to a wave
|
|
// (--wave N). Weak definition so the device build simply sees 0.
|
|
__attribute__((weak)) int emuStartWaveRequest = 0;
|
|
|
|
static void beginGame()
|
|
{
|
|
resetGame();
|
|
startWave(emuStartWaveRequest > 0 ? emuStartWaveRequest : 1);
|
|
}
|
|
|
|
static void resetGame()
|
|
{
|
|
for (int i = 0; i < CITY_COUNT; i++) cityAlive[i] = true;
|
|
for (int i = 0; i < 3; i++) {
|
|
batAlive[i] = true;
|
|
batAmmo[i] = AMMO_MAX;
|
|
}
|
|
for (int i = 0; i < MAX_BOMBS; i++) bombs[i].alive = false;
|
|
for (int i = 0; i < MAX_ROCKETS; i++) rockets[i].alive = false;
|
|
for (int i = 0; i < MAX_EXPL; i++) expls[i].alive = false;
|
|
for (int i = 0; i < MAX_CRAFTS; i++) crafts[i].alive = false;
|
|
score = 0;
|
|
wave = 0;
|
|
citiesLostWave = 0;
|
|
reserveCities = 0;
|
|
nextCityAt = 10000;
|
|
cityOSDUntil = 0;
|
|
cross.x = cross.dx = scrW / 2;
|
|
cross.y = cross.dy = scrH / 2;
|
|
}
|
|
|
|
static void startWave(int n)
|
|
{
|
|
wave = n;
|
|
// arcade rule: between levels missile batteries are rebuilt and
|
|
// replenished; only destroyed cities stay destroyed until a bonus
|
|
// city is deployed
|
|
for (int i = 0; i < 3; i++) {
|
|
batAlive[i] = true;
|
|
batAmmo[i] = AMMO_MAX;
|
|
}
|
|
// every third wave one destroyed city is rebuilt
|
|
if (n > 1 && (n - 1) % 3 == 0) {
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
if (!cityAlive[i]) {
|
|
cityAlive[i] = true;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
waveQuota = 8 + 2 * n;
|
|
if (waveQuota > 24) waveQuota = 24;
|
|
bombSpeed = 0.5f + 0.12f * (n - 1);
|
|
if (bombSpeed > 2.4f) bombSpeed = 2.4f;
|
|
spawnIntervalMs = 1400 - 70 * n;
|
|
if (spawnIntervalMs < 500) spawnIntervalMs = 500;
|
|
bombsSpawned = 0;
|
|
waveKills = 0;
|
|
citiesLostWave = 0; // fresh city-kill budget each wave
|
|
spawningStopped = false;
|
|
lastSpawnMs = millis();
|
|
|
|
drawWorld();
|
|
|
|
// bombers (and later satellites) cross the sky, launching bombs
|
|
for (int i = 0; i < MAX_CRAFTS; i++) crafts[i].alive = false;
|
|
if (n >= 2) spawnCraft(false);
|
|
if (n >= 5 && random(100) < 45) spawnCraft(true);
|
|
|
|
tft.setFreeFont(&FreeSansBold18pt7b);
|
|
tft.setTextColor(TFT_YELLOW, TFT_BLACK);
|
|
tft.setTextDatum(MC_DATUM);
|
|
tft.drawString("WAVE " + String(n), scrW / 2, 70);
|
|
tft.setTextFont(2);
|
|
|
|
cross.drawn = false;
|
|
gameState = ST_BANNER;
|
|
stateT0 = millis();
|
|
|
|
// Attack alarm: four falling tones as a wave-start intro, like the
|
|
// original. By the time it ends, the banner clears and gameplay begins.
|
|
sfxSirenIntro();
|
|
}
|
|
|
|
static void eraseBanner()
|
|
{
|
|
tft.fillRect(0, 50, scrW, 40, TFT_BLACK);
|
|
stars(12);
|
|
cross.drawn = false;
|
|
}
|
|
|
|
static void enterBonus()
|
|
{
|
|
sfxWaveClear();
|
|
|
|
// deploy reserve cities to rebuild destroyed ones (arcade rule)
|
|
int deployed = 0;
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
if (!cityAlive[i] && reserveCities > 0) {
|
|
reserveCities--;
|
|
cityAlive[i] = true;
|
|
deployed++;
|
|
}
|
|
}
|
|
|
|
int aliveCities = 0;
|
|
for (int i = 0; i < CITY_COUNT; i++) if (cityAlive[i]) aliveCities++;
|
|
|
|
int ammoLeft = 0;
|
|
for (int i = 0; i < 3; i++) ammoLeft += batAmmo[i];
|
|
|
|
int mult = scoreMult();
|
|
int cityPts = aliveCities * 100 * mult;
|
|
int ammoPts = ammoLeft * 5 * mult;
|
|
addScore(cityPts + ammoPts);
|
|
|
|
int px = 60, pw = scrW - 120, py = 64, ph = 108;
|
|
tft.fillRect(px, py, pw, ph, TFT_BLACK);
|
|
tft.drawRect(px, py, pw, ph, TFT_WHITE);
|
|
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(TFT_YELLOW, TFT_BLACK);
|
|
tft.setTextDatum(MC_DATUM);
|
|
tft.drawString("WAVE " + String(wave) + " CLEARED", scrW / 2, py + 12);
|
|
tft.setTextColor(TFT_WHITE, TFT_BLACK);
|
|
tft.drawString("MISSILES " + String(waveKills) + " x " + String(25 * mult), scrW / 2, py + 30);
|
|
tft.drawString("CITIES " + String(aliveCities) + " x " + String(100 * mult), scrW / 2, py + 46);
|
|
tft.drawString("AMMO " + String(ammoLeft) + " x " + String(5 * mult), scrW / 2, py + 62);
|
|
if (deployed > 0) {
|
|
tft.setTextColor(TFT_CYAN, TFT_BLACK);
|
|
tft.drawString("REBUILT " + String(deployed) + " (BONUS CITY)", scrW / 2, py + 78);
|
|
} else if (reserveCities > 0) {
|
|
tft.setTextColor(TFT_GOLD, TFT_BLACK);
|
|
tft.drawString("RESERVE CITIES " + String(reserveCities), scrW / 2, py + 78);
|
|
}
|
|
tft.setTextColor(TFT_GOLD, TFT_BLACK);
|
|
tft.drawString("SCORE " + String(score), scrW / 2, py + 94);
|
|
|
|
gameState = ST_BONUS;
|
|
stateT0 = millis();
|
|
}
|
|
|
|
static void enterGameOver()
|
|
{
|
|
sfxGameOver();
|
|
if (score > highScore) highScore = score;
|
|
savePrefs(); // the run is final: commit high score (+ current volume)
|
|
|
|
tft.fillScreen(TFT_BLACK);
|
|
stars(40);
|
|
tft.setFreeFont(&FreeSansBold24pt7b);
|
|
tft.setTextColor(TFT_RED, TFT_BLACK);
|
|
tft.setTextDatum(MC_DATUM);
|
|
tft.drawString("THE END", scrW / 2, 80);
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(TFT_WHITE, TFT_BLACK);
|
|
tft.drawString("FINAL SCORE " + String(score), scrW / 2, 130);
|
|
tft.setTextColor(TFT_GOLD, TFT_BLACK);
|
|
tft.drawString("HIGH SCORE " + String(highScore), scrW / 2, 152);
|
|
tft.setTextColor(TFT_DARKGREY, TFT_BLACK);
|
|
tft.drawString("press to continue", scrW / 2, 186);
|
|
|
|
gameState = ST_GAMEOVER;
|
|
stateT0 = millis();
|
|
}
|
|
|
|
static void drawTitle()
|
|
{
|
|
tft.fillScreen(TFT_BLACK);
|
|
stars(70);
|
|
drawGround();
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
cityAlive[i] = true;
|
|
drawCity(i);
|
|
}
|
|
for (int i = 0; i < 3; i++) {
|
|
batAlive[i] = true;
|
|
batAmmo[i] = AMMO_MAX;
|
|
drawBattery(i);
|
|
}
|
|
|
|
tft.setTextDatum(MC_DATUM);
|
|
tft.setFreeFont(&FreeSansBold24pt7b);
|
|
tft.setTextColor(TFT_RED, TFT_BLACK);
|
|
tft.drawString("MISSILE", scrW / 2, 55);
|
|
tft.setTextColor(TFT_CYAN, TFT_BLACK);
|
|
tft.drawString("COMMAND", scrW / 2, 95);
|
|
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(TFT_WHITE, TFT_BLACK);
|
|
tft.drawString("Trackball: aim press / tap: fire", scrW / 2, 136);
|
|
tft.drawString("A / S / D: battery U / V / M: volume", scrW / 2, 154);
|
|
tft.setTextColor(TFT_GOLD, TFT_BLACK);
|
|
if (highScore > 0) tft.drawString("HIGH " + String(highScore), scrW / 2, 178);
|
|
|
|
gameState = ST_TITLE;
|
|
stateT0 = millis();
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Input
|
|
// ---------------------------------------------------------------------------
|
|
// Trackball step accumulators: filled by pollTrackball() (called every loop
|
|
// iteration) and consumed by applyTrackball() once per game frame.
|
|
static int tbSteps[4];
|
|
|
|
// The ball emits pulse trains on the direction pins while rolling; every
|
|
// edge is one ball step. This runs in the loop() hot path (~1 ms apart) —
|
|
// at the old once-per-frame (33 ms) rate a fast roll completed whole pulse
|
|
// cycles between two reads, so most edges were dropped and the cross
|
|
// crawled across the screen one segment per tick.
|
|
static void pollTrackball()
|
|
{
|
|
// Quadrant pins + center click, per UnitTest's mouse mapping:
|
|
// G02 -> right, G01 -> up, G04 -> left, G03 -> down, BOOT -> click
|
|
static const uint8_t tbPins[5] = {
|
|
BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03, BOARD_BOOT_PIN
|
|
};
|
|
static bool last[5];
|
|
bool cur[5];
|
|
for (int i = 0; i < 5; i++) {
|
|
cur[i] = digitalRead(tbPins[i]);
|
|
}
|
|
|
|
static bool primed = false;
|
|
if (!primed) { // don't count the power-up pin levels as edges
|
|
primed = true;
|
|
for (int i = 0; i < 5; i++) last[i] = cur[i];
|
|
return;
|
|
}
|
|
|
|
if (gameState == ST_PLAYING || gameState == ST_BANNER) {
|
|
for (int i = 0; i < 4; i++) {
|
|
if (cur[i] != last[i]) tbSteps[i]++; // count every edge
|
|
}
|
|
}
|
|
|
|
bool pressed = (!cur[4] && last[4]); // falling edge = click
|
|
for (int i = 0; i < 5; i++) last[i] = cur[i];
|
|
|
|
if (!pressed) return;
|
|
|
|
switch (gameState) {
|
|
case ST_TITLE:
|
|
beginGame();
|
|
break;
|
|
case ST_BONUS:
|
|
startWave(wave + 1);
|
|
break;
|
|
case ST_GAMEOVER:
|
|
drawTitle();
|
|
break;
|
|
case ST_PLAYING:
|
|
fireAuto();
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Consume the pulses accumulated since the last frame: a slow roll moves
|
|
// the cross in fine steps, a fast roll accelerates it (capped per frame,
|
|
// like the arcade trackball where a hard flick sends the cursor flying).
|
|
static void applyTrackball()
|
|
{
|
|
for (int i = 0; i < 4; i++) {
|
|
int n = tbSteps[i];
|
|
if (!n) continue;
|
|
tbSteps[i] = 0;
|
|
int px = n * CROSS_STEP;
|
|
if (px > CROSS_MAX_STEP) px = CROSS_MAX_STEP;
|
|
switch (i) {
|
|
case 0: nudgeCross(+px, 0); break; // right
|
|
case 1: nudgeCross(0, -px); break; // up
|
|
case 2: nudgeCross(-px, 0); break; // left
|
|
case 3: nudgeCross(0, +px); break; // down
|
|
}
|
|
}
|
|
}
|
|
|
|
static void pollTouch()
|
|
{
|
|
if (!touchAvail) return;
|
|
static bool wasDown = false;
|
|
bool down = touch.isPressed();
|
|
if (!down) {
|
|
wasDown = false;
|
|
return;
|
|
}
|
|
if (wasDown) return; // only act on new taps
|
|
int16_t x[1], y[1];
|
|
if (touch.getPoint(x, y, 1) > 0) {
|
|
wasDown = true;
|
|
switch (gameState) {
|
|
case ST_TITLE:
|
|
beginGame();
|
|
break;
|
|
case ST_BONUS:
|
|
startWave(wave + 1);
|
|
break;
|
|
case ST_GAMEOVER:
|
|
drawTitle();
|
|
break;
|
|
case ST_PLAYING:
|
|
case ST_BANNER:
|
|
setCross(x[0], y[0]);
|
|
fireAuto();
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
static void pollKeyboard()
|
|
{
|
|
static char lastKey = 0;
|
|
Wire.requestFrom((uint8_t)0x55, (uint8_t)1);
|
|
if (Wire.available() == 0) {
|
|
lastKey = 0; // idle: arm the next press (same key can repeat)
|
|
return;
|
|
}
|
|
char k = (char)Wire.read();
|
|
if (k == 0) {
|
|
lastKey = 0;
|
|
return;
|
|
}
|
|
if (k == lastKey) return;
|
|
lastKey = k;
|
|
kbAvail = true;
|
|
|
|
char c = tolower(k);
|
|
|
|
// volume keys work in every state (and persist immediately)
|
|
if (c == 'u') {
|
|
sound.volumeUp();
|
|
volOSDUntil = millis() + 1200;
|
|
savePrefs();
|
|
return;
|
|
}
|
|
if (c == 'v') {
|
|
sound.volumeDown();
|
|
volOSDUntil = millis() + 1200;
|
|
savePrefs();
|
|
return;
|
|
}
|
|
if (c == 'm') {
|
|
sound.toggleMute();
|
|
volOSDUntil = millis() + 1200;
|
|
savePrefs();
|
|
return;
|
|
}
|
|
|
|
switch (gameState) {
|
|
case ST_TITLE:
|
|
beginGame();
|
|
break;
|
|
case ST_BONUS:
|
|
startWave(wave + 1);
|
|
break;
|
|
case ST_GAMEOVER:
|
|
drawTitle();
|
|
break;
|
|
case ST_PLAYING:
|
|
if (c == 'a') launch(0, cross.x, cross.y);
|
|
else if (c == 's') launch(1, cross.x, cross.y);
|
|
else if (c == 'd') launch(2, cross.x, cross.y);
|
|
else if (c == ' ') fireAuto();
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Per-state loop handlers
|
|
// ---------------------------------------------------------------------------
|
|
static void loopPlaying()
|
|
{
|
|
uint32_t now = millis();
|
|
|
|
if (spawningStopped) {
|
|
// no cities left: let the screen settle, then game over
|
|
if (!anyBombAlive() && !anyRocketAlive() && !anyExplAlive()) {
|
|
enterGameOver();
|
|
return;
|
|
}
|
|
} else {
|
|
if (bombsSpawned < waveQuota && now - lastSpawnMs >= spawnIntervalMs) {
|
|
lastSpawnMs = now;
|
|
int burst = 1 + random(0, 1 + wave / 4);
|
|
while (burst-- > 0 && bombsSpawned < waveQuota) spawnBomb();
|
|
}
|
|
}
|
|
|
|
updateRockets();
|
|
updateBombs();
|
|
updateCrafts();
|
|
updateExpls();
|
|
renderCross();
|
|
|
|
if (!spawningStopped) {
|
|
bool citiesLeft = false;
|
|
for (int i = 0; i < CITY_COUNT; i++) {
|
|
if (cityAlive[i]) citiesLeft = true;
|
|
}
|
|
if (!citiesLeft) spawningStopped = true;
|
|
}
|
|
|
|
if (waveDone()) enterBonus();
|
|
}
|
|
|
|
static void loopTitle()
|
|
{
|
|
// blinking start prompt
|
|
static bool shown = true;
|
|
static uint32_t lastBlink = 0;
|
|
uint32_t now = millis();
|
|
if (now - lastBlink >= 700) {
|
|
lastBlink = now;
|
|
shown = !shown;
|
|
tft.setTextFont(2);
|
|
tft.setTextColor(shown ? TFT_WHITE : TFT_BLACK, TFT_BLACK);
|
|
tft.setTextDatum(MC_DATUM);
|
|
tft.drawString("TAP OR PRESS TO START", scrW / 2, 200);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Init
|
|
// ---------------------------------------------------------------------------
|
|
// LilyGo T-Deck backlight has 16 levels (0..16)
|
|
static void setBrightness(uint8_t value)
|
|
{
|
|
static uint8_t level = 0;
|
|
static uint8_t steps = 16;
|
|
if (value == 0) {
|
|
digitalWrite(BOARD_BL_PIN, 0);
|
|
delay(3);
|
|
level = 0;
|
|
return;
|
|
}
|
|
if (level == 0) {
|
|
digitalWrite(BOARD_BL_PIN, 1);
|
|
level = steps;
|
|
delayMicroseconds(30);
|
|
}
|
|
int from = steps - level;
|
|
int to = steps - value;
|
|
int num = (steps + to - from) % steps;
|
|
for (int i = 0; i < num; i++) {
|
|
digitalWrite(BOARD_BL_PIN, 0);
|
|
digitalWrite(BOARD_BL_PIN, 1);
|
|
}
|
|
level = value;
|
|
}
|
|
|
|
static void hardwareInit()
|
|
{
|
|
Serial.begin(115200);
|
|
Serial.println("T-Deck Missile Command");
|
|
|
|
pinMode(BOARD_POWERON, OUTPUT);
|
|
digitalWrite(BOARD_POWERON, HIGH);
|
|
|
|
// CS lines high during init
|
|
pinMode(BOARD_SDCARD_CS, OUTPUT);
|
|
pinMode(RADIO_CS_PIN, OUTPUT);
|
|
pinMode(BOARD_TFT_CS, OUTPUT);
|
|
digitalWrite(BOARD_SDCARD_CS, HIGH);
|
|
digitalWrite(RADIO_CS_PIN, HIGH);
|
|
digitalWrite(BOARD_TFT_CS, HIGH);
|
|
|
|
pinMode(BOARD_SPI_MISO, INPUT_PULLUP);
|
|
SPI.begin(BOARD_SPI_SCK, BOARD_SPI_MISO, BOARD_SPI_MOSI);
|
|
|
|
tft.begin();
|
|
tft.setRotation(1);
|
|
tft.fillScreen(TFT_BLACK);
|
|
|
|
pinMode(BOARD_BL_PIN, OUTPUT);
|
|
for (int i = 0; i <= 16; ++i) {
|
|
setBrightness(i);
|
|
delay(20);
|
|
}
|
|
|
|
// I2C: touch + keyboard share the bus
|
|
Wire.begin(BOARD_I2C_SDA, BOARD_I2C_SCL);
|
|
|
|
touch.setPins(-1, BOARD_TOUCH_INT);
|
|
touchAvail = touch.begin(Wire);
|
|
if (touchAvail) {
|
|
touch.setMaxCoordinates(scrW, scrH);
|
|
touch.setSwapXY(true);
|
|
touch.setMirrorXY(false, true);
|
|
Serial.println("GT911 touch ready");
|
|
} else {
|
|
Serial.println("No GT911 touch found");
|
|
}
|
|
|
|
// Trackball pins (quadrants + center click)
|
|
const uint8_t tbPins[5] = {
|
|
BOARD_TBOX_G02, BOARD_TBOX_G01, BOARD_TBOX_G04, BOARD_TBOX_G03, BOARD_BOOT_PIN
|
|
};
|
|
for (int i = 0; i < 5; i++) {
|
|
pinMode(tbPins[i], INPUT_PULLUP);
|
|
}
|
|
|
|
randomSeed(esp_random());
|
|
}
|
|
|
|
void setup()
|
|
{
|
|
hardwareInit();
|
|
|
|
scrW = tft.width();
|
|
scrH = tft.height();
|
|
groundY = scrH - 12;
|
|
layout();
|
|
|
|
if (!sound.begin()) {
|
|
Serial.println("Sound engine init failed (no I2S?)");
|
|
}
|
|
|
|
Serial.printf("Screen %dx%d, ground at %d\n", scrW, scrH, groundY);
|
|
|
|
// restore persisted high score and volume
|
|
prefs.begin("mc", false);
|
|
highScore = (int)prefs.getUInt("hi", 0);
|
|
sound.setVolume((uint8_t)prefs.getUInt("vol", 5));
|
|
|
|
drawTitle();
|
|
}
|
|
|
|
void loop()
|
|
{
|
|
// swallow all input right after power-up/reset: the keyboard controller
|
|
// may still emit stale bytes and pins may float, which used to start
|
|
// a game immediately after a restart
|
|
uint32_t now = millis();
|
|
if (now < INPUT_GRACE_MS) {
|
|
delay(1);
|
|
return;
|
|
}
|
|
|
|
pollTrackball(); // hot path: sample the ball every iteration (~1 ms)
|
|
|
|
static uint32_t nextFrame = 0;
|
|
if ((int32_t)(now - nextFrame) < 0) {
|
|
delay(1);
|
|
return;
|
|
}
|
|
nextFrame = now + FRAME_MS;
|
|
frameCount++;
|
|
|
|
applyTrackball();
|
|
pollTouch();
|
|
pollKeyboard();
|
|
|
|
switch (gameState) {
|
|
case ST_TITLE:
|
|
loopTitle();
|
|
break;
|
|
case ST_BANNER:
|
|
if (now - stateT0 > BANNER_MS) {
|
|
eraseBanner();
|
|
gameState = ST_PLAYING;
|
|
}
|
|
break;
|
|
case ST_PLAYING:
|
|
loopPlaying();
|
|
break;
|
|
case ST_BONUS:
|
|
if (now - stateT0 > BONUS_MS) {
|
|
startWave(wave + 1);
|
|
}
|
|
break;
|
|
case ST_GAMEOVER:
|
|
default:
|
|
break;
|
|
}
|
|
|
|
drawVolumeOSD();
|
|
drawBonusCityOSD();
|
|
}
|