from machine import Pin, ADC, I2C
import time
from pico_i2c_lcd import I2cLcd
# ---------------- LCD SETUP ----------------
I2C_ADDR = 0x27 # change to 0x3F if needed
i2c = I2C(0, sda=Pin(8), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# ---------------- JOYSTICK SETUP ----------------
x_axis = ADC(26) # VRx
y_axis = ADC(28) # VRy
button = Pin(0, Pin.IN, Pin.PULL_UP)
# ---------------- GAME VARIABLES ----------------
player_x = 0
player_y = 0
target_x = 15
target_y = 1
# ---------------- DRAW FUNCTION ----------------
def draw():
lcd.clear()
for row in range(2):
lcd.move_to(0, row)
for col in range(16):
if row == player_y and col == player_x:
lcd.putchar('*')
elif row == target_y and col == target_x:
lcd.putchar('T')
else:
lcd.putchar(' ')
# ---------------- JOYSTICK FUNCTIONS ----------------
def get_direction():
x = x_axis.read_u16()
y = y_axis.read_u16()
if x < 20000:
return "LEFT"
elif x > 45000:
return "RIGHT"
elif y < 20000:
return "UP"
elif y > 45000:
return "DOWN"
else:
return "CENTER"
def wait_for_release():
# wait until joystick returns to center
while True:
x = x_axis.read_u16()
y = y_axis.read_u16()
if 30000 < x < 35000 and 30000 < y < 35000:
break
time.sleep(0.05)
# ---------------- START SCREEN ----------------
lcd.clear()
lcd.putstr("Reach Target!")
time.sleep(2)
# ---------------- GAME LOOP ----------------
while True:
direction = get_direction()
if direction != "CENTER":
if direction == "LEFT" and player_x > 0:
player_x -= 1
elif direction == "RIGHT" and player_x < 15:
player_x += 1
elif direction == "UP" and player_y > 0:
player_y -= 1
elif direction == "DOWN" and player_y < 1:
player_y += 1
draw()
# IMPORTANT: prevents multiple moves (fixes your issue)
wait_for_release()
# WIN CONDITION
if player_x == target_x and player_y == target_y:
lcd.clear()
lcd.putstr(" YOU WON! ")
break
time.sleep(0.05)