from machine import Pin, I2C
import time
from Displays import LCDDisplay
from Button import Button
from LightStrip import LightStrip
from Buzzer import PassiveBuzzer
from Log import Log


class PingPongController:
    def __init__(self):
        """
        Initializes the Ping Pong game controller, setting up buttons,
        buzzer, LCD, and light strip.
        """
        Log.i("PingPongController: initializing components")

        # Initialize Buttons
        self.player1_button = Button(18, "Player 1", handler=self)
        self.player2_button = Button(17, "Player 2", handler=self)

        # Initialize Buzzer
        self.buzzer = PassiveBuzzer(16, "Game Buzzer")

        # Initialize LCD Display
        self.lcd = LCDDisplay(sda=0, scl=1)
        self.lcd.clear()
        self.lcd.showText("Ping Pong Game")

        # Initialize Light Strip
        self.light_strip = LightStrip(pin=2, name="Neopixel Strip", numleds=8)

    def demo(self):
        """
        Demonstrates a simple animation on the light strip, moving
        a "ball" back and forth.
        """
        Log.i("PingPongController: starting demo")
        num_leds = self.light_strip._numleds
        ball_position = 0
        direction = 1

        while True:  # Loop the demo animation until you manually stop it.
            self.light_strip.setColor((0, 0, 0))  # Clear the strip
            self.light_strip.setPixel(ball_position, (255, 255, 255))  # White ball
            self.light_strip.show()
            time.sleep(0.2)

            ball_position += direction
            if ball_position >= num_leds:
                ball_position = num_leds - 1
                direction = -1
            elif ball_position < 0:
                ball_position = 0
                direction = 1
            
            if self.player1_button.isPressed() or self.player2_button.isPressed():
                Log.i("PingPongController: demo stopped by user input")
                break

    def buttonPressed(self, buttonName):
        """
        Handles button press events for the two player buttons
        """
        Log.i(f"PingPongController: {buttonName} pressed")
        self.buzzer.beep(500, 100)

    def buttonReleased(self, buttonName):
        """
        Handles button release events for the two player buttons
        """
        Log.i(f"PingPongController: {buttonName} released")
        self.buzzer.beep(1000, 50)

if __name__ == '__main__':
    #Log.setDebug(True)
    controller = PingPongController()
    controller.demo()
    
    while True:
        time.sleep(1)
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT