import time
import random
time.sleep(0.1) # Wait for USB to become ready
print("Hello, Pi Pico!")
from Lights import *
from Buzzer import *
from TerminalEmulator import *
red = Light(15, 'Red') # create a red light on pin 15
green = Light(13, 'Green') # create a green light on pin 13
beeper = PassiveBuzzer(14, 'Beeper') # Create a passive buzzer named beeper on 14
term = TerminalEmulator() # Create a terminal emulator with default parameters
# Step 3
# Jit Sengupta
# https://wokwi.com/projects/481067707554572289
# Step 4 - custom characters
hero_icon = [0x0E, 0x0C, 0x06, 0x1C, 0x06, 0x0C, 0x1B, 0x01]
gem_icon = [0x00, 0x00, 0x0E, 0x0A, 0x0E, 0x00, 0x00, 0x00]
term.addCustomChar(0, hero_icon)
term.addCustomChar(1, gem_icon)
# Step 5 - test display the gem and hero
player_pos = (0, 0)
gem_pos = (1, 10)
term.showChar(chr(0), player_pos)
term.showChar(chr(1), gem_pos)
score = 0
# Step 6 - define the update_position(pos, key)
def update_position(pos, key):
"""
update position takes the current position of player and
returns the new position based on the key typed
"""
row = pos[0]
col = pos[1]
if key == "2":
row = 0 # moving UP
elif key == "8":
row = 1 # moving down
elif key == "4":
col = max(0, col - 1)
elif key == "6":
col = min(15, col + 1)
return (row, col)
# Step 7 - define the spawn_gem function
def spawn_gem(player_pos):
"""
Randomly generate a position where the gem will be spawned
Make sure it is not the same as player_pos
return the new position
"""
row = random.randint(0, 1)
col = random.randint(0, 15)
while (row, col) == player_pos:
row = random.randint(0, 1)
col = random.randint(0, 15)
return (row, col)
# Step 8 - alert function
def alert(success = True, tone = 1400):
"""
Alert for a success or fail (success = False)
Plays the tone passed if success
Plays an ending note if fail
Turns on the red/green led depending on success
"""
if success:
green.on()
beeper.beep(tone, duration=80)
green.off()
else:
red.on()
# play some ending note
red.off()
# Step 9 - game loop
game_playing = True
while game_playing:
key = term.scanKey()
if key is not None:
new_pos = update_position(player_pos, key)
if new_pos != player_pos:
term.showChar(chr(0), new_pos)
term.clearCell(player_pos)
player_pos = new_pos
if player_pos == gem_pos:
score = score + 1
print(f"Score is {score}")
alert(success=True)
gem_pos = spawn_gem(player_pos)
term.showChar(chr(1), gem_pos)
time.sleep_ms(60)