Community project

Consola GAME YISUS

Photo of Consola GAME YISUS

jesusdavidnunezespinet42

Last updated November 28, 2026

Consola GAME YISUS is a handheld gaming device built around the ESP32 microcontroller, featuring a 128x64 pixel SSD1306 OLED display for crisp graphics and a PS2 joystick module for responsive controls. A piezo buzzer adds audio feedback to enhance the gaming experience.

This guide provides everything needed to assemble the console from scratch, including a complete wiring diagram showing how to connect the display, joystick, and buzzer to the ESP32, a full parts list with component specifications, custom firmware with a fixed framebuffer display driver, and step-by-step assembly instructions that walk through power management, component connection, and system verification.

Wiring diagram

Wiring diagram for Consola GAME YISUS
Loading diagram…

Gather all the parts

QtyComponent
1

SSD1306 OLED

0.96-inch 128 x 64 white monochrome OLED display module driven by an SSD1306 controller over I2C (address 0x3C). It runs from 3 V to 5 V and connects through a 4-pin 2.54 mm header (GND, VCC, SCL, SDA); the self-emitting pixels need no backlight.

1

PS2 Joystick Module (KY-023)

Two-axis analog thumb joystick module (KY-023 / PS2 style) with a push switch under the stick. Two 10 kOhm potentiometers give X and Y voltages that sit near half the supply at rest, and pressing the stick operates a digital switch. It runs from 3.3 to 5 V and connects through a five-pin GND, +5V, VRx, VRy, SW right-angle header.

1

Piezo Buzzer

Small passive piezo buzzer (TDK PS1240) for beeps, tones and alerts. It has no built-in oscillator, so drive one lead with a 3-30 V square wave from a microcontroller pin using tone() or PWM and connect the other lead to ground. It is loudest around 4 kHz and works from about 2 to 10 kHz; driving both leads in antiphase roughly doubles the volume.

1

Resistor

220 ohm

Through-hole resistor (current-limiting in series with an LED)

Assemble it in 5 steps

1. Desconecta la alimentación

Usa un ESP32 DevKit v1 clásico. Desenchufa el USB antes de conectar los módulos. Este montaje no utiliza el Uno ni el adaptador de niveles.

2. Conecta la pantalla

Conecta VCC a 3V3, GND a GND, SDA a GPIO21 (datos) y SCL a GPIO22 (reloj). Sigue las etiquetas de la pantalla, no el orden físico.

  • Invertir VCC y GND puede dañar la pantalla.

3. Conecta el joystick

Conecta el pin marcado +5V a 3V3, GND a GND, VRX a GPIO32 (horizontal), VRY a GPIO33 (vertical) y SW a GPIO27 (botón). El módulo funciona a 3.3 V aunque su etiqueta diga +5V.

  • No alimentes el joystick a 5 V; sus salidas podrían dañar las entradas del ESP32.

4. Revisa el montaje

Comprueba que ambos módulos comparten GND y reciben 3.3 V. Deja el joystick centrado al encender para calibrar los controles.

5. Añade el sonido

Con el USB desconectado, conecta GPIO25 a una resistencia de 220 ohmios, su otro extremo al positivo SIG del buzzer piezoeléctrico pasivo y el negativo del buzzer a GND. Alimenta la consola mediante el USB del ESP32 y pulsa Deploy para cargar el firmware. El menú y los seis juegos tendrán efectos de sonido.

  • Usa un buzzer piezoeléctrico pasivo, no un altavoz ni un buzzer magnético. No conectes 5 V al GPIO25.

Review all connections

1. Connections between "oled" and "ESP32"

FunctionoledESP32
powerVCC3V3
groundGNDGND
i2cSDAGPIO 21
i2cSCLGPIO 22

2. Connections between "joystick" and "ESP32"

FunctionjoystickESP32
power+5V3V3
groundGNDGND
analogVRXGPIO 32
analogVRYGPIO 33
digitalSWGPIO 27

3. Connections between "sound_resistor" and "ESP32"

Functionsound_resistorESP32
digitalP1GPIO 25
digitalP2 → Piezo Buzzer SIGEXT

4. Connections between "buzzer" and "ESP32"

FunctionbuzzerESP32
groundGNDGND

Deploy the firmware

