/** * @file MiataDrive.ino * @brief MiataDrive - Lotus Turbo Challenge style pseudo-3D racer for LilyGo T-Deck. * * Classic segment-based pseudo-3D road: track = list of (curve, hill) * segments projected with perspective. Road is drawn near->far with rumble * strips, lane markers and alternating shades that scroll with distance. * Roadside scenery and traffic are depth-scaled sprites drawn far->near, * clipped behind hill crests. Centrifugal force pulls you wide in curves. * * Controls: * Trackball / arrow keys : steer (left/right), gas (up), brake (down) * W / S : gas on / brake pulse A / D : steer * Enter / click : start / restart P : toggle auto-play */ #include #include #include #include #include #include "utilities.h" #include "sprites.h" #include "sound_engine.h" TFT_eSPI tft; SoundEngine sound; static int scrW, scrH; // --------------------------------------------------------------------------- // Tunables // --------------------------------------------------------------------------- static const uint32_t FRAME_MS = 33; // ~30 fps static const int SEG_LEN = 200; // segment length (world units) static const int RUMBLE_SEGS = 3; // segments per rumble stripe static const int DRAW_DIST = 90; // segments drawn ahead static const float ROAD_W = 1000.0f; // road half-width (world units) static const float CAM_H = 1500.0f; // camera height above road static const float CAM_D = 0.84f; // 1/tan(fov/2), fov ~100 deg static const float CENTRIFUGAL = 0.28f; static const float MAX_SPEED = SEG_LEN * 60.0f; static const float ACCEL = MAX_SPEED / 4.5f; static const float BRAKE = -MAX_SPEED * 1.2f; static const float DECEL = -MAX_SPEED / 5.0f; static const float OFF_DECEL = -MAX_SPEED / 1.5f; static const float OFF_LIMIT = MAX_SPEED / 4.0f; static const int LAPS = 3; static const float LAP_TIME = 75.0f; // --------------------------------------------------------------------------- // Track // --------------------------------------------------------------------------- struct Segment { float curve; float y1, y2; // road elevation at segment start / end float clip; // screen y: sprite rows below this are hidden uint8_t spriteType[2]; int8_t spriteOff[2]; // lateral offset in 1/8 road-half units uint8_t spriteCount; }; static const int MAX_SEGS = 1500; static Segment segments[MAX_SEGS]; static int segCount = 0; static float trackLen = 0; // player views per color: 0 rear, 1 slight-turn, 2 turn, 3 side enum { PV_REAR = 0, PV_SLIGHT, PV_TURN, PV_SIDE }; enum { SID_PLAYER_RED = 0, SID_PLAYER_BLUE = 4, SID_PLAYER_WHITE = 8, SID_PLAYER_YELLOW = 12, SID_PALM = 16, SID_PINE, SID_BUSH, SID_BILLBOARD, SID_ARCH, SID_TIRES, SID_CAR_BLUE, SID_CAR_BLUE_T, SID_CAR_WHITE, SID_CAR_WHITE_T, SID_CAR_YELLOW, SID_CAR_YELLOW_T }; enum PlayerColor { PC_RED = 0, PC_BLUE = 1, PC_WHITE = 2, PC_YELLOW = 3 }; static int playerColor = PC_RED; static inline int playerSprite(int view) { return playerColor * 4 + view; } static float lastY() { return segCount ? segments[segCount - 1].y2 : 0.0f; } static void addSegment(float curve, float y) { if (segCount >= MAX_SEGS) return; Segment &s = segments[segCount]; s.curve = curve; s.y1 = lastY(); s.y2 = y; s.clip = 0; s.spriteCount = 0; segCount++; } static float easeIn(float a, float b, float p) { return a + (b - a) * p * p; } static float easeInOut(float a, float b, float p) { return a + (b - a) * (-cosf(p * 3.14159265f) / 2 + 0.5f); } static void addRoad(int enter, int hold, int leave, float curve, float hillY) { float startY = lastY(); float endY = startY + hillY * SEG_LEN; int total = enter + hold + leave; for (int i = 0; i < enter; i++) addSegment(easeIn(0, curve, (float)i / enter), easeInOut(startY, endY, (float)(i + 1) / total)); for (int i = 0; i < hold; i++) addSegment(curve, easeInOut(startY, endY, (float)(enter + i + 1) / total)); for (int i = 0; i < leave; i++) addSegment(easeInOut(curve, 0, (float)i / leave), easeInOut(startY, endY, (float)(enter + hold + i + 1) / total)); } static void addSprite(int segIdx, int type, float offRoadHalves) { if (segIdx < 0 || segIdx >= segCount) return; Segment &s = segments[segIdx]; if (s.spriteCount >= 2) return; s.spriteType[s.spriteCount] = (uint8_t)type; s.spriteOff[s.spriteCount] = (int8_t)(offRoadHalves * 8); s.spriteCount++; } static void addScenery(int segIdx, int type, float side) { float off = side * (1.3f + (float)random(220) / 100.0f); addSprite(segIdx, type, off); } static void buildTrack() { segCount = 0; addRoad(40, 40, 40, 0, 0); // start straight addRoad(30, 50, 30, 2, 0); // gentle right addRoad(30, 40, 30, -3, 10); // left, slight rise addRoad(40, 60, 40, 4, -20); // long right, downhill addRoad(30, 30, 30, 0, 30); // climb addRoad(30, 50, 30, -5, 0); // hard left over the crest addRoad(40, 40, 40, 0, -30); // descend addRoad(25, 35, 25, 3, 0); // S bends addRoad(25, 35, 25, -3, 0); addRoad(40, 70, 40, 5, 20); // long right sweeper, uphill addRoad(30, 30, 30, 0, -10); // downhill straight (tuned to close the elevation loop) addRoad(30, 60, 30, -4, 0); // long left addRoad(20, 20, 20, 6, 0); // tight right addRoad(40, 40, 40, 0, 0); // finish straight trackLen = segCount * (float)SEG_LEN; addSprite(2, SID_ARCH, 0.0f); // start/finish gantry for (int n = 8; n < segCount - 8; n++) { float c = fabsf(segments[n].curve); if (n % 9 == 0) addScenery(n, (random(10) < 5) ? SID_PALM : SID_PINE, -1.0f); if (n % 9 == 4) addScenery(n, (random(10) < 5) ? SID_PINE : SID_PALM, 1.0f); if (n % 17 == 0) addScenery(n, SID_BUSH, (random(2) ? -1.0f : 1.0f)); if (n % 53 == 0) addScenery(n, SID_BILLBOARD, (n % 2) ? -1.8f : 1.8f); if (c > 3.5f && n % 14 == 0) addScenery(n, SID_TIRES, (segments[n].curve > 0) ? -1.15f : 1.15f); } } // --------------------------------------------------------------------------- // Game state // --------------------------------------------------------------------------- enum GameState { ST_TITLE, ST_PLAYING, ST_CRASH, ST_GAMEOVER, ST_WIN, ST_SPRITES }; static GameState gameState = ST_TITLE; static uint32_t stateT0 = 0; static uint32_t nextFrame = 0; static float position_ = 0; static float playerX = 0; static float speed_ = 0; static float timeLeft = LAP_TIME; static int lap = 0; static int score = 0; static bool autoPlay = #ifdef AUTOPLAY true; #else false; #endif ; // sound cooldowns static uint32_t sndAccelT = 0; #ifdef EMULATOR extern bool emuAutoplay; #endif static uint32_t sndSkidT = 0; // steering click tracking for skid trigger static uint32_t turnClickT = 0; static int turnClicks = 0; static void registerTurn() { uint32_t now = millis(); if (now - turnClickT > 350) turnClicks = 0; turnClicks++; turnClickT = now; } // crash / rollover static uint32_t crashT0 = 0; static int crashDir = 1; // slide direction off the road static float crashVel = 0; // sliding speed during the tumble static uint32_t shakeUntil = 0; // camera jolt struct TrafficCar { float z, offset, speed; int sprite, spriteTurn; }; static const int N_CARS = 8; static TrafficCar cars[N_CARS]; // manual input state static float steerInput = 0; static int gasLatch = 0; // W = 1 static uint32_t brakeUntil = 0; static int gasFrame = 0; // resolved each frame: 1 gas, -1 brake // --------------------------------------------------------------------------- // Input: trackball // --------------------------------------------------------------------------- static volatile uint32_t tbEdges[4]; static volatile uint32_t tbClicks; static void IRAM_ATTR tbIsrRight() { tbEdges[0]++; } static void IRAM_ATTR tbIsrUp() { tbEdges[1]++; } static void IRAM_ATTR tbIsrLeft() { tbEdges[2]++; } static void IRAM_ATTR tbIsrDown() { tbEdges[3]++; } static void IRAM_ATTR tbIsrClick() { tbClicks++; } static const int TB_FP = 8; #ifdef EMULATOR static const int TB_IMPULSE = 6; static const int TB_FRICTION = 12; #else static const int TB_IMPULSE = 24; static const int TB_FRICTION = 15; #endif static const int TB_VMAX = 48 << TB_FP; static int32_t tbVelX, tbVelY, tbRemX, tbRemY; static void attachTrackball() { 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); attachInterrupt(digitalPinToInterrupt(tbPins[0]), tbIsrRight, FALLING); attachInterrupt(digitalPinToInterrupt(tbPins[1]), tbIsrUp, FALLING); attachInterrupt(digitalPinToInterrupt(tbPins[2]), tbIsrLeft, FALLING); attachInterrupt(digitalPinToInterrupt(tbPins[3]), tbIsrDown, FALLING); attachInterrupt(digitalPinToInterrupt(tbPins[4]), tbIsrClick, FALLING); } static void resetTrackball() { for (int i = 0; i < 4; i++) tbEdges[i] = 0; tbClicks = 0; tbVelX = tbVelY = tbRemX = tbRemY = 0; } static void applyTrackball(int &pxX, int &pxY, uint32_t &clicks) { uint32_t e[4]; for (int i = 0; i < 4; i++) { e[i] = tbEdges[i]; tbEdges[i] = 0; } clicks = tbClicks; tbClicks = 0; tbVelX += ((int32_t)e[0] - (int32_t)e[2]) * TB_IMPULSE; tbVelY += ((int32_t)e[3] - (int32_t)e[1]) * TB_IMPULSE; if (tbVelX > TB_VMAX) tbVelX = TB_VMAX; if (tbVelX < -TB_VMAX) tbVelX = -TB_VMAX; if (tbVelY > TB_VMAX) tbVelY = TB_VMAX; if (tbVelY < -TB_VMAX) tbVelY = -TB_VMAX; tbVelX = tbVelX * TB_FRICTION / 16; tbVelY = tbVelY * TB_FRICTION / 16; tbRemX += tbVelX; tbRemY += tbVelY; pxX = tbRemX / TB_FP; pxY = tbRemY / TB_FP; tbRemX -= pxX * TB_FP; tbRemY -= pxY * TB_FP; } // --------------------------------------------------------------------------- // Colors / palette (with distance fog) // --------------------------------------------------------------------------- static uint16_t C(uint8_t r, uint8_t g, uint8_t b) { return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3); } static uint16_t palRoad[2][3], palGrassL[3], palGrassD[3], palRumL[3], palRumD[3], palLane[3]; static uint16_t colSkyHi, colSkyLo; static void buildPalette() { colSkyHi = C(70, 130, 220); colSkyLo = C(120, 175, 240); // [light band][fog 0..2] palRoad[0][0] = C(102,102,102); palRoad[1][0] = C(96, 96, 96); palRoad[0][1] = C(128,132,130); palRoad[1][1] = C(122,126,124); palRoad[0][2] = C(150,165,190); palRoad[1][2] = C(146,161,186); palGrassL[0] = C(26,148,54); palGrassD[0] = C(18,118,42); palGrassL[1] = C(70,152,96); palGrassD[1] = C(58,132,84); palGrassL[2] = C(115,165,165);palGrassD[2] = C(104,152,152); palRumL[0] = C(255,255,255); palRumD[0] = C(205,40,40); palRumL[1] = C(235,235,235); palRumD[1] = C(205,120,120); palRumL[2] = C(215,220,225); palRumD[2] = C(205,165,165); palLane[0] = C(255,255,255); palLane[1] = C(235,235,235); palLane[2] = C(215,220,225); } // --------------------------------------------------------------------------- // Draw primitives // --------------------------------------------------------------------------- static inline int iround(float v) { return (int)(v + (v >= 0 ? 0.5f : -0.5f)); } static void fillSpan(int y, float xa, float xb, uint16_t c) { if (y < 0 || y >= scrH) return; int a = iround(xa), b = iround(xb); if (b < a) { int t = a; a = b; b = t; } if (b < 0 || a >= scrW) return; if (a < 0) a = 0; if (b >= scrW) b = scrW - 1; tft.drawFastHLine(a, y, b - a + 1, c); } static void fillTrap(float y1, float xa1, float xb1, float y2, float xa2, float xb2, uint16_t c) { if (y1 == y2) { fillSpan(iround(y1), xa1, xb1, c); return; } int yTop = (int)ceilf(y1 < y2 ? y1 : y2); int yBot = (int)floorf(y1 < y2 ? y2 : y1); for (int y = yTop; y <= yBot; y++) { float t = ((float)y - y1) / (y2 - y1); fillSpan(y, xa1 + (xa2 - xa1) * t, xb1 + (xb2 - xb1) * t, c); } } // scaled sprite, bottom-center anchor, rows below clipY are cut (hill occlusion) static void drawSprite(int id, int destW, float sx, float bottomY, float clipY, bool flip = false) { const GameSprite &sp = SPRITES[id]; if (destW < 1) return; int dw = destW; int dh = (int)(destW * sp.h / sp.w); if (dh < 1) dh = 1; int x0 = iround(sx) - dw / 2; int yBase = iround(bottomY); int clip = iround(clipY); if (x0 >= scrW || x0 + dw <= 0) return; for (int y = 0; y < dh; y++) { int dy = yBase - dh + y; // bottom-up if (dy > clip) continue; // hidden behind nearer geometry / crest if (dy < 0 || dy >= scrH) continue; const uint16_t *row = sp.data + (y * sp.h / dh) * sp.w; int lastC = -2, runStart = 0; for (int x = 0; x <= dw; x++) { uint16_t c = (x < dw) ? row[(flip ? (dw - 1 - x) : x) * sp.w / dw] : (uint16_t)0; bool trans = (x == dw) || (c == SPR_TRANSP); if (!trans) { if (c != lastC) { if (lastC >= 0) { int dx0 = x0 + runStart, wln = x - runStart; if (dx0 < scrW && dx0 + wln > 0) tft.fillRect(dx0, dy, wln, 1, (uint16_t)lastC); } runStart = x; lastC = c; } } else { if (lastC >= 0) { int dx0 = x0 + runStart, wln = x - runStart; if (dx0 < scrW && dx0 + wln > 0) tft.fillRect(dx0, dy, wln, 1, (uint16_t)lastC); } lastC = -2; } } } } // --------------------------------------------------------------------------- // Projection + road render // --------------------------------------------------------------------------- struct Proj { float x, y, w; }; static Proj P1[DRAW_DIST + 2]; static Proj P2[DRAW_DIST + 2]; static int segIdxN[DRAW_DIST + 2]; static bool slotValid[DRAW_DIST + 2]; static void renderRoad() { // LOW horizon (OutRun-style) -> camera feels planted on the road const float HORIZON_Y = scrH * 0.36f; // sky down to just past the vanishing point int skyBot = (int)HORIZON_Y + 14; for (int y = 0; y < skyBot; y++) { uint16_t c = (y < skyBot * 2 / 5) ? colSkyHi : colSkyLo; tft.drawFastHLine(0, y, scrW, c); } float basePercent = fmodf(position_, SEG_LEN) / SEG_LEN; int baseIdx = ((int)(position_ / SEG_LEN)) % segCount; const Segment &bs = segments[baseIdx]; float camY = CAM_H + bs.y1 + (bs.y2 - bs.y1) * basePercent; float camX = playerX * ROAD_W; // whiplash camera jolt if ((int32_t)(millis() - shakeUntil) < 0) camX += (float)(random(201) - 100); float x = 0; float dx = -(bs.curve * basePercent); float maxY = (float)scrH; for (int n = 0; n < DRAW_DIST; n++) { int idx = (baseIdx + n) % segCount; bool looped = idx < baseIdx; float camZ = position_ - (looped ? trackLen : 0); Segment &seg = segments[idx]; float z1 = idx * (float)SEG_LEN - camZ; float z2 = z1 + SEG_LEN; // clamp near plane so the road reaches the bottom of the screen // (avoids a gap where the camera's own segment is skipped) float z1p = z1; float xn = x; const float NEAR_Z = CAM_D * 30.0f; if (z1p < NEAR_Z) { float frac = (NEAR_Z - z1) / SEG_LEN; if (frac > 1.0f) frac = 1.0f; z1p = NEAR_Z; xn = x + dx * frac; } // project p1/p2 (curve accumulated into camera x) float s1 = CAM_D / z1p; float s2 = CAM_D / z2; P1[n].x = scrW / 2.0f + s1 * (0 - (camX - xn)) * scrW / 2.0f; P1[n].y = HORIZON_Y - s1 * (seg.y1 + (seg.y2 - seg.y1) * ((z1p - z1) / SEG_LEN) - camY) * scrH / 2.0f; P1[n].w = s1 * ROAD_W * scrW / 2.0f; float x2 = x + dx; // p2 camera x offset (curve) float camX2 = camX - x2; P2[n].x = scrW / 2.0f + s2 * (0 - camX2) * scrW / 2.0f; P2[n].y = HORIZON_Y - s2 * (seg.y2 - camY) * scrH / 2.0f; P2[n].w = s2 * ROAD_W * scrW / 2.0f; seg.clip = maxY; segIdxN[n] = idx; slotValid[n] = (z1 > NEAR_Z) && (z1 < DRAW_DIST * SEG_LEN * 2.0f); x += dx; dx += seg.curve; if (z2 <= NEAR_Z) continue; // fully behind camera if (P2[n].y >= maxY || P2[n].y >= P1[n].y) continue; // hidden or backfacing int fog = 0; if (n > DRAW_DIST * 3 / 4) fog = 2; else if (n > DRAW_DIST / 2) fog = 1; bool light = ((idx / RUMBLE_SEGS) % 2) == 0; // grass band uint16_t grass = light ? palGrassL[fog] : palGrassD[fog]; int yTop = iround(P2[n].y), yBot = iround(P1[n].y) - 1; for (int y = yTop; y <= yBot; y++) if (y < maxY) tft.drawFastHLine(0, y, scrW, grass); // rumble strips (wide, for speed sensation) float r1 = P1[n].w / 6.0f, r2 = P2[n].w / 6.0f; uint16_t rumble = light ? palRumL[fog] : palRumD[fog]; fillTrap(P1[n].y, P1[n].x - P1[n].w - r1, P1[n].x - P1[n].w, P2[n].y, P2[n].x - P2[n].w - r2, P2[n].x - P2[n].w, rumble); fillTrap(P1[n].y, P1[n].x + P1[n].w + r1, P1[n].x + P1[n].w, P2[n].y, P2[n].x + P2[n].w + r2, P2[n].x + P2[n].w, rumble); // road surface fillTrap(P1[n].y, P1[n].x - P1[n].w, P1[n].x + P1[n].w, P2[n].y, P2[n].x - P2[n].w, P2[n].x + P2[n].w, palRoad[light ? 0 : 1][fog]); // dashed center line on light bands if (light) { float l1 = P1[n].w / 22.0f, l2 = P2[n].w / 22.0f; fillTrap(P1[n].y, P1[n].x - l1, P1[n].x + l1, P2[n].y, P2[n].x - l2, P2[n].x + l2, palLane[fog]); } maxY = P2[n].y; } } // --------------------------------------------------------------------------- // Sprites (far -> near) // --------------------------------------------------------------------------- static void renderSprites() { for (int n = DRAW_DIST - 1; n >= 1; n--) { if (!slotValid[n]) continue; int idx = segIdxN[n]; const Proj &pr = P1[n]; Segment &seg = segments[idx]; for (int si = 0; si < seg.spriteCount; si++) { int type = seg.spriteType[si]; float off = seg.spriteOff[si] / 8.0f; float worldW; switch (type) { case SID_PALM: worldW = 1.1f; break; case SID_PINE: worldW = 1.0f; break; case SID_BUSH: worldW = 0.45f; break; case SID_BILLBOARD: worldW = 1.5f; break; case SID_ARCH: worldW = 4.6f; break; case SID_TIRES: worldW = 0.5f; break; default: worldW = 1.0f; break; } float sx = pr.x + off * pr.w; drawSprite(type, iround(worldW * pr.w), sx, pr.y, seg.clip); } // traffic cars in this segment for (int c = 0; c < N_CARS; c++) { int carSeg = (int)(cars[c].z / SEG_LEN) % segCount; if (carSeg != idx) continue; float percent = fmodf(cars[c].z, SEG_LEN) / SEG_LEN; const Proj &pn = (n + 1 < DRAW_DIST && slotValid[n + 1]) ? P1[n + 1] : pr; float sx = pr.x + (pn.x - pr.x) * percent + cars[c].offset * pr.w; float sy = pr.y + (pn.y - pr.y) * percent; float w = pr.w + (pn.w - pr.w) * percent; // lean into corners: turning 3/4 view, mirrored on right-hand curves float cv = segments[idx].curve; int sid = (fabsf(cv) > 1.5f) ? cars[c].spriteTurn : cars[c].sprite; drawSprite(sid, iround(w * 0.48f), sx, sy, seg.clip, cv > 0); } } } static void drawPlayerCar() { const int CAR_W = 64; // player car width on screen (px) float speedPct = speed_ / MAX_SPEED; float bounce = (float)(random(3) - 1) * speedPct * 1.0f; float cx = scrW / 2.0f + steerInput * 5.0f; int baseY = scrH - 3 + (int)bounce; // dirt rushing from the rear wheels while accelerating if (gasFrame > 0 && speed_ > MAX_SPEED * 0.15f) { for (int i = 0; i < 10; i++) { int side = (i < 5) ? -1 : 1; int dx0 = iround(cx) + side * (14 + (int)random(6)); int dy0 = baseY - 2 - (int)random(14); int r = 1 + (int)random(3); uint8_t g = 110 + (uint8_t)random(60); tft.fillCircle(dx0, dy0, r, C(g, g - 20, g - 40)); } // skid-like streaks when launching hard if (speedPct < 0.4f) { for (int i = 0; i < 4; i++) { int side = (i < 2) ? -1 : 1; int x0 = iround(cx) + side * 16; tft.drawFastVLine(x0, baseY - 18, 12, C(150, 140, 120)); } } } // contact shadow -> plants the car on the road for (int dy = 0; dy < 5; dy++) { int wdt = CAR_W - 6 - dy * 7; if (wdt > 0) tft.drawFastHLine(scrW / 2 - wdt / 2, baseY + dy, wdt, C(30, 30, 26)); } float ta = fabsf(steerInput); int view = PV_REAR; if (ta > 0.75f) view = PV_TURN; else if (ta > 0.30f) view = PV_SLIGHT; bool flip = steerInput > 0; // sheet views face nose-left; mirror for right turns drawSprite(playerSprite(view), CAR_W, cx, baseY, scrH, flip); } // rollover animation: spare car sprites tumbling off the road static void drawCrashCar() { uint32_t t = millis() - crashT0; const float DUR = 2300.0f; float p = t / DUR; if (p > 1) p = 1; // sprite sequence: rear -> slight -> turn -> side (rolling over) int id; if (t < 260) { id = playerSprite(PV_REAR); } else { int f = ((t - 260) / 140) % 3; id = playerSprite(PV_SLIGHT + f); } float cx = scrW / 2.0f + crashDir * p * 46.0f; if (t < 650) cx += (float)(random(7) - 3); // whiplash shake float hop = -sinf(p * 3.14159f) * 16.0f; // airborne arc int baseY = scrH - 3 + (int)hop; int w = 64 + (int)(sinf(p * 3.14159f) * 12.0f); // swells mid-tumble // dust kicked up opposite the slide for (int i = 0; i < 5; i++) { int dx0 = iround(cx) - crashDir * (28 + (int)random(26)); int dy0 = baseY - (int)random(10); tft.fillCircle(dx0, dy0, 1 + (int)random(2), C(150, 140, 120)); } drawSprite(id, w, cx, baseY, scrH, crashDir > 0); } // --------------------------------------------------------------------------- // HUD // --------------------------------------------------------------------------- static void drawHUD() { tft.setTextDatum(TL_DATUM); tft.setTextFont(2); tft.setTextColor(TFT_WHITE, C(15,15,18)); char buf[48]; snprintf(buf, sizeof(buf), "TIME %d", (int)ceilf(timeLeft)); tft.drawString(buf, 6, 4); snprintf(buf, sizeof(buf), "LAP %d/%d", lap + 1 < 1 ? 1 : lap + 1, LAPS); tft.drawString(buf, 6, 22); tft.setTextDatum(TR_DATUM); snprintf(buf, sizeof(buf), "%d km/h", (int)(speed_ / 100.0f)); tft.drawString(buf, scrW - 6, 4); tft.setTextDatum(TL_DATUM); } // --------------------------------------------------------------------------- // Simulation // --------------------------------------------------------------------------- static void placeTraffic() { const float lane[3] = { -0.66f, 0.0f, 0.66f }; for (int i = 0; i < N_CARS; i++) { cars[i].z = (float)random((long)trackLen); cars[i].offset = lane[i % 3]; cars[i].speed = MAX_SPEED * (0.25f + (float)random(30) / 100.0f); static const int carSets[3][2] = { { SID_CAR_BLUE, SID_CAR_BLUE_T }, { SID_CAR_WHITE, SID_CAR_WHITE_T }, { SID_CAR_YELLOW, SID_CAR_YELLOW_T }, }; cars[i].sprite = carSets[i % 3][0]; cars[i].spriteTurn = carSets[i % 3][1]; } } static void startGame() { position_ = 0; playerX = 0; speed_ = 0; timeLeft = LAP_TIME; lap = 0; score = 0; steerInput = 0; gasLatch = 0; brakeUntil = 0; // manual gas by default (no auto-throttle) placeTraffic(); gameState = ST_PLAYING; stateT0 = millis(); } static float clampf(float v, float lo, float hi) { return v < lo ? lo : (v > hi ? hi : v); } static void updateGame(float dt) { int baseIdx = ((int)(position_ / SEG_LEN)) % segCount; const Segment &baseSeg = segments[baseIdx]; float speedPct = speed_ / MAX_SPEED; // --- sound triggers --- uint32_t now = millis(); // continuous engine hum: frequency tracks speed (keep queue short for snappy SFX) if (speed_ > 10.0f && sound.pending() < 2 && (int32_t)(now - sndAccelT) >= 100) { sndAccelT = now; int f = 70 + (int)(speedPct * 170.0f); uint16_t amp = gasFrame > 0 ? 7000 : 4500; SndEvent e = { SND_TONE, (uint16_t)f, 0, 120, amp }; sound.play(e); } bool skid = (turnClicks >= 3) && (fabsf(steerInput) > 0.55f) && (speedPct > 0.45f); if (skid && (int32_t)(now - sndSkidT) >= 600) { sndSkidT = now; turnClicks = 0; sound.clear(); SndEvent e = { SND_SWEEP, 900, 300, 120, 9000 }; sound.play(e); } float dx = dt * 2.4f * (speedPct > 0.18f ? speedPct : 0.18f); // steer authority grows with speed (min so steering works at low speed) if (autoPlay) { // AI: aim inside of upcoming curve, dodge traffic float aheadCurve = 0; for (int k = 2; k < 22; k++) aheadCurve += segments[(baseIdx + k) % segCount].curve; float target = clampf(-aheadCurve * 0.035f, -0.8f, 0.8f); for (int c = 0; c < N_CARS; c++) { float rel = cars[c].z - position_; if (rel < 0) rel += trackLen; if (rel > 0 && rel < SEG_LEN * 14 && fabsf(cars[c].offset - playerX) < 0.55f) target = clampf(cars[c].offset + (cars[c].offset >= 0 ? -0.9f : 0.9f), -0.85f, 0.85f); } if (target > playerX) playerX += dx; else if (target < playerX) playerX -= dx; float maxA = (fabsf(aheadCurve) > 9.0f) ? 0.6f : 1.0f; speed_ += (speed_ < MAX_SPEED * maxA) ? ACCEL * dt : DECEL * dt; } else { playerX += dx * steerInput * 1.8f; if (gasFrame > 0) speed_ += ACCEL * dt; else if (gasFrame < 0) speed_ += BRAKE * dt; else speed_ += DECEL * dt; } // centrifugal force in curves playerX -= dx * speedPct * baseSeg.curve * CENTRIFUGAL; // off-road drag if ((playerX < -1.05f || playerX > 1.05f) && speed_ > OFF_LIMIT) speed_ += OFF_DECEL * dt; // hard off-road excursion -> rollover crash (any speed above a crawl) if (fabsf(playerX) > 1.65f && speed_ > MAX_SPEED * 0.08f) { crashDir = (playerX > 0) ? 1 : -1; crashVel = speed_ * 0.45f; crashT0 = millis(); shakeUntil = crashT0 + 700; score -= 300; if (score < 0) score = 0; speed_ = 0; gameState = ST_CRASH; // crash sound (clear queued hum so it plays immediately) sound.clear(); { SndEvent e = { SND_NOISE, 0, 0, 260, 22000 }; sound.play(e); SndEvent f = { SND_SWEEP, 400, 80, 220, 14000 }; sound.play(f); } return; } playerX = clampf(playerX, -2.2f, 2.2f); if (speed_ < 0) speed_ = 0; if (speed_ > MAX_SPEED) speed_ = MAX_SPEED; position_ += speed_ * dt; while (position_ >= trackLen) { position_ -= trackLen; lap++; timeLeft += 45.0f; score += 2000; if (lap >= LAPS) { gameState = ST_WIN; stateT0 = millis(); return; } } score += (int)(speed_ * dt * 0.02f); for (int c = 0; c < N_CARS; c++) { cars[c].z += cars[c].speed * dt; if (cars[c].z >= trackLen) cars[c].z -= trackLen; float rel = cars[c].z - position_; if (rel < 0) rel += trackLen; if (rel < SEG_LEN * 0.9f && fabsf(cars[c].offset - playerX) < 0.30f) { speed_ = cars[c].speed * 0.6f; position_ = cars[c].z - SEG_LEN * 1.2f; if (position_ < 0) position_ += trackLen; shakeUntil = millis() + 250; // jolt on rear-ending traffic { SndEvent e = { SND_NOISE, 0, 0, 120, 12000 }; sound.play(e); } } } timeLeft -= dt; if (timeLeft <= 0) { timeLeft = 0; gameState = ST_GAMEOVER; stateT0 = millis(); } } // rollover: slide, tumble through the spare car sprites, then rejoin static void updateCrash(float dt) { crashVel *= 0.90f; position_ += crashVel * dt; if (position_ >= trackLen) position_ -= trackLen; timeLeft -= dt; if (millis() - crashT0 > 2300) { playerX = crashDir * 0.55f; // recovered, back on the tarmac speed_ = 0; gasLatch = 1; gameState = ST_PLAYING; } if (timeLeft <= 0) { timeLeft = 0; gameState = ST_GAMEOVER; stateT0 = millis(); } } // --------------------------------------------------------------------------- // Screens // --------------------------------------------------------------------------- static void drawTitle() { // backdrop is our own scene: the start line under the arch position_ = 0; playerX = 0; speed_ = 0; renderRoad(); renderSprites(); tft.setTextDatum(MC_DATUM); tft.setFreeFont(&FreeSansBold24pt7b); tft.setTextColor(TFT_YELLOW, C(15,15,18)); tft.drawString("MIATADRIVE", scrW / 2, 14); tft.setFreeFont(nullptr); tft.setTextFont(2); tft.setTextColor(TFT_WHITE, C(15,15,18)); tft.drawString("W gas S brake A/D steer", scrW / 2, 60); tft.drawString("P auto T sprites Press/tap: race", scrW / 2, 78); // car color picker: 1 Red 2 Blue 3 White 4 Yellow static const char* names[4] = { "1 Red", "2 Blue", "3 White", "4 Yellow" }; uint16_t pal[4] = { C(220,40,40), C(60,90,220), C(235,235,235), C(240,200,40) }; for (int i = 0; i < 4; i++) { tft.setTextColor(i == playerColor ? pal[i] : C(200,200,200), C(15,15,18)); tft.setTextDatum(TC_DATUM); tft.drawString(names[i], 46 + i * 76, 102); if (i == playerColor) { tft.setTextColor(TFT_WHITE, C(15,15,18)); tft.drawString("^", 46 + i * 76, 118); } } tft.setTextDatum(TL_DATUM); // showcase the selected car, parked on the road below the arch drawSprite(playerSprite(PV_REAR), 110, scrW / 2, scrH - 4, scrH); } // sprite test gallery: every SPRITES[] entry at native size on a checkerboard, // bottom-center anchored like in-game, labeled with index + crop size static int spritePage = 0; static void drawSpriteTest() { // checker background for (int by = 0; by < scrH; by += 8) for (int bx = 0; bx < scrW; bx += 8) { uint16_t c = (((bx / 8) + (by / 8)) & 1) ? C(70,70,74) : C(135,135,138); tft.fillRect(bx, by, 8, 8, c); } // build list of sprite ids for this page int ids[12]; int nids = 0; if (spritePage < 4) { int color = spritePage; // 0..3 ids[nids++] = color * 4 + PV_REAR; ids[nids++] = color * 4 + PV_SLIGHT; ids[nids++] = color * 4 + PV_TURN; } else if (spritePage == 4) { int arr[] = { SPR_CAR_BLUE, SPR_CAR_BLUE_T, SPR_CAR_WHITE, SPR_CAR_WHITE_T, SPR_CAR_YELLOW, SPR_CAR_YELLOW_T }; for (int i = 0; i < 6; i++) ids[nids++] = arr[i]; } else { int arr[] = { SPR_PALM, SPR_PINE, SPR_BUSH, SPR_BILLBOARD, SPR_ARCH, SPR_TIRES }; for (int i = 0; i < 6; i++) ids[nids++] = arr[i]; } const int CELL_W = 96, CELL_H = 96; int cols = 3; for (int i = 0; i < nids; i++) { int col = i % cols, row = i / cols; int cx0 = col * CELL_W + 8, cy0 = row * CELL_H + 24; tft.drawRect(cx0, cy0, CELL_W, CELL_H, C(20,20,24)); const GameSprite &sp = SPRITES[ids[i]]; int destW = sp.w <= CELL_W - 8 ? sp.w : CELL_W - 8; if (destW * sp.h / sp.w > CELL_H - 16) destW = (CELL_H - 16) * sp.w / sp.h; drawSprite(ids[i], destW, cx0 + CELL_W / 2, cy0 + CELL_H - 8, scrH); tft.fillCircle(cx0 + CELL_W / 2, cy0 + CELL_H - 8, 1, TFT_MAGENTA); char buf[24]; snprintf(buf, sizeof(buf), "%d %dx%d", ids[i], sp.w, sp.h); tft.setTextDatum(TL_DATUM); tft.setTextFont(1); tft.setTextColor(TFT_YELLOW, C(20,20,24)); tft.drawString(buf, cx0 + 2, cy0 + 2); } tft.setTextFont(2); tft.setTextColor(TFT_WHITE, C(20,20,24)); tft.setTextDatum(TC_DATUM); char title[48]; const char* names[] = { "Car 1", "Car 2", "Car 3", "Car 4", "Traffic cars", "Props" }; snprintf(title, sizeof(title), "Page %d/6: %s (A/D flip, T back)", spritePage + 1, names[spritePage]); tft.drawString(title, scrW / 2, 0); tft.setTextDatum(TL_DATUM); } static void drawEndScreen(bool win) { tft.fillScreen(C(10,10,14)); tft.setTextDatum(MC_DATUM); tft.setFreeFont(&FreeSansBold24pt7b); tft.setTextColor(win ? TFT_GREEN : TFT_RED, C(10,10,14)); tft.drawString(win ? "FINISH!" : "GAME OVER", scrW / 2, 80); tft.setFreeFont(nullptr); tft.setTextFont(2); tft.setTextColor(TFT_WHITE, C(10,10,14)); char buf[48]; snprintf(buf, sizeof(buf), "Score %d", score); tft.drawString(buf, scrW / 2, 140); tft.setTextColor(TFT_GOLD, C(10,10,14)); tft.drawString("Press to restart", scrW / 2, 190); tft.setTextDatum(TL_DATUM); } static void render() { switch (gameState) { case ST_TITLE: drawTitle(); break; case ST_SPRITES: drawSpriteTest(); break; case ST_GAMEOVER: drawEndScreen(false); break; case ST_WIN: drawEndScreen(true); break; default: renderRoad(); renderSprites(); if (gameState == ST_CRASH) drawCrashCar(); else drawPlayerCar(); drawHUD(); break; } } // --------------------------------------------------------------------------- // Keyboard // --------------------------------------------------------------------------- static void pollKeyboard() { static char lastKey = 0; Wire.requestFrom((uint8_t)0x55, (uint8_t)1); if (Wire.available() == 0) { lastKey = 0; return; } char k = (char)Wire.read(); if (k == 0) { lastKey = 0; return; } if (k == lastKey) return; lastKey = k; char c = tolower(k); switch (c) { case 'w': gasLatch = 1; break; case 's': brakeUntil = millis() + 500; gasLatch = 0; break; case 'a': if (gameState == ST_SPRITES) { spritePage = (spritePage + 5) % 6; } else { steerInput -= 0.4f; registerTurn(); } break; case 'd': if (gameState == ST_SPRITES) { spritePage = (spritePage + 1) % 6; } else { steerInput += 0.4f; registerTurn(); } break; case 'p': autoPlay = !autoPlay; break; case '1': playerColor = PC_RED; if (gameState == ST_TITLE) drawTitle(); break; case '2': playerColor = PC_BLUE; if (gameState == ST_TITLE) drawTitle(); break; case '3': playerColor = PC_WHITE; if (gameState == ST_TITLE) drawTitle(); break; case '4': playerColor = PC_YELLOW; if (gameState == ST_TITLE) drawTitle(); break; case 't': if (gameState == ST_SPRITES) { gameState = ST_TITLE; stateT0 = millis(); } else gameState = ST_SPRITES; break; case ' ': case 'r': if (gameState == ST_TITLE) startGame(); else if (gameState == ST_GAMEOVER || gameState == ST_WIN) { gameState = ST_TITLE; stateT0 = millis(); } break; } steerInput = clampf(steerInput, -1, 1); } // --------------------------------------------------------------------------- // Hardware // --------------------------------------------------------------------------- static void hardwareInit() { Serial.begin(115200); pinMode(BOARD_POWERON, OUTPUT); digitalWrite(BOARD_POWERON, HIGH); 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); digitalWrite(BOARD_BL_PIN, HIGH); Wire.begin(BOARD_I2C_SDA, BOARD_I2C_SCL); attachTrackball(); randomSeed(esp_random()); } void setup() { hardwareInit(); scrW = tft.width(); scrH = tft.height(); buildPalette(); buildTrack(); if (!sound.begin()) Serial.println("Sound engine init failed"); sound.setVolume(5); #ifdef EMULATOR if (emuAutoplay) autoPlay = true; #endif drawTitle(); } void loop() { uint32_t now = millis(); if (now < 800) { resetTrackball(); delay(1); return; } if ((int32_t)(now - nextFrame) < 0) { delay(1); return; } float dt = (nextFrame == 0) ? 0.033f : (float)(now - (nextFrame - FRAME_MS)) / 1000.0f; if (dt < 0.004f) dt = 0.004f; if (dt > 0.1f) dt = 0.1f; nextFrame = now + FRAME_MS; int pxX, pxY; uint32_t clicks; applyTrackball(pxX, pxY, clicks); if (clicks) { if (gameState == ST_TITLE) startGame(); else if (gameState == ST_GAMEOVER || gameState == ST_WIN) { gameState = ST_TITLE; stateT0 = millis(); } } pollKeyboard(); // resolve manual input for this frame gasFrame = gasLatch; if (pxY < 0) gasFrame = 1; if (pxY > 0) gasFrame = -1; if ((int32_t)(now - brakeUntil) < 0) gasFrame = -1; if (gameState == ST_PLAYING && !autoPlay) { if (pxX) { steerInput += (pxX > 0 ? 1 : -1) * 0.4f; registerTurn(); } else steerInput *= 0.90f; // auto-center only when not steering steerInput = clampf(steerInput, -1, 1); } // auto-play driver / demo loop if (autoPlay) { if (gameState == ST_TITLE && now - stateT0 > 1200) startGame(); if ((gameState == ST_GAMEOVER || gameState == ST_WIN) && now - stateT0 > 3500) { gameState = ST_TITLE; stateT0 = millis(); } } if (gameState == ST_PLAYING) updateGame(dt); else if (gameState == ST_CRASH) updateCrash(dt); render(); }