from machine import Pin, SoftI2C, ADC
import ssd1306
import time
# Configurar pantalla OLED (I2C) usando SoftI2C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# Configurar Joystick
x_pin = ADC(Pin(34)) # Eje X del joystick
y_pin = ADC(Pin(35)) # Eje Y del joystick
x_pin.atten(ADC.ATTN_11DB)
y_pin.atten(ADC.ATTN_11DB)
button_pin = Pin(32, Pin.IN, Pin.PULL_UP)
# Variables del juego
ship_x = oled_width // 2 # Posición inicial de la nave
ship_y = oled_height - 10
bullet_active = False
bullet_x = ship_x
bullet_y = ship_y - 10
bullet_speed = 5
enemy_y = 0
enemy_x = 64
enemy_speed = 1
score = 0
# Función para dibujar la nave
def draw_ship(x, y):
oled.fill(0) # Limpiar pantalla antes de dibujar
# Dibujar una nave simple usando píxeles
for dx in range(10):
oled.pixel(x + dx, y, 1)
oled.pixel(x + 5, y - 1, 1)
oled.pixel(x + 4, y - 2, 1)
oled.pixel(x + 6, y - 2, 1)
# Función para mover la nave con el joystick
def move_ship():
global ship_x
x_val = x_pin.read() # Leer valor del eje X
ship_x = int(x_val / 4095 * (oled_width - 10)) # Mapear el rango del joystick al ancho de la pantalla
# Función para disparar un proyectil
def shoot():
global bullet_active, bullet_x, bullet_y
if bullet_active: # Mover el proyectil si está activo
bullet_y -= bullet_speed
if bullet_y < 0: # Si el proyectil sale de la pantalla
bullet_active = False
else: # Activar nuevo disparo si el botón está presionado
if not button_pin.value():
bullet_active = True
bullet_x = ship_x + 4
bullet_y = ship_y - 10
# Función para dibujar al enemigo
def draw_enemy():
global enemy_y, enemy_x
enemy_y += enemy_speed # El enemigo baja por la pantalla
if enemy_y > oled_height:
enemy_y = 0
enemy_x = (enemy_x + 20) % oled_width # Cambiar de lugar cuando llega abajo
# Función para detectar colisiones
def check_collision():
global score, bullet_active, enemy_y, enemy_x
if bullet_active and (bullet_y < enemy_y + 5) and (enemy_x < bullet_x < enemy_x + 10):
score += 1
enemy_y = 0 # Reiniciar la posición del enemigo
enemy_x = (enemy_x + 30) % oled_width
bullet_active = False
# Bucle principal del juego
while True:
oled.fill(0) # Limpiar la pantalla
# Mover la nave con el joystick
move_ship()
# Dibujar la nave
draw_ship(ship_x, ship_y)
# Disparar el proyectil
shoot()
if bullet_active:
for dy in range(5): # Dibujar el proyectil usando píxeles
oled.pixel(bullet_x, bullet_y + dy, 1)
# Dibujar y mover al enemigo
draw_enemy()
for dx in range(10): # Dibujar enemigo usando píxeles
for dy in range(5):
oled.pixel(enemy_x + dx, enemy_y + dy, 1)
# Comprobar colisiones
check_collision()
# Mostrar el puntaje
oled.text('Score: {}'.format(score), 0, 0)
# Actualizar la pantalla
oled.show()
# Control de velocidad del juego
time.sleep(0.05)