#include <Arduino.h>
#include <Wire.h>
#include <Preferences.h>
#include <pgmspace.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
// SSD1306 driver: fixed framebuffer, no external libraries.
#define SSD1306_WHITE 1
#define SSD1306_SWITCHCAPVCC 2
class OLED : public Print {
 uint8_t buffer[1024]; int cursorX=0,cursorY=0; uint8_t address=0x3C;
 void command(uint8_t c){Wire.beginTransmission(address);Wire.write(0x00);Wire.write(c);Wire.endTransmission();}
 public:
 bool begin(uint8_t, uint8_t addr){
  address=addr;Wire.begin(21,22);Wire.setClock(400000);Wire.beginTransmission(address);
  if(Wire.endTransmission()!=0)return false;
  const uint8_t init[]={0xAE,0xD5,0x80,0xA8,0x3F,0xD3,0x00,0x40,0x8D,0x14,0x20,0x00,0xA1,0xC8,0xDA,0x12,0x81,0xCF,0xD9,0xF1,0xDB,0x40,0xA4,0xA6,0x2E};
  for(uint8_t c:init)command(c);
  clearDisplay();display();command(0xAF);return true;
 }
 void clearDisplay(){memset(buffer,0,sizeof(buffer));}
 void setTextSize(uint8_t){} void setTextColor(uint8_t){}
 void setCursor(int x,int y){cursorX=x;cursorY=y;}
 void pixel(int x,int y){if(x>=0&&x<128&&y>=0&&y<64)buffer[x+(y/8)*128]|=1<<(y&7);}
 void drawLine(int x,int y,int xx,int yy,uint8_t){int dx=abs(xx-x),sx=x<xx?1:-1,dy=-abs(yy-y),sy=y<yy?1:-1,err=dx+dy;for(;;){pixel(x,y);if(x==xx&&y==yy)break;int e=2*err;if(e>=dy){err+=dy;x+=sx;}if(e<=dx){err+=dx;y+=sy;}}}
 void fillRect(int x,int y,int w,int h,uint8_t color){for(int j=y;j<y+h;j++)for(int i=x;i<x+w;i++){if(color)pixel(i,j);else if(i>=0&&i<128&&j>=0&&j<64)buffer[i+(j/8)*128]&=~(1<<(j&7));}}
 void drawRect(int x,int y,int w,int h,uint8_t c){drawLine(x,y,x+w-1,y,c);drawLine(x,y+h-1,x+w-1,y+h-1,c);drawLine(x,y,x,y+h-1,c);drawLine(x+w-1,y,x+w-1,y+h-1,c);}
 void fillCircle(int x,int y,int r,uint8_t){for(int j=-r;j<=r;j++)for(int i=-r;i<=r;i++)if(i*i+j*j<=r*r)pixel(x+i,y+j);}
 void drawCircle(int x,int y,int r,uint8_t){for(int j=-r;j<=r;j++)for(int i=-r;i<=r;i++){int d=i*i+j*j;if(d<=r*r&&d>=(r-1)*(r-1))pixel(x+i,y+j);}}
 size_t write(uint8_t c) override {
  // Original compact 3x5 alphabet. Lowercase is displayed as uppercase.
  static const uint16_t glyphs[] PROGMEM={
   0b010101111101101,0b110101110101110,0b011100100100011,
   0b110101101101110,0b111100110100111,0b111100110100100,
   0b011100101101011,0b101101111101101,0b111010010010111,
   0b001001001101010,0b101101110101101,0b100100100100111,
   0b101111111101101,0b101111111111101,0b010101101101010,
   0b110101110100100,0b010101101111011,0b110101110101101,
   0b011100010001110,0b111010010010010,0b101101101101111,
   0b101101101101010,0b101101111111101,0b101101010101101,
   0b101101010010010,0b111001010100111,
   0b111101101101111,0b010110010010111,0b110001010100111,
   0b110001010001110,0b101101111001001,0b111100110001110,
   0b011100110101010,0b111001010010010,0b010101010101010,
   0b010101011001110};
  if(c=='\n'){cursorX=0;cursorY+=8;return 1;}
  if(c>='a'&&c<='z')c-=32;
  uint16_t bits=0;
  if(c>='A'&&c<='Z')bits=pgm_read_word(glyphs+c-'A');
  else if(c>='0'&&c<='9')bits=pgm_read_word(glyphs+26+c-'0');
  else if(c=='>')bits=0b100010001010100;
  else if(c==':')bits=0b000010000010000;
  else if(c=='!')bits=0b010010010000010;
  else if(c=='-')bits=0b000000111000000;
  else if(c=='%')bits=0b101001010100101;
  for(int y=0;y<5;y++)for(int x=0;x<3;x++)if(bits&(1U<<(14-y*3-x)))pixel(cursorX+x,cursorY+y+1);
  cursorX+=6;return 1;
 }
 void display(){command(0x21);command(0);command(127);command(0x22);command(0);command(7);
  for(uint16_t i=0;i<1024;){Wire.beginTransmission(address);Wire.write(0x40);for(uint8_t n=0;n<16;n++)Wire.write(buffer[i++]);Wire.endTransmission();}
 }
};
OLED screen;
const uint8_t BUTTON=27;
const uint8_t BUZZER=25;
struct ButtonEvent { bool down; unsigned long at; };
QueueHandle_t buttonEvents;
// Sample independently of the OLED transfers, including during redraws.
void sampleButton(void *) {
 bool stable=digitalRead(BUTTON)==LOW, candidate=stable;
 unsigned long since=millis();
 for(;;){
  bool reading=digitalRead(BUTTON)==LOW;
  unsigned long now=millis();
  if(reading!=candidate){candidate=reading;since=now;}
  if(candidate!=stable && now-since>=15){
   stable=candidate; ButtonEvent event={stable,now};
   xQueueSend(buttonEvents,&event,portMAX_DELAY);
  }
  vTaskDelay(pdMS_TO_TICKS(2));
 }
}
unsigned long effectUntil=0;
void beep(unsigned int hz=4000,unsigned long duration=60){
 effectUntil=millis()+duration;
 tone(BUZZER,hz,duration);
}
int cx=2048,cy=2048;
bool ready=false,rawOld=false,held=false,longDone=false,dirty=true;
unsigned long changed=0,downAt=0,tickAt=0,navAt=0;
// mode: menu, playing, result, idle. Shared game storage keeps RAM usage low.
const uint8_t GAME_COUNT=6;
uint8_t mode=0,game=0,menuSelection=0,rankSelection=0;
uint32_t rankPoints=0,earnedPoints=0;
bool rewarded=false,rankSaveError=false;
uint8_t rankChoice=0;
bool reachedTop=false;
const uint8_t RANK_COUNT=14;
const char *rankNames[RANK_COUNT]={"NOVATO 1","NOVATO 2","NOVATO 3","PRINCIPIANTE 1","PRINCIPIANTE 2","PRINCIPIANTE 3","PROFESIONAL 1","PROFESIONAL 2","PROFESIONAL 3","PROFESIONAL 4","SUPER PROFESIONAL 1","SUPER PROFESIONAL 2","DIOS SUPREMO","EL MEJOR JUGADOR"};
// Cost to enter each rank, not a lifetime-total threshold.
const uint16_t rankCosts[RANK_COUNT]={0,1000,1000,2000,2000,2000,4000,4000,4000,4000,2500,2500,10000,10999};
uint32_t rankThreshold(uint8_t index){uint32_t n=0;for(uint8_t i=1;i<=index;i++)n+=rankCosts[i];return n;}
uint8_t currentRank(){uint8_t r=0;while(r+1<RANK_COUNT&&rankPoints>=rankThreshold(r+1))r++;return r;}
Preferences recordsStore;
bool recordsReady=false,newRecord=false;
uint32_t records[GAME_COUNT][3]={};
void loadRecords(){
 recordsReady=recordsStore.begin("yisus-records",false);
 if(!recordsReady){Serial.println("No se pudo abrir memoria de records");return;}
 rankPoints=recordsStore.getUInt("rank-points",0);
 for(uint8_t g=0;g<GAME_COUNT;g++)for(uint8_t d=0;d<3;d++){
  char key[12];snprintf(key,sizeof(key),g==1?"tetris-d%u":(g==2?"pacman-d%u":(g==5?"snake-d%u":"g%u-d%u")),(g==1||g==2||g==5)?d:g,d);
  records[g][d]=recordsStore.getUInt(key,0);
 }
}
uint8_t difficulty=1; // Easy, normal, hard.
const unsigned long gameInterval[]={75,50,30};
void difficultyName(){switch(difficulty){case 0:screen.print(F("FACIL"));break;case 1:screen.print(F("NORMAL"));break;default:screen.print(F("DIFICIL"));break;}}
void chooseDifficulty(){mode=4;navAt=millis();dirty=true;beep(4000,60);}
unsigned long menuActivityAt=0;
int obstacleX=128, obstacleY=30;

