import pygame
import sas_pygame3 as sas

view = sas.createView(600, 400, "white","Breakout")
bandeRechts = sas.Rectangle(590,0,10,400, "black")
bandeOben = sas.Rectangle(0,0,600,30, "black")
bandeLinks = sas.Rectangle(0,0,10,400, "black")
bandeUnten = sas.Rectangle(0, 400, 600, 10,"black")
ball = sas.Circle(295, 195, 10, "blue")
ball.setDirection(sas.Tools.randomNumber(1, 44))
schlaeger = sas.Rectangle(200, 355, 50, 5, "green")
hindernisse = []
for i in range(25):
    hindernisse.append(sas.Rectangle(40 + i*20, 100, 10, 10,"orange"))

def aendereRichtung(richtung, ball):
    if richtung ==1 or richtung == 3:
        ball.setDirection(360 - ball.getDirection())
    elif richtung == 0:
        ball.setDirection(180 - ball.getDirection())
    elif richtung == 2:
        ball.setDirection(180 - ball.getDirection()+sas.Tools.randomNumber(1,5))

def gibHindernisIndex():
    index = - 1
    for i in range(len(hindernisse)):
        if ball.intersects(hindernisse[i]):
            index = i
    return index

def pruefeEnde(hits):
    if ball.intersects(bandeUnten):
        return 1
    elif hits == len(hindernisse):
        return 2
    return 0

def main():
    speed = 6
    hits = 0
    schlaegerSpeed = 50
    ballSpeed =5
    kommentar = sas.Text(10,5,"","white")
    while view.running:
        view.step()
        ende = pruefeEnde(hits)
        if ende == 0: 
            if ball.intersects(bandeUnten) or hits == len(hindernisse):
                schlaegerSpeed = 0
                ballSpeed = 0
            if view.keyLeftPressed():
                schlaeger.move(-schlaegerSpeed)
            if view.keyRightPressed():
                schlaeger.move(schlaegerSpeed)
            if ball.intersects(bandeOben):
                aendereRichtung(0, ball)
            if ball.intersects(bandeLinks):
                aendereRichtung(1, ball)
            if ball.intersects(bandeRechts):
                aendereRichtung(3, ball)
            if ball.intersects(schlaeger):
                aendereRichtung(2, ball) 
            hindernisNr = gibHindernisIndex()
            if hindernisNr != -1:
                aendereRichtung(2,ball)
                hindernisse[hindernisNr].setHidden(True)
                hits += 1
            ball.move(ballSpeed)
        elif ende == 1:
            kommentar.set_text("Leider verloren Neustart mit n") 
        elif ende == 2:
            kommentar.set_text("Glückwunscht alle Steine abgeräumt Neustart mit n")
        if view.keyPressed('n'):
            ende = 0
            for i in range(len(hindernisse)):
                    hindernisse[i].setHidden(False)
            ball.moveTo(295, 195)
            hits = 0
            kommentar.set_text("")         
        view.clock.tick(30)
    pygame.quit()
        

main()


