Projects / Tetris on a colour screen

Tetris on a colour screen

Intermediate4 hGuided buildReviewed

Build it step by step

0 of 8 done
  1. ESP32ILI9341ILI9341

    Wire the TFT

    Follow the table, all on 3V3.

  2. ESP32

    Wire four buttons and the buzzer

    Buttons go to GND.

  3. ESP32ILI9341ILI9341

    Install the libraries

    Adafruit GFX and ILI9341.

  4. ESP32

    Run a screen test

    Fill the screen with a colour first.

  5. ESP32

    Upload the game

    Select the ESP32 board.

  6. ESP32

    Play a round

    Check rotation and walls.

  7. ESP32

    Fill a row on purpose

    Check the line clear and score.

  8. ESP32

    Let the stack reach the top

    Check game over and high score.

In short

How do you build a tetris on a colour screen?

A full Tetris game on a 2.8-inch TFT with rotation, line clears, levels, a buzzer and a high score that survives power-off. You need ESP32 DevKit V1, 2.8 inch TFT touch (ILI9341, SPI), Tactile push button 6 mm × 4, Passive buzzer, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm). It takes 8 steps and about 240 minutes.

Level
Intermediate
Time
About 240 min
Parts
6

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
TFT VCC and LEDESP32 3V3Power and backlight
TFT GNDESP32 GNDCommon ground
TFT CSESP32 GPIO5SPI chip select
TFT RESETESP32 GPIO17Reset
TFT DCESP32 GPIO16Data or command
TFT SDI (MOSI)ESP32 GPIO23SPI data
TFT SCKESP32 GPIO18SPI clock
Button LEFTGPIO32 to GNDInternal pull-up is used
Button RIGHTGPIO33 to GNDInternal pull-up is used
Button ROTATEGPIO25 to GNDInternal pull-up is used
Button DROPGPIO26 to GNDInternal pull-up is used
Passive buzzer +GPIO27, minus to GNDSound effects

Code

The game keeps a ten by twenty grid in an array and draws it with the Adafruit ILI9341 library. Each of the seven pieces is stored as sixteen bits, one bit per square of a four by four box, so rotating is just a small loop that turns the box a quarter turn. Before any move the code asks valid() whether the new place is inside the walls and free of blocks, which is the whole secret of collision handling. When a piece lands it is copied into the grid, full rows are removed and the rows above fall. Every ten lines the level goes up and the drop gets faster. The best score is saved in the ESP32's flash with the Preferences library. Redrawing the whole board on every move is not the fastest method but is simple, and SPI at this size is quick enough. Install the Adafruit GFX Library and Adafruit ILI9341 from the Library Manager. Setup: Arduino IDE with the ESP32 boards package 2.0.x, board "ESP32 Dev Module". If the picture is mirrored, change setRotation. The Z and S pieces drift slightly when turned because there are no wall kicks; adding them is a good extension. The O piece does not rotate on purpose.

Runs on a virtual ESP32 Dev Module in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <Preferences.h>

#define TFT_CS 5
#define TFT_DC 16
#define TFT_RST 17
Adafruit_ILI9341 tft(TFT_CS, TFT_DC, TFT_RST);
Preferences prefs;

const int BTN_L = 32, BTN_R = 33, BTN_ROT = 25, BTN_DROP = 26, BUZ = 27;
const int W = 10, H = 20, CELL = 11, OX = 10, OY = 20;
const uint16_t COL[8] = {0x0000, 0x07FF, 0xFFE0, 0xF81F, 0x07E0, 0xF800, 0x001F, 0xFD20};
// Seven shapes as 4x4 bit masks, row 0 is the top nibble: I O T S Z J L
const uint16_t SHAPES[7] = {0x0F00, 0x6600, 0x4E00, 0x06C0, 0xC600, 0x8E00, 0x2E00};

uint8_t board[H][W];
uint16_t cur;
int curType, px, py, score, lvl, lineCount, hi;
bool over;
uint32_t lastDrop, lastMove;

int cellAt(uint16_t m, int r, int c) { return (m >> (15 - (r * 4 + c))) & 1; }

uint16_t rotateCW(uint16_t m) {
  uint16_t n = 0;
  for (int r = 0; r < 4; r++)
    for (int c = 0; c < 4; c++)
      if (cellAt(m, 3 - c, r)) n |= 1 << (15 - (r * 4 + c));
  return n;
}

bool valid(uint16_t m, int x, int y) {
  for (int r = 0; r < 4; r++)
    for (int c = 0; c < 4; c++)
      if (cellAt(m, r, c)) {
        int bx = x + c, by = y + r;
        if (bx < 0 || bx >= W || by >= H) return false;
        if (by >= 0 && board[by][bx]) return false;
      }
  return true;
}

void beep(int f, int ms) { ledcWriteTone(BUZ, f); delay(ms); ledcWriteTone(BUZ, 0); }

void drawCell(int x, int y, uint16_t colour) {
  tft.fillRect(OX + x * CELL, OY + y * CELL, CELL - 1, CELL - 1, colour);
}

void drawBoard() {
  for (int y = 0; y < H; y++)
    for (int x = 0; x < W; x++) drawCell(x, y, COL[board[y][x]]);
  for (int r = 0; r < 4; r++)
    for (int c = 0; c < 4; c++)
      if (cellAt(cur, r, c) && py + r >= 0) drawCell(px + c, py + r, COL[curType + 1]);
}