bool paused=false;
uint8_t pauseClicks=0;
unsigned long lastPauseClick=0;
int score=0,px=60,bx=64,by=32,vx=2,vy=2,enemy=26;
uint32_t bricks=0;
uint8_t brickLevel=1,brickIntro=0;
const uint8_t BRICK_LEVELS=5;
// Twenty possible bricks: five columns by four rows.
const uint32_t brickLayouts[BRICK_LEVELS]={
 0x07FFFUL, // Three full rows.
 0xFFFFFUL, // Four full rows.
 0xAD6B5UL, // Alternating columns.
 0xFBAEFUL, // Openings in the middle rows.
 0xFFFFFUL  // Final full wall at maximum speed.
};
// Offset from paddle centre controls the outgoing direction.
// A small centre zone gives a straight shot; edges give a wider angle.
int paddleDeflection(int offset,int halfLength,int speed){
 int distance=abs(offset);
 if(distance<=halfLength/4)return 0;
 int lateral=distance<=halfLength*2/3?max(1,speed-1):speed;
 return offset<0?-lateral:lateral;
}
// Independent streaks for Pong's two paddles and the brick paddle.
int8_t lastHitZone[3]={-1,-1,-1};
uint8_t sameZoneHits[3]={0,0,0};
bool centreEscapePositive[3]={true,true,true};
void resetBounceStreaks(){
 for(uint8_t i=0;i<3;i++){lastHitZone[i]=-1;sameZoneHits[i]=0;centreEscapePositive[i]=true;}
}
int variedPaddleDeflection(int offset,int halfLength,int speed,uint8_t paddle){
 int zone=offset < -halfLength/3 ? 0 : (offset > halfLength/3 ? 2 : 1);
 if(lastHitZone[paddle]==zone)sameZoneHits[paddle]++;
 else {lastHitZone[paddle]=zone;sameZoneHits[paddle]=1;}
 int direction=paddleDeflection(offset,halfLength,speed);
 if(sameZoneHits[paddle]>=3){
  sameZoneHits[paddle]=0;
  // Third hit escapes the repeated zone; middle alternates either side.
  if(zone==0)direction=speed;
  else if(zone==2)direction=-speed;
  else {direction=centreEscapePositive[paddle]?speed:-speed;centreEscapePositive[paddle]=!centreEscapePositive[paddle];}
 }
 return direction;
}
int brickSpeed(){return brickLevel>=3?3:2;}
void loadBrickLevel(){
 resetBounceStreaks();bricks=brickLayouts[brickLevel-1];px=53;bx=64;by=48;
 vx=brickSpeed();vy=-brickSpeed();brickIntro=25;dirty=true;
}
bool won=false;
// Sample independently from the blocking OLED transfers.
struct DirectionEvent { int x,y; };
QueueHandle_t directionEvents;
volatile int inputX=0,inputY=0;
int normalizedAxis(int raw,int center){
 int delta=raw-center;
 int span=delta>=0?4095-center:center;
 return -(delta*1000/max(span,1));
}
void sampleJoystick(void *){
 int previousX=0,previousY=0;
 for(;;){
  int ax=0,ay=0;
  for(int i=0;i<4;i++){ax+=analogRead(32);ay+=analogRead(33);}
  // Physical directions reported: up=old X+, right=old Y+.
  // Map to screen coordinates: right=X+, down=Y+.
  int physicalVertical=normalizedAxis(ax/4,cx);
  int physicalHorizontal=normalizedAxis(ay/4,cy);
  ax=physicalHorizontal;ay=-physicalVertical;
  int mx=abs(ax),my=abs(ay),x=0,y=0;
  bool horizontal=mx>=my;
  if(previousX && mx+80>=my)horizontal=true;
  if(previousY && my+80>=mx)horizontal=false;
  int strength=horizontal?mx:my;
  int threshold=(previousX||previousY)?180:300;
  if(strength>=threshold){
   if(horizontal)x=ax>0?1:-1;else y=ay>0?1:-1;
  }
  inputX=x;inputY=y;
  if(x!=previousX||y!=previousY){
   DirectionEvent event={x,y};xQueueSend(directionEvents,&event,0);
   previousX=x;previousY=y;
  }
  vTaskDelay(pdMS_TO_TICKS(5));
 }
}
void readJoystick(int &x,int &y){x=inputX;y=inputY;}
void text(int x,int y,const __FlashStringHelper *s){screen.setCursor(x,y);screen.print(s);}
void name(uint8_t n){switch(n){case 0:screen.print(F("Pong"));break;case 1:screen.print(F("Tetris"));break;case 2:screen.print(F("Pac-Man"));break;case 3:screen.print(F("Rompeladrillos"));break;case 4:screen.print(F("Carreras"));break;case 5:screen.print(F("Culebrita"));break;}}
void saveRecord(){
 if(score<=0 || uint32_t(score)<=records[game][difficulty])return;
 records[game][difficulty]=score;newRecord=true;
 if(recordsReady){
  char key[12];snprintf(key,sizeof(key),game==1?"tetris-d%u":(game==2?"pacman-d%u":(game==5?"snake-d%u":"g%u-d%u")),(game==1||game==2||game==5)?difficulty:game,difficulty);
  if(recordsStore.putUInt(key,score)!=4)Serial.println("Error al guardar record");
 }
}
void rewardMatch(bool victory){
 (void)victory;
 if(rewarded)return;rewarded=true;earnedPoints=0;rankSaveError=false;
 if(score<=0)return;
 uint8_t previousRank=currentRank();
 uint32_t gain=uint32_t(score);
 uint32_t next=rankPoints>UINT32_MAX-gain?UINT32_MAX:rankPoints+gain;
 if(recordsReady&&recordsStore.putUInt("rank-points",next)==4){earnedPoints=next-rankPoints;rankPoints=next;reachedTop=previousRank<RANK_COUNT-1&&currentRank()==RANK_COUNT-1;}
 else {rankSaveError=true;Serial.println("Error al guardar puntos de rango");}
}
void endGame(bool victory=false){if(mode!=1)return;rewardMatch(victory);saveRecord();beep(victory?5000:2000,300);mode=reachedTop?6:2;rankChoice=0;reachedTop=false;won=victory;dirty=true;}
// Tetris: 10 columns, 16 rows, seven tetrominoes.
uint16_t field[16]={};
const uint16_t shapes[7]={0x00F0,0x0066,0x0072,0x0036,0x0063,0x0071,0x0074};
int pieceX=3,pieceY=0;
uint8_t pieceType=0,pieceRotation=0;
int lastTetrisX=0,lastTetrisY=0;
unsigned long fallAt=0,moveAt=0;
bool pieceCell(int x,int y,int rotation){
 for(int i=0;i<rotation;i++){int old=x;x=y;y=3-old;}
 return shapes[pieceType]&(1U<<(y*4+x));
}
bool fitsPiece(int xx,int yy,int rr){
 for(int y=0;y<4;y++)for(int x=0;x<4;x++)if(pieceCell(x,y,rr)){
  int fx=xx+x,fy=yy+y;
  if(fx<0||fx>=10||fy>=16)return false;
  if(fy>=0&&(field[fy]&(1U<<fx)))return false;
 }
 return true;
}
void spawnPiece(){pieceType=random(7);pieceRotation=0;pieceX=3;pieceY=0;fallAt=millis();if(!fitsPiece(pieceX,pieceY,0))endGame();}
void startTetris(){memset(field,0,sizeof(field));lastTetrisX=lastTetrisY=0;moveAt=millis();spawnPiece();}
void lockPiece(){
 for(int y=0;y<4;y++)for(int x=0;x<4;x++)if(pieceCell(x,y,pieceRotation)){
  int fy=pieceY+y;if(fy<0){endGame();return;}field[fy]|=1U<<(pieceX+x);
 }
 int lines=0;
 for(int y=15;y>=0;y--)if(field[y]==0x3FF){
  for(int row=y;row>0;row--)field[row]=field[row-1];field[0]=0;lines++;y++;
 }
 if(lines){score+=lines*lines*100;beep(5000,100);}else beep(3000,25);
 spawnPiece();
}
void updateTetris(int x,int y){
 unsigned long now=millis();
 if(x&&(x!=lastTetrisX||now-moveAt>=140)){
  if(fitsPiece(pieceX+x,pieceY,pieceRotation))pieceX+=x;moveAt=now;
 }
 if(y<0&&lastTetrisY>=0){
  int rr=(pieceRotation+1)%4;
  if(fitsPiece(pieceX,pieceY,rr))pieceRotation=rr;
  else if(fitsPiece(pieceX-1,pieceY,rr)){pieceX--;pieceRotation=rr;}
  else if(fitsPiece(pieceX+1,pieceY,rr)){pieceX++;pieceRotation=rr;}
 }
 lastTetrisX=x;lastTetrisY=y;
 const unsigned long speeds[3]={700,450,250};
 if(now-fallAt>=(y>0?55UL:speeds[difficulty])){
  fallAt=now;if(fitsPiece(pieceX,pieceY+1,pieceRotation))pieceY++;else lockPiece();
 }
}
void drawTetris(){
 screen.drawRect(46,12,32,50,1);
 for(int y=0;y<16;y++)for(int x=0;x<10;x++)if(field[y]&(1U<<x))screen.fillRect(47+x*3,13+y*3,2,2,1);
 for(int y=0;y<4;y++)for(int x=0;x<4;x++)if(pieceCell(x,y,pieceRotation)&&pieceY+y>=0)screen.fillRect(47+(pieceX+x)*3,13+(pieceY+y)*3,2,2,1);
 text(0,20,F("ARRIBA"));text(0,29,F("GIRAR"));text(84,20,F("ABAJO"));text(84,29,F("BAJAR"));
}
// Compact maze chase: each tile is 6 pixels, with separate persistent records.
const char pacMaze[8][22]={
 "#####################",
 "#.........#.........#",
 "#.###.###.#.###.###.#",
 "#...................#",
 "#.###.#.#####.#.###.#",
 "#.....#...#...#.....#",
 "#.........#.........#",
 "#####################",
};
uint32_t pacDots[8];
int pacX=1,pacY=1,pacDX=0,pacDY=0,pacWantedX=0,pacWantedY=0;
int ghostX[2],ghostY[2],pacLives=3,pacRemaining=0;
unsigned int pacSteps=0,pacPower=0,pacSafe=0;
bool pacOpen(int x,int y){return x>=0&&x<21&&y>=0&&y<8&&pacMaze[y][x]!='#';}
void pacPositions(){pacX=1;pacY=1;pacDX=pacDY=pacWantedX=pacWantedY=0;ghostX[0]=19;ghostY[0]=6;ghostX[1]=19;ghostY[1]=1;pacSafe=25;}
void startPac(){
 pacLives=3;pacRemaining=0;pacSteps=pacPower=0;pacPositions();
 for(int y=0;y<8;y++){pacDots[y]=0;for(int x=0;x<21;x++)if(pacOpen(x,y)){pacDots[y]|=1UL<<x;pacRemaining++;}}
}
void pacCollision(){
 for(int i=0;i<2;i++)if(pacX==ghostX[i]&&pacY==ghostY[i]){
  if(pacPower){score+=50;ghostX[i]=19;ghostY[i]=i?1:6;beep(5000,80);}
  else if(!pacSafe){pacLives--;beep(2000,150);if(!pacLives)endGame();else pacPositions();return;}
 }
}
void updatePac(int x,int y){
 // Tick counters freeze naturally when the game is paused.

 if(pacPower)pacPower--;if(pacSafe)pacSafe--;
 if(++pacSteps%3)return;
 if(pacOpen(pacX+pacWantedX,pacY+pacWantedY)){pacDX=pacWantedX;pacDY=pacWantedY;}
 if(pacOpen(pacX+pacDX,pacY+pacDY)){pacX+=pacDX;pacY+=pacDY;}
 if(pacDots[pacY]&(1UL<<pacX)){
  pacDots[pacY]&=~(1UL<<pacX);pacRemaining--;score+=10;
  if((pacX==1||pacX==19)&&(pacY==1||pacY==6)){pacPower=120;beep(5500,120);}
 }
 pacCollision();if(mode!=1)return;
 if(!pacRemaining){endGame(true);return;}
 if(pacSteps%(difficulty==2?3:6)==0){
  const int dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
  // Breadth-first distances follow corridors, not straight lines through walls.
  int16_t distance[8][21];
  uint8_t queue[168];
  int head=0,tail=0;
  for(int row=0;row<8;row++)for(int col=0;col<21;col++)distance[row][col]=-1;
  distance[pacY][pacX]=0;
  queue[tail++]=pacY*21+pacX;
  while(head<tail){
   int cell=queue[head++],cx=cell%21,cy=cell/21;
   for(int d=0;d<4;d++){
    int nx=cx+dx[d],ny=cy+dy[d];
    if(pacOpen(nx,ny)&&distance[ny][nx]<0){
     distance[ny][nx]=distance[cy][cx]+1;
     queue[tail++]=ny*21+nx;
    }
   }
  }
  for(int i=0;i<2;i++){
   int best=-1,bestValue=-10000;
   for(int d=0;d<4;d++){
    int nx=ghostX[i]+dx[d],ny=ghostY[i]+dy[d];
    if(!pacOpen(nx,ny)||distance[ny][nx]<0)continue;
    int value=pacPower?distance[ny][nx]:-distance[ny][nx];
    if(value>bestValue){bestValue=value;best=d;}
   }
   if(best>=0){ghostX[i]+=dx[best];ghostY[i]+=dy[best];}
  }
 }
 pacCollision();
}
void drawPac(){
 for(int y=0;y<8;y++)for(int x=0;x<21;x++){
  int xx=1+x*6,yy=16+y*6;
  if(!pacOpen(x,y))screen.drawRect(xx,yy,6,6,1);
  else if(pacDots[y]&(1UL<<x)){
   if((x==1||x==19)&&(y==1||y==6))screen.fillCircle(xx+3,yy+3,1,1);
   else screen.pixel(xx+3,yy+3);
  }
 }
 int xx=4+pacX*6,yy=19+pacY*6;
 screen.fillCircle(xx,yy,2,1);
 if(pacSteps%6<3){int dx=pacDX,dy=pacDY;if(!dx&&!dy)dx=1;screen.fillRect(xx+dx,yy+dy,1,1,0);screen.fillRect(xx+2*dx,yy+2*dy,1,1,0);}
 for(int i=0;i<2;i++){int gx=2+ghostX[i]*6,gy=17+ghostY[i]*6;
  if(pacPower)screen.drawRect(gx,gy,4,4,1);else{screen.fillRect(gx,gy,4,4,1);screen.fillRect(gx+1,gy+1,1,1,0);screen.fillRect(gx+3,gy+1,1,1,0);}
 }
 screen.setCursor(0,10);screen.print(F("VIDAS "));screen.print(pacLives);
}

// Snake: 32 by 13 cells, four pixels per cell.
uint8_t snakeX[416],snakeY[416],foodX,foodY;
uint16_t snakeLength=4;
int snakeDX=1,snakeDY=0,snakeWantedX=1,snakeWantedY=0;
unsigned long snakeAt=0;
bool snakeTurnQueued=false;
bool snakeContains(int x,int y,int length){
 for(int i=0;i<length;i++)if(snakeX[i]==x&&snakeY[i]==y)return true;
 return false;
}
void snakeFood(){
 int freeCells=416-snakeLength;
 if(!freeCells){endGame(true);return;}
 int chosen=random(freeCells);
 for(int y=0;y<13;y++)for(int x=0;x<32;x++)if(!snakeContains(x,y,snakeLength)){
  if(chosen--==0){foodX=x;foodY=y;return;}
 }
}
void startSnake(){
 snakeLength=4;snakeDX=snakeWantedX=1;snakeDY=snakeWantedY=0;
 for(int i=0;i<4;i++){snakeX[i]=8-i;snakeY[i]=6;}
 snakeAt=millis();snakeFood();
}
void updateSnake(int x,int y){
 // Input is queued separately at every loop, not just at simulation ticks.
 const unsigned long speeds[3]={200,140,90};
 if(millis()-snakeAt<speeds[difficulty])return;
 snakeAt=millis();snakeDX=snakeWantedX;snakeDY=snakeWantedY;snakeTurnQueued=false;
 int nx=snakeX[0]+snakeDX,ny=snakeY[0]+snakeDY;
 bool eating=nx==foodX&&ny==foodY;
 if(nx<0||nx>=32||ny<0||ny>=13||snakeContains(nx,ny,snakeLength-(eating?0:1))){endGame();return;}
 if(eating)snakeLength++;
 for(int i=snakeLength-1;i>0;i--){snakeX[i]=snakeX[i-1];snakeY[i]=snakeY[i-1];}
 snakeX[0]=nx;snakeY[0]=ny;
 if(eating){score+=10;snakeFood();}
}
void drawSnake(){
 for(int i=0;i<snakeLength;i++)screen.fillRect(snakeX[i]*4,12+snakeY[i]*4,3,3,1);
 screen.drawRect(foodX*4,12+foodY*4,4,4,1);
}
void startGame(){resetBounceStreaks();rewarded=false;earnedPoints=0;beep(4500,120);mode=1;newRecord=false;paused=false;pauseClicks=0;score=0;px=30;bx=64;by=35;vx=2;vy=-2;enemy=26;if(game==3){brickLevel=1;loadBrickLevel();}if(game==2)startPac();if(game==1)startTetris();obstacleX=128;obstacleY=random(16,51);if(game==5){startSnake();snakeTurnQueued=false;}if(game>=4)px=30;tickAt=millis();dirty=true;}
void draw(){screen.clearDisplay();screen.setTextSize(1);screen.setTextColor(SSD1306_WHITE);
 if(mode==0){screen.setCursor(0,0);screen.print(rankNames[currentRank()]);uint8_t first=menuSelection<5?0:menuSelection-4;for(uint8_t row=0;row<5;row++){uint8_t i=first+row;screen.setCursor(0,12+row*10);screen.print(i==menuSelection?'>':' ');if(i==GAME_COUNT)screen.print(F("RANGOS"));else name(i);} }
 else if(mode==5){
  uint8_t r=currentRank();
  text(0,0,F("RANGO ACTUAL"));screen.setCursor(0,10);screen.print(rankNames[r]);
  text(0,21,F("TOTAL: "));screen.print(rankPoints);
  if(r+1<RANK_COUNT){text(0,31,F("PROGRESO: "));screen.print(rankPoints-rankThreshold(r));screen.print('/');screen.print(rankCosts[r+1]);}
  else text(0,31,F("RANGO MAXIMO"));
  screen.setCursor(0,42);screen.print(rankNames[rankSelection]);
  text(0,52,F("COSTE: "));screen.print(rankCosts[rankSelection]);
 }
 else if(mode==6||mode==7){
  text(0,0,F("EL MEJOR JUGADOR"));
  text(0,12,mode==7?F("REINICIAR RANGOS?"):F("QUE QUIERES HACER?"));
  screen.setCursor(0,27);screen.print(rankChoice==0?'>':' ');screen.print(mode==7?F("CANCELAR"):F("SEGUIR JUGANDO"));
  screen.setCursor(0,39);screen.print(rankChoice==1?'>':' ');screen.print(mode==7?F("SI, REINICIAR"):F("REINICIAR RANGOS"));
  text(0,53,rankSaveError?F("ERROR AL GUARDAR"):F("PULSA PARA ELEGIR"));
 }
 else if(mode==4){screen.setCursor(0,0);name(game);text(0,14,F("DIFICULTAD"));for(uint8_t i=0;i<3;i++){screen.setCursor(12,26+i*9);screen.print(i==difficulty?'>':' ');screen.print(i==0?F("FACIL"):(i==1?F("NORMAL"):F("DIFICIL")));screen.setCursor(68,26+i*9);screen.print(records[game][i]);}text(0,56,F("PULSA PARA EMPEZAR"));}
 else if(mode==3){text(37,22,F("TE ESPERO"));text(19,40,F("PULSA PARA JUGAR"));}
 else if(mode==2){text(0,4,won?F("Ganaste!"):F("Fin del juego"));text(0,15,F("Puntos: "));screen.print(score);text(0,24,rankSaveError?F("ERROR GUARDAR RANGO"):F("RANGO +"));if(!rankSaveError)screen.print(earnedPoints);text(0,33,newRecord?F("NUEVO RECORD: "):F("RECORD: "));screen.print(records[game][difficulty]);text(0,44,F("Pulsa: nivel"));text(0,54,F("Mantener: menu"));}
 else {screen.setCursor(0,0);name(game);screen.setCursor(100,0);screen.print(score);screen.drawLine(0,10,127,10,SSD1306_WHITE);
 if(game==0){screen.fillRect(2,px,3,14,SSD1306_WHITE);screen.fillRect(123,enemy,3,14,SSD1306_WHITE);screen.fillCircle(bx,by,2,SSD1306_WHITE);}
 if(game==1)drawTetris();
 if(game==2)drawPac();
 if(game==3){
  screen.setCursor(80,0);screen.print('L');screen.print(brickLevel);
  for(uint8_t i=0;i<20;i++)if(bricks&(1UL<<i))screen.drawRect((i%5)*25+2,13+(i/5)*7,23,5,SSD1306_WHITE);
  screen.fillRect(px,59,22,3,SSD1306_WHITE);screen.fillCircle(bx,by,2,SSD1306_WHITE);
  if(brickIntro){screen.fillRect(26,43,78,10,0);text(32,44,F("NIVEL "));screen.print(brickLevel);}
 }
 if(game==4){screen.drawLine(0,14,127,14,1);screen.drawLine(0,62,127,62,1);screen.drawRect(12,px,12,8,1);screen.fillRect(obstacleX,obstacleY,12,8,1);}
 if(game==5)drawSnake();
 }
 if(mode==1&&!paused&&pauseClicks){screen.fillRect(94,0,34,9,0);screen.setCursor(100,0);screen.print(pauseClicks);screen.print(F("/3"));}
 if(mode==1&&paused){screen.fillRect(14,22,100,26,0);text(46,24,F("PAUSA"));text(19,38,F("Pulsa: continuar"));}
 screen.display();dirty=false;}
void updateGame(int x,int y){
 int previousScore=score;
 if(game==0){px=constrain(px+y*5,12,49);enemy=constrain(enemy+(by>enemy+7?2:-2),12,49);bx+=vx;by+=vy;if(by<=13||by>=61){by=constrain(by,13,61);vy=-vy;beep(3000,30);}if(vx<0&&bx<=7&&bx>=3&&by>=px-2&&by<=px+16){vx=2;vy=variedPaddleDeflection(by-(px+7),7,2,0);bx=7;score+=(score>=100?5:1);}if(vx>0&&bx>=120&&by>=enemy-2&&by<=enemy+16){vx=-2;vy=variedPaddleDeflection(by-(enemy+7),7,2,1);bx=120;beep(3500,40);}if(bx<0)endGame();if(bx>127){score+=(score>=100?25:5);bx=64;by=35;vx=-2;}}
 else if(game==1){updateTetris(x,y);}
 else if(game==2){updatePac(x,y);}
 else if(game==3){
  px=constrain(px+x*6,0,106);
  if(brickIntro){brickIntro--;dirty=true;return;}
  int oldY=by;bx+=vx;by+=vy;
  if(bx<=2||bx>=125){bx=constrain(bx,2,125);vx=-vx;beep(3000,30);}
  if(by<=13){by=13;vy=abs(vy);}
  for(uint8_t i=0;i<20;i++)if(bricks&(1UL<<i)){
   int xx=(i%5)*25+2,yy=13+(i/5)*7;
   if(bx>=xx-2&&bx<=xx+24&&by>=yy-2&&by<=yy+6){
    bricks&=~(1UL<<i);score++;
    if(oldY<=yy-2){by=yy-3;vy=-abs(vy);}
    else if(oldY>=yy+6){by=yy+7;vy=abs(vy);}
    else {vx=-vx;bx+=vx;}
    break;
   }
  }
  if(vy>0&&by>=56&&by<=61&&bx>=px-2&&bx<=px+24){
   by=56;vy=-brickSpeed();vx=variedPaddleDeflection(bx-(px+11),11,brickSpeed(),2);beep(3500,40);
  }
  if(by>64){endGame();return;}
  if(!bricks){
   score+=50;saveRecord();
   if(brickLevel==BRICK_LEVELS){endGame(true);return;}
   brickLevel++;loadBrickLevel();beep(5000,160);return;
  }
 }
 else if(game==4){px=constrain(px+y*5,16,53);obstacleX-=3;if(obstacleX<24&&obstacleX+12>12&&obstacleY<px+8&&obstacleY+8>px){endGame();return;}if(obstacleX< -12){score++;obstacleX=128;obstacleY=random(16,54);}}
 else if(game==5){updateSnake(x,y);}
 if(mode==1&&score>previousScore)beep(4500,70);
 dirty=true;
}
void setup(){pinMode(BUZZER,OUTPUT);digitalWrite(BUZZER,LOW);Serial.begin(115200);loadRecords();analogReadResolution(12);pinMode(BUTTON,INPUT_PULLUP);delay(200);long a=0,b=0;for(uint8_t i=0;i<32;i++){a+=analogRead(32);b+=analogRead(33);delay(5);}cx=a/32;cy=b/32;randomSeed(micros()+a+b);ready=screen.begin(SSD1306_SWITCHCAPVCC,0x3C);if(!ready)Serial.println(F("OLED no responde en 0x3C"));
 if(ready){
  // Timed startup indicator: redraw only when the percentage changes.
  const unsigned long loadingStart=millis();
  int lastPercent=-1;
  for(;;){
   int percent=min(100UL,(millis()-loadingStart)/100UL);
   if(percent!=lastPercent){
    screen.clearDisplay();
    text(35,12,F("GAME YISUS"));
    text(40,26,F("CARGANDO"));
    screen.setCursor(percent==100?52:(percent>=10?55:58),38);
    screen.print(percent);screen.print('%');
    screen.drawRect(12,50,104,8,SSD1306_WHITE);
    screen.fillRect(14,52,percent,4,SSD1306_WHITE);
    screen.display();
    lastPercent=percent;
   }
   if(percent==100)break;
   delay(1);
  }
  // Ignore a button held during startup until it has been released.
  rawOld=held=digitalRead(BUTTON)==LOW;
  longDone=held;
  changed=navAt=menuActivityAt=millis();
  downAt=millis();
  directionEvents=xQueueCreate(32,sizeof(DirectionEvent));
  buttonEvents=xQueueCreate(32,sizeof(ButtonEvent));
  if(!buttonEvents||!directionEvents){ready=false;Serial.println("Error: cola del boton");return;}
  if(xTaskCreate(sampleJoystick,"joystick",2048,nullptr,2,nullptr)!=pdPASS){ready=false;Serial.println("Error: tarea del joystick");return;}
  if(xTaskCreate(sampleButton,"button",2048,nullptr,2,nullptr)!=pdPASS){ready=false;Serial.println("Error: tarea del boton");return;}
 }
}
void loop(){if(!ready)return;unsigned long now=millis();bool click=false,pressed=false;
 ButtonEvent event;
 if(xQueueReceive(buttonEvents,&event,0)==pdTRUE){
  held=event.down;
  if(held){downAt=event.at;longDone=false;pressed=true;}
  else if(!longDone)click=true;
  Serial.printf("Boton GPIO27: %s\n",held?"PULSADO":"SUELTO");
 }

 if(mode!=3&&held&&!longDone&&now-downAt>=800){longDone=true;if(mode==1)saveRecord();beep(3000,100);mode=0;paused=false;pauseClicks=0;dirty=true;navAt=menuActivityAt=now;}
 int x=0,y=0;readJoystick(x,y);
 // Only NEW direction changes request a turn. Holding an old direction
 // must not overwrite a queued corner or cause a second unwanted snake turn.
 DirectionEvent direction;
 while(xQueueReceive(directionEvents,&direction,0)==pdTRUE){
  if(mode!=1||paused)continue;
  int dx=direction.x,dy=direction.y;
  if(game==2&&(dx||dy)){pacWantedX=dx;pacWantedY=dy;}
  if(game==5&&(dx||dy)){
   if((dx&&snakeDX==0)||(dy&&snakeDY==0)){
    snakeWantedX=dx;snakeWantedY=dy;snakeTurnQueued=true;
   }
  }
 }
 if(mode==3){
  if(pressed){mode=0;menuActivityAt=navAt=now;longDone=true;dirty=true;beep(4000,60);}
 }
 else if(mode==0){
  if(x||y||held||pressed||click)menuActivityAt=now;
  if(now-menuActivityAt>=10000){mode=3;dirty=true;}
  if(mode==0&&y&&now-navAt>=220){menuSelection=(menuSelection+GAME_COUNT+1+y)%(GAME_COUNT+1);navAt=now;dirty=true;beep(4000,35);}if(mode==0&&click){if(menuSelection==GAME_COUNT){mode=5;rankSelection=currentRank();dirty=true;navAt=now;}else{game=menuSelection;chooseDifficulty();}}}
 else if(mode==5){
  if(y&&now-navAt>=220){rankSelection=(rankSelection+RANK_COUNT+y)%RANK_COUNT;navAt=now;dirty=true;beep(4000,35);}
  if(click){mode=currentRank()==RANK_COUNT-1?6:0;rankChoice=0;rankSaveError=false;menuActivityAt=now;dirty=true;}
 }
 else if(mode==6||mode==7){
  if(y&&now-navAt>=220){rankChoice=1-rankChoice;navAt=now;dirty=true;beep(4000,35);}
  if(click){
   if(rankChoice==0){mode=0;menuActivityAt=now;dirty=true;}
   else if(mode==6){mode=7;rankChoice=0;rankSaveError=false;dirty=true;}
   else if(recordsReady&&recordsStore.putUInt("rank-points",0)==4){
    rankPoints=0;earnedPoints=0;rankSelection=0;rankSaveError=false;
    mode=0;menuActivityAt=now;dirty=true;beep(4500,100);
   }else{rankSaveError=true;dirty=true;Serial.println("Error al reiniciar rangos");}
  }
 }
 else if(mode==2){if(click)chooseDifficulty();}
 else if(mode==4){
  if(y&&now-navAt>=220){difficulty=(difficulty+3+y)%3;navAt=now;dirty=true;beep(4000,35);}
  if(click)startGame();
 }
 else {
  if(pauseClicks&&now-lastPauseClick>1500){pauseClicks=0;dirty=true;}
  if(pressed){
   if(paused){paused=false;pauseClicks=0;tickAt=now;fallAt=now;snakeAt=now;dirty=true;beep(4500,60);}
   else {
    lastPauseClick=now;dirty=true;
    if(++pauseClicks>=3){paused=true;pauseClicks=0;noTone(BUZZER);dirty=true;Serial.println("PAUSA ACTIVADA");}

   }
  }
  if(!paused&&now-tickAt>=gameInterval[difficulty]){tickAt=now;updateGame(x,y);}
 }

 if(dirty)draw();
}

Remix this project

Make it yours in one click

Open a full copy of this project in your own Schematik workspace, diagram, code, parts, and assembly steps included. Swap the sensor, add features, or redesign the whole thing with AI. The author's original stays untouched.

Open in Schematik