import pygame
import math

pygame.init()

screenWidth = 500
screenHeight = 300
screen = pygame.display.set_mode((screenWidth, screenHeight))  # Fenstergrösse

pygame.display.set_caption("Pong")

# Spieler-Rechteck Position
x1 = 40
y1 = 130
x2 = 455
y2 = 130

# Spieler-Rechteck Grösse
width = 5
height = 40
vel = 2

## Eigenschaften des Balls
ballx = 170  # Ball Anfangsposition
bally = 100
dirx = 1.0  # Ball Bewegungsrichtung entlang x-Koordinate
diry = -1.0
speed = 0.7  # Ball Geschwindigkeit

run = True
while run:
    pygame.time.delay(
        5
    )  # time delay in milliseconds (kind of the clock delay in the game)

    for (
        event
    ) in (
        pygame.event.get()
    ):  # loop over all the events that happen in the game (e.g. mouse click or motion)
        if (
            event.type == pygame.QUIT
        ):  # if we find the event of QUIT (user clicked on window exit button)
            run = False

    keys = pygame.key.get_pressed()

    # Bewegung der Spieler
    if (keys[pygame.K_w]) and y1 >= 0:
        y1 -= vel
    if (keys[pygame.K_s]) and y1 <= screenHeight - height:
        y1 += vel
    if (keys[pygame.K_UP]) and y2 >= 0:
        y2 -= vel
    if (keys[pygame.K_DOWN]) and y2 <= screenHeight - height:
        y2 += vel

    # lass den Ball bewegen
    ballx = ballx + speed * dirx
    bally = bally + speed * diry

    # Reflexion an den Paddles
    if x1 <= ballx <= x1 + width and y1 < bally < y1 + height:
        dirx = -dirx
    if x2 <= ballx <= x2 + width and y2 < bally < y2 + height:
        dirx = -dirx

    # Wenn der Ball die Decke oder den Boden berührt, dann sollte er seine Richtung ändern
    if bally <= 0 or bally >= screenHeight:
        diry = -diry

    screen.fill(
        (0, 0, 0)
    )  # fill the screen with black in order to conceal the image of the previous time step

    # Zeichne Spieler-Rechtecke
    pygame.draw.rect(
        screen, (255, 0, 0), (x1, y1, width, height)
    )  # draw rectangle on the 'win' surface in the color red (RGB: 255,0,0) with my defined size. (in pygame the coordinates are on the top left)
    pygame.draw.rect(screen, (255, 0, 0), (x2, y2, width, height))

    # Zeichne Ball
    pygame.draw.rect(screen, (255, 0, 0), (ballx, bally, width, width))

    pygame.display.update()

pygame.quit()