import numpy as np
import matplotlib.pyplot as plt

# Erdbeschleunigung
g = 9.81  # m/s^2

# Anfangswerte für den schiefen Wurf
x0 = 0.0        # Start-x in m
y0 = 0.0        # Start-y in m (z.B. Boden)
v0 = 20.0       # Anfangsgeschwindigkeit in m/s
alpha_deg = 45  # Abwurfwinkel in Grad

# Winkel in Radiant
alpha = np.deg2rad(alpha_deg)

# Anfangskomponenten der Geschwindigkeit
v0x = v0 * np.cos(alpha)
v0y = v0 * np.sin(alpha)

# Bewegungsgleichungen
def x(t):
    """Weg in x-Richtung"""
    return x0 + v0x * t

def y(t):
    """Weg in y-Richtung"""
    return y0 + v0y * t - 0.5 * g * t**2

def vx(t):
    """Geschwindigkeit in x-Richtung (konstant)"""
    return v0x * np.ones_like(t)

def vy(t):
    """Geschwindigkeit in y-Richtung"""
    return v0y - g * t

def ax(t):
    """Beschleunigung in x-Richtung (0)"""
    return np.zeros_like(t)

def ay(t):
    """Beschleunigung in y-Richtung (-g)"""
    return -g * np.ones_like(t)

# Flugzeit bestimmen: y(T) = 0
# y(t) = y0 + v0y * t - 0.5*g*t**2 = 0
# => -0.5*g*t^2 + v0y*t + y0 = 0
A = -0.5 * g
B = v0y
C = y0

D = B**2 - 4 * A * C  # Diskriminante

if D < 0:
    raise ValueError("Keine reale Flugzeit: prüfe y0, v0 und alpha.")

t1 = (-B + np.sqrt(D)) / (2 * A)
t2 = (-B - np.sqrt(D)) / (2 * A)

# Positive Lösung als Flugzeit wählen
t_candidates = [t for t in (t1, t2) if t > 0]
if not t_candidates:
    raise ValueError("Keine positive Flugzeit gefunden.")

T = max(t_candidates)

# Zeitvektor von 0 bis T
t = np.linspace(0, T, 400)

# Werte berechnen
x_t = x(t)
y_t = y(t)
vx_t = vx(t)
vy_t = vy(t)
ax_t = ax(t)
ay_t = ay(t)

# Plot 1: Weg-Zeit-Funktionen
plt.figure()
plt.plot(t, x_t, label="x(t)")
plt.plot(t, y_t, label="y(t)")
plt.xlabel("Zeit t [s]")
plt.ylabel("Weg [m]")
plt.title("Schiefer Wurf: Weg-Zeit-Funktionen")
plt.legend()
plt.grid(True)

# Plot 2: Geschwindigkeit-Zeit-Funktionen
plt.figure()
plt.plot(t, vx_t, label="v_x(t)")
plt.plot(t, vy_t, label="v_y(t)")
plt.xlabel("Zeit t [s]")
plt.ylabel("Geschwindigkeit [m/s]")
plt.title("Schiefer Wurf: Geschwindigkeit-Zeit-Funktionen")
plt.legend()
plt.grid(True)

# Plot 3: Beschleunigung-Zeit-Funktionen
plt.figure()
plt.plot(t, ax_t, label="a_x(t)")
plt.plot(t, ay_t, label="a_y(t)")
plt.xlabel("Zeit t [s]")
plt.ylabel("Beschleunigung [m/s^2]")
plt.title("Schiefer Wurf: Beschleunigung-Zeit-Funktionen")
plt.legend()
plt.grid(True)

# Plot 4: Bahnkurve y(x)
plt.figure()
plt.plot(x_t, y_t)
plt.xlabel("x [m]")
plt.ylabel("y [m]")
plt.title("Schiefer Wurf: Bahnkurve y(x)")
plt.grid(True)

plt.show()
