import pygame
import sas_pygame as sas

view = sas.createView(600, 400, "white","Staubsaugerroboter")
teppich = sas.Picture(0,0,600,400,"teppich.jpg")
randRechts = sas.Rectangle(580,0,20,400, "blue")
randOben = sas.Rectangle(0,0,580,20, "blue")
randLinks = sas.Rectangle(0,20,20,380, "blue")
randUnten = sas.Rectangle(0, 380, 580, 20,"blue")
station = sas.Rectangle(20, 20,70, 70, "yellow")
anleitung = sas.Text(20,2,"s: zur Station    f: fahren", "white")
staub = []
for i in range(80):
    x = sas.Tools.randomNumber(25,575)
    y = sas.Tools.randomNumber(25,375)
    if  (x >92)  or (x < 92 and y > 92):
        staub.append(sas.Circle(x, y, 3))
roboter = sas.Sprite(sas.Circle(300, 200, 30, "red"))

zaehlerAnzeige = sas.Text(315, 222,"000", "white")
zaehlerAnzeige.setFont( 16)
roboter.add(zaehlerAnzeige)
roboter.setDirection(sas.Tools.randomNumber(0,360))

def updateTextanzeige(zaehler):
    zahlstring = str(zaehler)
    while len(zahlstring)<3:
        zahlstring = "0"+zahlstring
    zaehlerAnzeige.setText(zahlstring)

def saugeStaub(staub, roboter, staubzaehler):
    tempstaub = []
    for staubkorn in staub:
        if roboter.intersects(staubkorn):
            staubzaehler += 1
            staubkorn.setHidden(True)
            updateTextanzeige(staubzaehler)
        else:
            tempstaub.append(staubkorn)
    return tempstaub, staubzaehler


def pruefeRand(roboter):
    if roboter.intersects(randLinks):
        roboter.setDirection(sas.Tools.randomNumber(0,180))
    if roboter.intersects(randRechts):
        roboter.setDirection(sas.Tools.randomNumber(180,360))
    if roboter.intersects(randOben):
        roboter.setDirection(sas.Tools.randomNumber(90,270))
    if roboter.intersects(randUnten):
        roboter.setDirection(sas.Tools.randomNumber(270,450))

def main():
    global staub
    zaehler = 0
    speed = 5
    home_speed = 1.5
    stop = False

    going_home = False
    home_speed = 1.5
    while view.running:
        view.step()
        if view.keyPressed('s'):
            going_home = True
            stop = True
            view.keyBufferDelete()
        if view.keyPressed('f'):
            going_home = False
            stop = False
            roboter.setDirection(125)
            view.keyBufferDelete()
        if going_home:
            richtung = sas.Tools.getDirection(
                roboter.get_center_x(), roboter.get_center_y(),
                station.getCenterX(), station.getCenterY()
            )
            roboter.setDirection(richtung)
            roboter.move(home_speed)
            if station.contains(roboter):
                going_home = False
        else:
            if not stop:
                roboter.move(speed)
        pruefeRand(roboter)
        staub, zaehler   = saugeStaub(staub, roboter, zaehler)
        print(len(staub))

    view.quit()

main()