void drawScore() {
  tft.fillRect(130, 20, 100, 120, ILI9341_BLACK);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(2);
  tft.setCursor(130, 20);  tft.print("Score");
  tft.setCursor(130, 40);  tft.print(score);
  tft.setCursor(130, 70);  tft.print("Level");
  tft.setCursor(130, 90);  tft.print(lvl);
  tft.setCursor(130, 120); tft.print("Best ");
  tft.print(hi);
}

void spawn() {
  curType = esp_random() % 7;
  cur = SHAPES[curType];
  px = 3; py = 0;
  if (!valid(cur, px, py)) {
    over = true;
    if (score > hi) { hi = score; prefs.putInt("hi", hi); }
  }
}

void clearLines() {
  int cleared = 0;
  for (int y = H - 1; y >= 0; y--) {
    bool full = true;
    for (int x = 0; x < W; x++) if (!board[y][x]) full = false;
    if (full) {
      cleared++;
      for (int k = y; k > 0; k--) memcpy(board[k], board[k - 1], W);
      memset(board[0], 0, W);
      y++;  // check the same row again
    }
  }
  if (cleared) {
    static const int pts[5] = {0, 100, 300, 500, 800};
    score += pts[cleared] * (lvl + 1);
    lineCount += cleared;
    lvl = lineCount / 10;
    beep(1200, 80);
  }
}

void lockPiece() {
  for (int r = 0; r < 4; r++)
    for (int c = 0; c < 4; c++)
      if (cellAt(cur, r, c) && py + r >= 0) board[py + r][px + c] = curType + 1;
  clearLines();
  spawn();
}

void newGame() {
  memset(board, 0, sizeof(board));
  score = 0; lvl = 0; lineCount = 0; over = false;
  tft.fillScreen(ILI9341_BLACK);
  tft.drawRect(OX - 2, OY - 2, W * CELL + 3, H * CELL + 3, ILI9341_WHITE);
  spawn();
  drawScore();
  drawBoard();
  lastDrop = millis();
}

void setup() {
  pinMode(BTN_L, INPUT_PULLUP); pinMode(BTN_R, INPUT_PULLUP);
  pinMode(BTN_ROT, INPUT_PULLUP); pinMode(BTN_DROP, INPUT_PULLUP);
  ledcAttach(BUZ, 2000, 8);
  prefs.begin("tetris", false);
  hi = prefs.getInt("hi", 0);
  tft.begin();
  tft.setRotation(0);
  newGame();
}

void loop() {
  if (over) {
    tft.setTextColor(ILI9341_RED);
    tft.setTextSize(3);
    tft.setCursor(20, 120); tft.print("GAME OVER");
    beep(200, 300);
    while (digitalRead(BTN_DROP)) delay(10);
    newGame();
    return;
  }
  uint32_t now = millis();
  bool changed = false;
  if (now - lastMove > 120) {
    if (!digitalRead(BTN_L) && valid(cur, px - 1, py)) { px--; changed = true; lastMove = now; }
    if (!digitalRead(BTN_R) && valid(cur, px + 1, py)) { px++; changed = true; lastMove = now; }
    if (!digitalRead(BTN_ROT) && curType != 1) {
      uint16_t r = rotateCW(cur);
      if (valid(r, px, py)) { cur = r; changed = true; beep(800, 15); }
      lastMove = now + 100;  // a longer pause so one press turns once
    }
    if (!digitalRead(BTN_DROP) && valid(cur, px, py + 1)) { py++; changed = true; lastMove = now; }
  }
  uint32_t interval = max(100, 600 - lvl * 50);
  if (now - lastDrop > interval) {
    lastDrop = now;
    if (valid(cur, px, py + 1)) py++;
    else { lockPiece(); drawScore(); }
    changed = true;
  }
  if (changed) drawBoard();
}

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Power onEmpty box with the first piece falling
Hold LEFT at the wallPiece stops, does not leave the box
Press ROTATE next to a wallPiece does not turn through the wall
Complete a rowRow disappears and score rises
Lose a game, then restartBest score kept
Unplug and plug inBest score still shown

If it does not work

White screen

Check CS, DC, RESET pins match the code and the backlight pin is on 3V3.

Picture upside down

Change setRotation to 2.

Flicker

Normal while redrawing the whole board; reduce by drawing only changed cells.

Pieces drift when rotated

Expected without wall kicks.

Buzzer silent

A passive buzzer is needed, and this needs core 2.0.x for ledcWriteTone.

Random sequence repeats

esp_random is used and should vary each time.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the tetris on a colour screen?

ESP32 DevKit V1, 2.8 inch TFT touch (ILI9341, SPI), Tactile push button 6 mm × 4, Passive buzzer, Breadboard 830 Tie Points and Jumper wires male to male (40 pcs, 20 cm).

How long does the tetris on a colour screen take to build?

About 240 minutes for a intermediate maker, in 8 steps.

How do I know the tetris on a colour screen works?

Power on: Empty box with the first piece falling. Hold LEFT at the wall: Piece stops, does not leave the box. Press ROTATE next to a wall: Piece does not turn through the wall.

White screen: what should I check?

Check CS, DC, RESET pins match the code and the backlight pin is on 3V3.

Picture upside down: what should I check?

Change setRotation to 2.

Flicker: what should I check?

Normal while redrawing the whole board; reduce by drawing only changed cells.

Pieces drift when rotated: what should I check?

Expected without wall kicks.