


#include <Adafruit_GFX.h>
#include <Adafruit_ST7735.h>
#include <SPI.h>
#include <EEPROM.h>
// Adjust these pins to match your wiring.
#define TFT_CS 10
#define TFT_DC 9
#define TFT_RST 8
#define JOY_X A0
#define JOY_Y A1
#define JOY_SW 4
// SCREEN SIZE
#define SCREEN_W 160
#define SCREEN_H 128
// COLORS
#define BLACK ST77XX_BLACK
#define WHITE ST77XX_WHITE
#define RED ST77XX_RED
#define GREEN ST77XX_GREEN
#define BLUE ST77XX_BLUE
#define YELLOW ST77XX_YELLOW
#define CYAN ST77XX_CYAN
#define ORANGE 0xFD20
#define GRAY 0x8410
Adafruit_ST7735 tft(TFT_CS, TFT_DC, TFT_RST);
// =============================================
// GAME MODES
// =============================================
enum GameMode {
MENU,
TETRIS,
PONG,
BREAKOUT,
GALAXY,
RACING,
SNAKE,
GAME_OVER
};
GameMode mode = MENU;
GameMode lastGame = TETRIS;
byte selectedGame = 0;
uint16_t score = 0;
uint16_t highScores[6];
byte level = 1;
// =============================================
// JOYSTICK
// =============================================
int joyX = 512;
int joyY = 512;
bool buttonNow = false;
bool buttonPrevious = false;
bool buttonPressed = false;
bool buttonLocked = false;
bool actionQueued = false;
unsigned long buttonStart = 0;
unsigned long menuTimer = 0;
// =============================================
// SHARED GAME VARIABLES
// =============================================
unsigned long frameTimer = 0;
int ballX = 80;
int ballY = 64;
int ballVX = 2;
int ballVY = 2;
// =============================================
// FUNCTION DECLARATIONS
// =============================================
void drawMenu();
void startGame(GameMode game);
void endGame();
void drawHUD();
// =============================================
// INPUT
// =============================================
bool left() {
return joyX < 380;
}
bool right() {
return joyX > 640;
}
bool up() {
return joyY < 380;
}
bool down() {
return joyY > 640;
}
void saveHighScore() {
byte index = (byte)lastGame - 1;
if (index >= 6) return;
if (score > highScores[index]) {
highScores[index] = score;
EEPROM.put(
2 + index * 2,
highScores[index]
);
}
}
void readJoystick() {
joyX = analogRead(JOY_X);
joyY = analogRead(JOY_Y);
buttonNow = digitalRead(JOY_SW) == LOW;
buttonPressed =
buttonNow &&
!buttonPrevious &&
!buttonLocked;
if (buttonNow && !buttonPrevious) {
buttonStart = millis();
}
if (!buttonNow) {
buttonLocked = false;
}
// Hold button for 2 seconds to return to menu
if (buttonNow &&
!buttonLocked &&
mode != MENU &&
millis() - buttonStart >= 2000UL) {
if (mode != GAME_OVER) {
saveHighScore();
}
mode = MENU;
buttonLocked = true;
actionQueued = false;
drawMenu();
}
buttonPrevious = buttonNow;
}
// =============================================
// EEPROM HIGH SCORES
// =============================================
void loadHighScores() {
if (EEPROM.read(0) != 0x4E ||
EEPROM.read(1) != 0x55) {
EEPROM.update(0, 0x4E);
EEPROM.update(1, 0x55);
for (byte i = 0; i < 6; i++) {
highScores[i] = 0;
EEPROM.put(
2 + i * 2,
highScores[i]
);
}
} else {
for (byte i = 0; i < 6; i++) {
EEPROM.get(
2 + i * 2,
highScores[i]
);
}
}
// Upgrade existing five-game EEPROM saves without losing them.
if (EEPROM.read(14) != 0x53) {
highScores[5] = 0;
EEPROM.put(12, highScores[5]);
EEPROM.update(14, 0x53);
}
}
// =============================================
// SCORE AND LEVEL DISPLAY
// =============================================
void drawHUD() {
tft.fillRect(
0, 0,
SCREEN_W, 13,
BLACK
);
tft.setTextSize(1);
tft.setTextColor(YELLOW);
tft.setCursor(2, 3);
tft.print(F("S:"));
tft.print(score);
tft.setTextColor(GREEN);
tft.setCursor(66, 3);
tft.print(F("L:"));
tft.print(level);
tft.setTextColor(CYAN);
tft.setCursor(105, 3);
tft.print(F("HI:"));
byte index = (byte)lastGame - 1;
if (index < 6) {
tft.print(highScores[index]);
}
}
void addScore(uint16_t points) {
if ((uint32_t)score + points > 65535UL) {
score = 65535;
} else {
score += points;
}
drawHUD();
}
void nextLevel() {
if (level < 20) {
level++;
}
drawHUD();
}
// =============================================
// MAIN MENU
// =============================================
void drawMenu() {
tft.fillScreen(BLACK);
tft.setTextSize(2);
tft.setTextColor(CYAN);
tft.setCursor(12, 3);
tft.print(F("NANO ARCADE"));
tft.drawFastHLine(
5, 27,
150, BLUE
);
tft.setTextSize(1);
for (byte i = 0; i < 6; i++) {
int y = 32 + i * 14;
if (selectedGame == i) {
tft.fillRect(
4, y - 2,
152, 13,
BLUE
);
tft.setTextColor(YELLOW);
} else {
tft.setTextColor(WHITE);
}
tft.setCursor(10, y);
if (selectedGame == i) {
tft.print(F("> "));
} else {
tft.print(F(" "));
}
switch (i) {
case 0:
tft.print(F("TETRIS"));
break;
case 1:
tft.print(F("PONG"));
break;
case 2:
tft.print(F("BREAKOUT"));
break;
case 3:
tft.print(F("GALAXY DEFENDER"));
break;
case 4:
tft.print(F("RACING CHALLENGE"));
break;
case 5:
tft.print(F("SNAKE"));
break;
}
}
tft.setTextColor(GREEN);
tft.setCursor(25, 119);
tft.print(F("PRESS TO PLAY"));
}
void updateMenu() {
if (millis() - menuTimer > 190) {
if (up()) {
selectedGame =
(selectedGame + 5) % 6;
drawMenu();
menuTimer = millis();
} else if (down()) {
selectedGame =
(selectedGame + 1) % 6;
drawMenu();
menuTimer = millis();
}
}
if (buttonPressed) {
startGame(
(GameMode)(selectedGame + 1)
);
}
}
// =============================================
// GAME OVER
// =============================================
void endGame() {
if (mode == GAME_OVER ||
mode == MENU) {
return;
}
lastGame = mode;
saveHighScore();
mode = GAME_OVER;
actionQueued = false;
tft.fillScreen(BLACK);
tft.setTextSize(2);
tft.setTextColor(RED);
tft.setCursor(20, 25);
tft.print(F("GAME OVER"));
tft.setTextSize(1);
tft.setTextColor(YELLOW);
tft.setCursor(30, 65);
tft.print(F("SCORE: "));
tft.print(score);
tft.setCursor(30, 80);
tft.print(F("LEVEL: "));
tft.print(level);
tft.setCursor(30, 95);
tft.print(F("BEST: "));
tft.print(highScores[(byte)lastGame - 1]);
tft.setTextColor(WHITE);
tft.setCursor(15, 114);
tft.print(F("PRESS TO RESTART"));
}
// =============================================
// GAME 1 - TETRIS
// =============================================
#define TC 10
#define TR 16
#define TS 7
byte board[TR][TC];
const byte shapes[7][4][2] PROGMEM = {
{{0,1},{1,1},{2,1},{3,1}},
{{1,0},{2,0},{1,1},{2,1}},
{{1,0},{0,1},{1,1},{2,1}},
{{1,0},{2,0},{0,1},{1,1}},
{{0,0},{1,0},{1,1},{2,1}},
{{0,0},{0,1},{1,1},{2,1}},
{{2,0},{0,1},{1,1},{2,1}}
};
byte pieceType = 0;
byte pieceRotation = 0;
int pieceX = 3;
int pieceY = -1;
unsigned long tetrisDrop = 0;
unsigned long tetrisMove = 0;
bool rotateReady = true;
uint16_t linesCleared = 0;
void blockXY(
byte i,
byte rotation,
int &x,
int &y
) {
x = pgm_read_byte(
&shapes[pieceType][i][0]
);
y = pgm_read_byte(
&shapes[pieceType][i][1]
);
if (pieceType != 1) {
for (byte r = 0; r < rotation; r++) {
int oldX = x;
x = 3 - y;
y = oldX;
}
}
}
bool pieceFits(
int dx,
int dy,
byte rotation
) {
for (byte i = 0; i < 4; i++) {
int x, y;
blockXY(i, rotation, x, y);
x += pieceX + dx;
y += pieceY + dy;
if (x < 0 ||
x >= TC ||
y >= TR) {
return false;
}
if (y >= 0 && board[y][x]) {
return false;
}
}
return true;
}
void newPiece() {
pieceType = random(7);
pieceRotation = 0;
pieceX = 3;
pieceY = -1;
if (!pieceFits(0, 0, 0)) {
endGame();
}
}
void lockPiece() {
for (byte i = 0; i < 4; i++) {
int x, y;
blockXY(
i,
pieceRotation,
x, y
);
x += pieceX;
y += pieceY;
if (y < 0) {
endGame();
return;
}
board[y][x] = pieceType + 1;
}
for (int y = TR - 1; y >= 0; y--) {
bool full = true;
for (byte x = 0; x < TC; x++) {
if (!board[y][x]) {
full = false;
}
}
if (full) {
linesCleared++;
addScore(100);
// Increase level every 2 lines
if (linesCleared % 2 == 0) {
nextLevel();
}
for (int yy = y; yy > 0; yy--) {
for (byte x = 0; x < TC; x++) {
board[yy][x] =
board[yy - 1][x];
}
}
for (byte x = 0; x < TC; x++) {
board[0][x] = 0;
}
y++;
}
}
newPiece();
}
void drawTetris() {
// Redraw only when the piece changes
tft.fillRect(
8, 14,
70, 112,
BLACK
);
for (byte y = 0; y < TR; y++) {
for (byte x = 0; x < TC; x++) {
if (board[y][x]) {
tft.fillRect(
8 + x * TS,
14 + y * TS,
6, 6,
CYAN
);
}
}
}
for (byte i = 0; i < 4; i++) {
int x, y;
blockXY(
i,
pieceRotation,
x, y
);
x += pieceX;
y += pieceY;
if (y >= 0 && y < TR) {
tft.fillRect(
8 + x * TS,
14 + y * TS,
6, 6,
YELLOW
);
}
}
}
void updateTetris() {
unsigned long now = millis();
bool changed = false;
if (now - tetrisMove >= 125) {
if (left() &&
pieceFits(-1, 0, pieceRotation)) {
pieceX--;
changed = true;
} else if (right() &&
pieceFits(1, 0, pieceRotation)) {
pieceX++;
changed = true;
}
tetrisMove = now;
}
if (up() && rotateReady) {
byte r = (pieceRotation + 1) % 4;
if (pieceFits(0, 0, r)) {
pieceRotation = r;
changed = true;
}
rotateReady = false;
}
if (!up()) {
rotateReady = true;
}
// Falling speed increases each level
unsigned long interval =
500UL - (unsigned long)(level - 1) * 23UL;
if (interval < 65) {
interval = 65;
}
if (down()) {
interval = 45;
}
if (now - tetrisDrop >= interval) {
if (pieceFits(0, 1, pieceRotation)) {
pieceY++;
} else {
lockPiece();
}
changed = true;
tetrisDrop = now;
}
if (mode == TETRIS && changed) {
drawTetris();
}
}
// =============================================
// GAME 2 - PONG
// =============================================
int pongPaddle = 50;
int pongCPU = 50;
byte pongReturns = 0;
void pongCenterLine() {
for (int y = 17; y < 128; y += 12) {
tft.drawFastVLine(
79, y,
6, GRAY
);
}
}
void resetPongBall() {
ballX = 80;
ballY = 65;
int speed = 2 + (level - 1) / 4;
if (speed > 5) {
speed = 5;
}
ballVX = random(2) ? speed : -speed;
ballVY = random(2) ? 2 : -2;
}
void updatePong() {
unsigned long interval =
40UL - min(23UL, (unsigned long)(level - 1) * 2UL);
if (millis() - frameTimer < interval) {
return;
}
frameTimer = millis();
int oldPaddle = pongPaddle;
int oldCPU = pongCPU;
int oldX = ballX;
int oldY = ballY;
if (up()) pongPaddle -= 4;
if (down()) pongPaddle += 4;
pongPaddle = constrain(
pongPaddle, 15, 106
);
int cpuSpeed = 2 + (level - 1) / 3;
if (cpuSpeed > 5) {
cpuSpeed = 5;
}
if (pongCPU + 11 < ballY) {
pongCPU += cpuSpeed;
}
if (pongCPU + 11 > ballY) {
pongCPU -= cpuSpeed;
}
pongCPU = constrain(
pongCPU, 15, 106
);
ballX += ballVX;
ballY += ballVY;
if (ballY <= 17) {
ballY = 17;
ballVY = abs(ballVY);
}
if (ballY >= 124) {
ballY = 124;
ballVY = -abs(ballVY);
}
// Player paddle collision
if (ballVX < 0 &&
ballX <= 12 &&
ballX >= 5 &&
ballY >= pongPaddle - 3 &&
ballY <= pongPaddle + 25) {
ballX = 12;
ballVX = abs(ballVX);
pongReturns++;
addScore(1);
// Five returns advance one level
if (pongReturns >= 5) {
pongReturns = 0;
nextLevel();
ballVX = min(6, abs(ballVX) + 1);
int newVY = min(5, abs(ballVY) + 1);
ballVY =
ballVY < 0 ? -newVY : newVY;
}
}
// Computer paddle collision
if (ballVX > 0 &&
ballX >= 148 &&
ballX <= 155 &&
ballY >= pongCPU - 3 &&
ballY <= pongCPU + 25) {
ballX = 148;
ballVX = -abs(ballVX);
}
if (ballX < 0) {
endGame();
return;
}
if (ballX > 160) {
addScore(5);
resetPongBall();
}
// Erase old positions
tft.fillRect(
5, oldPaddle,
4, 22,
BLACK
);
tft.fillRect(
151, oldCPU,
4, 22,
BLACK
);
tft.fillCircle(
oldX, oldY,
4, BLACK
);
if (oldX >= 75 && oldX <= 83) {
pongCenterLine();
}
// Draw new positions
tft.fillRect(
5, pongPaddle,
4, 22,
GREEN
);
tft.fillRect(
151, pongCPU,
4, 22,
RED
);
tft.fillCircle(
ballX, ballY,
3, WHITE
);
}
// =============================================
// GAME 3 - BREAKOUT
// =============================================
#define BRICK_ROWS 3
#define BRICK_COLS 8
bool bricks[BRICK_ROWS][BRICK_COLS];
byte bricksRemaining = 0;
int breakoutPaddle = 65;
void resetBricks() {
bricksRemaining =
BRICK_ROWS * BRICK_COLS;
for (byte row = 0; row < BRICK_ROWS; row++) {
for (byte col = 0; col < BRICK_COLS; col++) {
bricks[row][col] = true;
uint16_t color =
row == 0 ? RED :
row == 1 ? ORANGE : YELLOW;
tft.fillRect(
3 + col * 19,
19 + row * 11,
17, 9,
color
);
}
}
}
void updateBreakout() {
unsigned long interval =
40UL - min(24UL, (unsigned long)(level - 1) * 3UL);
if (millis() - frameTimer < interval) {
return;
}
frameTimer = millis();
int oldPaddle = breakoutPaddle;
int oldX = ballX;
int oldY = ballY;
if (left()) breakoutPaddle -= 4;
if (right()) breakoutPaddle += 4;
breakoutPaddle = constrain(
breakoutPaddle, 0, 130
);
ballX += ballVX;
ballY += ballVY;
// Side walls
if (ballX <= 3) {
ballX = 3;
ballVX = abs(ballVX);
}
if (ballX >= 156) {
ballX = 156;
ballVX = -abs(ballVX);
}
// Ceiling
if (ballY <= 16) {
ballY = 16;
ballVY = abs(ballVY);
}
// Paddle collision
if (ballVY > 0 &&
ballY >= 112 &&
ballY <= 120 &&
ballX >= breakoutPaddle - 2 &&
ballX <= breakoutPaddle + 32) {
ballY = 112;
ballVY = -abs(ballVY);
int offset =
ballX - (breakoutPaddle + 15);
if (offset < -5) {
ballVX = -abs(ballVX);
}
if (offset > 5) {
ballVX = abs(ballVX);
}
}
// Brick collisions
bool hitBrick = false;
for (byte row = 0;
row < BRICK_ROWS && !hitBrick;
row++) {
for (byte col = 0; col < BRICK_COLS; col++) {
if (!bricks[row][col]) {
continue;
}
int bx = 3 + col * 19;
int by = 19 + row * 11;
if (ballX + 3 >= bx &&
ballX - 3 <= bx + 17 &&
ballY + 3 >= by &&
ballY - 3 <= by + 9) {
bricks[row][col] = false;
bricksRemaining--;
ballVY = -ballVY;
tft.fillRect(
bx, by,
17, 9,
BLACK
);
addScore(10);
hitBrick = true;
break;
}
}
}
if (ballY > 127) {
endGame();
return;
}
// Erase previous moving objects
tft.fillRect(
oldPaddle, 115,
30, 5,
BLACK
);
tft.fillCircle(
oldX, oldY,
4, BLACK
);
// All bricks destroyed = next level
if (bricksRemaining == 0) {
addScore(100);
nextLevel();
ballX = 80;
ballY = 100;
int speed = 2 + level / 3;
if (speed > 6) {
speed = 6;
}
ballVX = speed;
ballVY = -speed;
resetBricks();
}
// Draw new moving objects
tft.fillRect(
breakoutPaddle, 115,
30, 5,
GREEN
);
tft.fillCircle(
ballX, ballY,
3, WHITE
);
}
// =============================================
// GAME 4 - GALAXY DEFENDER
// =============================================
#define ENEMY_COUNT 12
int enemyX[ENEMY_COUNT];
int enemyY[ENEMY_COUNT];
bool enemyAlive[ENEMY_COUNT];
bool enemyDiving[ENEMY_COUNT];
int enemyDirection = 1;
int galaxyPlayerX = 74;
int laserX = 0;
int laserY = 0;
bool laserActive = false;
unsigned long enemyTimer = 0;
unsigned long laserTimer = 0;
unsigned long diveTimer = 0;
void drawEnemy(
int x,
int y,
uint16_t color
) {
tft.fillRect(
x + 2, y,
8, 3,
color
);
tft.fillRect(
x, y + 3,
12, 5,
color
);
tft.drawPixel(
x + 3, y + 4,
WHITE
);
tft.drawPixel(
x + 8, y + 4,
WHITE
);
}
void drawGalaxyShip() {
tft.fillTriangle(
galaxyPlayerX + 6, 105,
galaxyPlayerX, 118,
galaxyPlayerX + 12, 118,
GREEN
);
}
void createEnemyWave() {
for (byte i = 0; i < ENEMY_COUNT; i++) {
enemyX[i] =
15 + (i % 6) * 23;
enemyY[i] =
25 + (i / 6) * 18;
enemyAlive[i] = true;
enemyDiving[i] = false;
}
enemyDirection = 1;
}
void updateGalaxy() {
unsigned long now = millis();
// Capture button presses independently
// of the animation frame rate.
if (buttonPressed) {
actionQueued = true;
}
// Move player
if (now - frameTimer >= 35) {
int oldX = galaxyPlayerX;
if (left()) galaxyPlayerX -= 3;
if (right()) galaxyPlayerX += 3;
galaxyPlayerX = constrain(
galaxyPlayerX, 0, 148
);
tft.fillRect(
oldX, 104,
13, 15,
BLACK
);
drawGalaxyShip();
frameTimer = now;
}
// Fire laser
if (actionQueued && !laserActive) {
laserActive = true;
laserX = galaxyPlayerX + 6;
laserY = 102;
actionQueued = false;
}
// Move laser
if (now - laserTimer >= 35) {
if (laserActive) {
tft.fillRect(
laserX, laserY,
2, 6,
BLACK
);
laserY -= 5;
if (laserY < 15) {
laserActive = false;
} else {
tft.fillRect(
laserX, laserY,
2, 6,
YELLOW
);
}
}
laserTimer = now;
}
// Enemy movement becomes faster each level
unsigned long enemyInterval =
150UL - min(
110UL,
(unsigned long)(level - 1) * 10UL
);
if (now - enemyTimer < enemyInterval) {
return;
}
enemyTimer = now;
// Erase old enemy positions
for (byte i = 0; i < ENEMY_COUNT; i++) {
if (enemyAlive[i]) {
tft.fillRect(
enemyX[i],
enemyY[i],
12, 8,
BLACK
);
}
}
int formationSpeed =
min(5, 1 + (int)level / 3);
int diveSpeed =
min(7, 2 + (int)level / 2);
bool anyAlive = false;
bool edgeReached = false;
for (byte i = 0; i < ENEMY_COUNT; i++) {
if (!enemyAlive[i]) {
continue;
}
anyAlive = true;
if (enemyDiving[i]) {
enemyY[i] += diveSpeed;
if (enemyX[i] < galaxyPlayerX) {
enemyX[i] += 2;
} else {
enemyX[i] -= 2;
}
if (enemyY[i] > 125) {
enemyDiving[i] = false;
enemyY[i] =
25 + (i / 6) * 18;
enemyX[i] =
15 + (i % 6) * 23;
}
} else {
enemyX[i] +=
enemyDirection * formationSpeed;
if (enemyX[i] <= 2 ||
enemyX[i] >= 146) {
edgeReached = true;
}
}
// Laser collision
if (laserActive &&
abs(laserX - (enemyX[i] + 6)) < 9 &&
abs(laserY - (enemyY[i] + 4)) < 8) {
enemyAlive[i] = false;
laserActive = false;
tft.fillRect(
laserX, laserY,
2, 6,
BLACK
);
addScore(10);
continue;
}
// Player collision
if (abs((galaxyPlayerX + 6) -
(enemyX[i] + 6)) < 11 &&
abs(111 - (enemyY[i] + 4)) < 11) {
endGame();
return;
}
}
if (edgeReached) {
enemyDirection = -enemyDirection;
}
// Diving attacks become more frequent
unsigned long diveInterval =
1700UL - min(
1200UL,
(unsigned long)(level - 1) * 90UL
);
if (now - diveTimer >= diveInterval) {
byte i = random(ENEMY_COUNT);
if (enemyAlive[i]) {
enemyDiving[i] = true;
}
diveTimer = now;
}
// All enemies destroyed = next level
if (!anyAlive) {
addScore(100);
nextLevel();
createEnemyWave();
}
// Draw enemies
for (byte i = 0; i < ENEMY_COUNT; i++) {
if (enemyAlive[i]) {
drawEnemy(
enemyX[i],
enemyY[i],
enemyDiving[i] ? RED : CYAN
);
}
}
}
// =============================================
// GAME 5 - RACING CHALLENGE
// =============================================
// Three-lane highway
#define TRAFFIC_COUNT 3
const int laneCenters[3] = {
49, 80, 111
};
byte playerLane = 1;
int trafficY[TRAFFIC_COUNT];
byte trafficLane[TRAFFIC_COUNT];
bool trafficActive[TRAFFIC_COUNT];
byte carsPassed = 0;
byte roadOffset = 0;
unsigned long racingTimer = 0;
unsigned long steeringTimer = 0;
// ---------------------------------------------
// DRAW RACING CAR
// ---------------------------------------------
void drawCar(
int centerX,
int y,
uint16_t color
) {
// Car body
tft.fillRoundRect(
centerX - 7,
y,
14, 19,
2,
color
);
// Windshield
tft.fillRect(
centerX - 5,
y + 4,
10, 5,
CYAN
);
// Wheels
tft.fillRect(
centerX - 9,
y + 4,
2, 5,
BLACK
);
tft.fillRect(
centerX + 7,
y + 4,
2, 5,
BLACK
);
}
// ---------------------------------------------
// DRAW ROAD
// ---------------------------------------------
void drawRoad() {
tft.fillRect(
30, 13,
100, 115,
GRAY
);
// Road boundaries
tft.drawFastVLine(
30, 13,
115, YELLOW
);
tft.drawFastVLine(
129, 13,
115, YELLOW
);
// Lane markings
for (int y = 16; y < 128; y += 20) {
tft.fillRect(
64, y,
2, 10,
WHITE
);
tft.fillRect(
95, y,
2, 10,
WHITE
);
}
}
// ---------------------------------------------
// RESET TRAFFIC CAR
// ---------------------------------------------
void resetTraffic(byte i) {
trafficLane[i] = random(3);
trafficY[i] =
-24 - random(20, 100);
trafficActive[i] = true;
}
// ---------------------------------------------
// UPDATE RACING CHALLENGE
// ---------------------------------------------
void updateRacing() {
unsigned long now = millis();
// Each level increases traffic speed.
unsigned long interval =
55UL - min(
37UL,
(unsigned long)(level - 1) * 3UL
);
if (now - racingTimer < interval) {
return;
}
racingTimer = now;
// -----------------------------------------
// PLAYER STEERING
// -----------------------------------------
if (now - steeringTimer >= 125) {
if (left() && playerLane > 0) {
playerLane--;
steeringTimer = now;
} else if (right() && playerLane < 2) {
playerLane++;
steeringTimer = now;
}
}
// -----------------------------------------
// RESTORE ROAD BACKGROUND
// -----------------------------------------
// The HUD is never cleared during racing.
// Only the road area is updated.
tft.fillRect(
31, 13,
98, 115,
GRAY
);
// -----------------------------------------
// ANIMATE ROAD MARKINGS
// -----------------------------------------
roadOffset = (roadOffset + 3) % 20;
for (int y = 16 + roadOffset;
y < 128;
y += 20) {
tft.fillRect(
64, y,
2, 10,
WHITE
);
tft.fillRect(
95, y,
2, 10,
WHITE
);
}
// -----------------------------------------
// TRAFFIC SPEED
// -----------------------------------------
int trafficSpeed = 2 + level;
if (trafficSpeed > 10) {
trafficSpeed = 10;
}
// -----------------------------------------
// MOVE TRAFFIC
// -----------------------------------------
for (byte i = 0; i < TRAFFIC_COUNT; i++) {
if (!trafficActive[i]) {
continue;
}
trafficY[i] += trafficSpeed;
// Successfully passed a vehicle
if (trafficY[i] > 128) {
resetTraffic(i);
carsPassed++;
addScore(10);
// Every 10 cars = next level
if (carsPassed >= 10) {
carsPassed = 0;
nextLevel();
}
}
}
// -----------------------------------------
// COLLISION DETECTION
// -----------------------------------------
for (byte i = 0; i < TRAFFIC_COUNT; i++) {
if (!trafficActive[i]) {
continue;
}
if (trafficLane[i] == playerLane &&
trafficY[i] + 19 >= 105 &&
trafficY[i] <= 124) {
endGame();
return;
}
}
// -----------------------------------------
// DRAW TRAFFIC
// -----------------------------------------
for (byte i = 0; i < TRAFFIC_COUNT; i++) {
if (trafficActive[i] &&
trafficY[i] > -19 &&
trafficY[i] < 128) {
drawCar(
laneCenters[trafficLane[i]],
trafficY[i],
RED
);
}
}
// -----------------------------------------
// DRAW PLAYER CAR
// -----------------------------------------
drawCar(
laneCenters[playerLane],
105,
GREEN
);
}
// =============================================
// GAME 6 - SNAKE
// =============================================
// 20 x 14 cells of 8 pixels, below the 13-pixel HUD.
#define SNAKE_COLS 20
#define SNAKE_ROWS 14
#define SNAKE_CELL 8
#define SNAKE_TOP 16
#define SNAKE_MAX 100
byte snakeX[SNAKE_MAX];
byte snakeY[SNAKE_MAX];
byte snakeLength = 3;
byte snakeDir = 1; // 0 up, 1 right, 2 down, 3 left
byte snakeNextDir = 1;
byte foodX = 0;
byte foodY = 0;
byte snakeEaten = 0;
unsigned long snakeTimer = 0;
void snakeCell(byte x, byte y, uint16_t color) {
tft.fillRect((int)x * SNAKE_CELL + 1,
SNAKE_TOP + (int)y * SNAKE_CELL + 1,
SNAKE_CELL - 2, SNAKE_CELL - 2, color);
}
bool snakeOccupies(byte x, byte y) {
for (byte i = 0; i < snakeLength; i++) {
if (snakeX[i] == x && snakeY[i] == y) return true;
}
return false;
}
void placeSnakeFood() {
// Choose uniformly among all free cells, even on a nearly full board.
int freeCells = SNAKE_COLS * SNAKE_ROWS - snakeLength;
if (freeCells <= 0) {
endGame();
return;
}
int target = random(freeCells);
for (byte y = 0; y < SNAKE_ROWS; y++) {
for (byte x = 0; x < SNAKE_COLS; x++) {
if (!snakeOccupies(x, y)) {
if (target-- == 0) {
foodX = x;
foodY = y;
snakeCell(foodX, foodY, RED);
return;
}
}
}
}
}
void initSnake() {
snakeLength = 3;
snakeDir = snakeNextDir = 1;
snakeEaten = 0;
snakeTimer = millis();
for (byte i = 0; i < snakeLength; i++) {
snakeX[i] = 9 - i;
snakeY[i] = 7;
snakeCell(snakeX[i], snakeY[i], i == 0 ? YELLOW : GREEN);
}
placeSnakeFood();
}
void updateSnake() {
// Joystick selects direction; never reverse into the snake.
byte requested = snakeNextDir;
if (up()) requested = 0;
else if (right()) requested = 1;
else if (down()) requested = 2;
else if (left()) requested = 3;
if ((requested + 2) % 4 != snakeDir) snakeNextDir = requested;
unsigned long now = millis();
unsigned long interval = 230UL - min(155UL, (unsigned long)(level - 1) * 12UL);
if (now - snakeTimer < interval) return;
snakeTimer = now;
snakeDir = snakeNextDir;
int nx = snakeX[0];
int ny = snakeY[0];
if (snakeDir == 0) ny--;
else if (snakeDir == 1) nx++;
else if (snakeDir == 2) ny++;
else nx--;
if (nx < 0 || nx >= SNAKE_COLS || ny < 0 || ny >= SNAKE_ROWS) {
endGame();
return;
}
bool eating = (nx == foodX && ny == foodY);
// Moving into the old tail is legal unless the snake is growing.
byte collisionLength = snakeLength - (eating ? 0 : 1);
for (byte i = 0; i < collisionLength; i++) {
if (snakeX[i] == nx && snakeY[i] == ny) {
endGame();
return;
}
}
byte oldTailX = snakeX[snakeLength - 1];
byte oldTailY = snakeY[snakeLength - 1];
byte oldHeadX = snakeX[0];
byte oldHeadY = snakeY[0];
bool grow = eating && snakeLength < SNAKE_MAX;
if (grow) snakeLength++;
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
snakeX[0] = (byte)nx;
snakeY[0] = (byte)ny;
if (!grow) snakeCell(oldTailX, oldTailY, BLACK);
snakeCell(oldHeadX, oldHeadY, GREEN);
snakeCell(snakeX[0], snakeY[0], YELLOW);
if (eating) {
addScore(10);
snakeEaten++;
if (snakeEaten >= 5) {
snakeEaten = 0;
nextLevel();
}
placeSnakeFood();
}
}
// =============================================
// START GAME
// =============================================
void startGame(GameMode game) {
mode = game;
lastGame = game;
score = 0;
level = 1;
actionQueued = false;
tft.fillScreen(BLACK);
drawHUD();
unsigned long now = millis();
frameTimer = now;
switch (game) {
// ---------------------------------------
// TETRIS
// ---------------------------------------
case TETRIS:
memset(
board,
0,
sizeof(board)
);
linesCleared = 0;
rotateReady = true;
tetrisDrop = now;
tetrisMove = now;
tft.drawRect(
6, 13,
74, 113,
WHITE
);
tft.setTextSize(1);
tft.setTextColor(WHITE);
tft.setCursor(90, 36);
tft.print(F("TETRIS"));
tft.setCursor(90, 60);
tft.print(F("UP:ROTATE"));
tft.setCursor(90, 75);
tft.print(F("DN:FAST"));
newPiece();
if (mode == TETRIS) {
drawTetris();
}
break;
// ---------------------------------------
// PONG
// ---------------------------------------
case PONG:
pongPaddle = 50;
pongCPU = 50;
pongReturns = 0;
resetPongBall();
pongCenterLine();
tft.fillRect(
5, pongPaddle,
4, 22,
GREEN
);
tft.fillRect(
151, pongCPU,
4, 22,
RED
);
tft.fillCircle(
ballX, ballY,
3, WHITE
);
break;
// ---------------------------------------
// BREAKOUT
// ---------------------------------------
case BREAKOUT:
breakoutPaddle = 65;
ballX = 80;
ballY = 100;
ballVX = 2;
ballVY = -2;
resetBricks();
tft.fillRect(
breakoutPaddle, 115,
30, 5,
GREEN
);
tft.fillCircle(
ballX, ballY,
3, WHITE
);
break;
// ---------------------------------------
// GALAXY DEFENDER
// ---------------------------------------
case GALAXY:
galaxyPlayerX = 74;
laserActive = false;
enemyTimer = now;
laserTimer = now;
diveTimer = now;
createEnemyWave();
drawGalaxyShip();
for (byte i = 0; i < ENEMY_COUNT; i++) {
drawEnemy(
enemyX[i],
enemyY[i],
CYAN
);
}
break;
// ---------------------------------------
// RACING CHALLENGE
// ---------------------------------------
case RACING:
playerLane = 1;
carsPassed = 0;
roadOffset = 0;
racingTimer = now;
steeringTimer = now;
drawRoad();
for (byte i = 0; i < TRAFFIC_COUNT; i++) {
resetTraffic(i);
trafficY[i] -= i * 50;
}
drawCar(
laneCenters[playerLane],
105,
GREEN
);
break;
case SNAKE:
initSnake();
break;
default:
break;
}
}
// =============================================
// SETUP
// =============================================
void setup() {
pinMode(
JOY_SW,
INPUT_PULLUP
);
randomSeed(
analogRead(A5)
);
tft.initR(INITR_BLACKTAB);
tft.setRotation(1);
loadHighScores();
drawMenu();
}
// =============================================
// MAIN LOOP
// =============================================
void loop() {
readJoystick();
if (mode == MENU) {
updateMenu();
return;
}
if (mode == GAME_OVER) {
if (buttonPressed) {
startGame(lastGame);
}
return;
}
switch (mode) {
case TETRIS:
updateTetris();
break;
case PONG:
updatePong();
break;
case BREAKOUT:
updateBreakout();
break;
case GALAXY:
updateGalaxy();
break;
case RACING:
updateRacing();
break;
case SNAKE:
updateSnake();
break;
default:
break;
}
}




