from machine import Pin, ADC, PWM
from time import sleep, ticks_ms, ticks_diff
# Sets all of the sounds
class Game_sound:
def __init__(self, pin=14):
self.__buzzer = PWM(Pin(pin))
self.__buzzer.duty_u16(0)
def play(self, freq, duty=2000, duration=0.2):
self.__buzzer.freq(freq)
self.__buzzer.duty_u16(duty)
sleep(duration)
self.__buzzer.duty_u16(0)
class Special_game_sound(Game_sound):
def beep(self, numBeeps):
for _ in range(numBeeps):
self.play(1000, 2000, 0.2)
sleep(0.1)
# Sets the winning sound
def winning_sound(self):
print("Winner!")
self.beep(3)
for freq in range(1000, 2000, 100):
self.play(freq, 3000, 0.1)
# Main logic
class Game:
# Encapsulates score and logic (makes variables private)
def __init__(self, sound: Special_game_sound, cooldown=100):
self.__score = 0
self.__last_score_time = 0
self.__cooldown = cooldown
self.__sound = sound
# Resets the game
def reset(self):
self.__score = 0
self.__sound.beep(2)
print("Ready for new game")
# Checks if the light level is higher, then adds score if it is
def add_score(self, points, light_level):
current_time = ticks_ms()
if light_level > 50000 and ticks_diff(current_time, self.__last_score_time) > self.__cooldown:
self.__score += points
self.__last_score_time = current_time
self.__sound.play(self.__score + 100, self.__score + 1000, 0.2)
print("Score:", self.__score)
if self.__score >= 500:
self.__sound.winning_sound()
self.reset()
# Turns the method into a read-only attribute which allows it to look like a variable
@property
def score(self):
return self.__score
# Hardware configuration
potentiometer1 = ADC(Pin(26))
potentiometer2 = ADC(Pin(27))
light_sensor = ADC(Pin(28))
p2 = Pin(20, Pin.IN, Pin.PULL_UP)
servo_yaw = PWM(Pin(1))
servo_roll = PWM(Pin(0))
servo_yaw.freq(50)
servo_roll.freq(50)
# Game Setup
buzzer = Special_game_sound()
game = Game(buzzer)
game.reset()
while True:
# Read potentiometers
potent1 = potentiometer1.read_u16()
potent2 = potentiometer2.read_u16()
yaw_value = round(potent1 // 5, -2)
roll_value = round(potent2 // 5, -2)
servo_yaw.duty_u16(yaw_value)
servo_roll.duty_u16(roll_value)
# Read light sensor
light_level = 60000 - round(light_sensor.read_u16(), -2)
print(round(potent1 // 5, -3), round(potent2 // 5, -3), light_level)
# Game scoring
game.add_score(10, light_level)
sleep(0.01)