import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ball Over Wall Simulation")
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
GRAY = (200, 200, 200)
# Fonts
font = pygame.font.SysFont(None, 24)
# Physics parameters
GRAVITY = -650 # units/s^2
BALL_RADIUS = 96.3881 # units
WALL_Y = 1474 # units
WALL_HEIGHT = 400 # units
BALL_MAX_SPEED = 6000
Y_MAX = 3581
Y_MIN = -3581
# Scaling factors to fit the simulation on screen
# Assume y ranges from 0 to 2000 mapped to 0 to WIDTH
SCALE_Y = WIDTH / 4000 # y from -2000 to +2000
# z ranges from 0 to 1000 mapped to HEIGHT
SCALE_Z = HEIGHT / 1000
# Function to convert simulation coordinates to screen coordinates
def sim_to_screen(y, z):
screen_x = WIDTH // 2 + int(y * SCALE_Y / 2)
screen_y = HEIGHT - int(z * SCALE_Z)
return (screen_x, screen_y)
# Button class
class Button:
def __init__(self, rect, color, text):
self.rect = pygame.Rect(rect)
self.color = color
self.text = text
self.text_surface = font.render(text, True, BLACK)
text_rect = self.text_surface.get_rect(center=self.rect.center)
self.text_pos = (self.rect.x + (self.rect.width - self.text_surface.get_width()) / 2,
self.rect.y + (self.rect.height - self.text_surface.get_height()) / 2)
def draw(self, surface):
pygame.draw.rect(surface, self.color, self.rect)
surface.blit(self.text_surface, self.text_pos)
def is_clicked(self, pos):
return self.rect.collidepoint(pos)
# Initialize ball parameters
ball_pos = [0, 0] # [y, z] in simulation units
ball_velocity = [0, 0] # [vy, vz] in units/s
ball_launched = False
trajectory = []
freeze = False
# Create buttons
predict_button = Button((50, 550, 100, 30), GRAY, "Predict")
launch_button = Button((200, 550, 100, 30), GRAY, "Launch")
reset_button = Button((350, 550, 100, 30), GRAY, "Reset")
# Helper function to predict if the ball will clear the wall
def predict_clear(y0, z0, v0, theta_deg):
if v0 > BALL_MAX_SPEED:
return False
theta_rad = math.radians(theta_deg)
vy = v0 * math.cos(theta_rad)
vz = v0 * math.sin(theta_rad)
if vy <= 0:
return False
t_wall = (WALL_Y - y0) / vy
if t_wall < 0:
return False
z_wall = z0 + vz * t_wall + 0.5 * GRAVITY * t_wall ** 2
if z_wall > (WALL_HEIGHT + BALL_RADIUS):
return True
else:
return False
# Helper function to simulate trajectory
def simulate_trajectory(y0, z0, vy, vz, delta_t=0.01):
traj = []
t = 0
current_y = y0
current_z = z0
while current_y <= Y_MAX and current_y >= Y_MIN and current_z >= BALL_RADIUS:
current_y = y0 + vy * t
current_z = z0 + vz * t + 0.5 * GRAVITY * t ** 2
traj.append((current_y, current_z))
# Check collision with floor
if current_z <= BALL_RADIUS:
break
# Check collision with wall
if (current_y >= WALL_Y - BALL_RADIUS and current_y <= WALL_Y + BALL_RADIUS):
if current_z <= WALL_HEIGHT + BALL_RADIUS:
traj.append((current_y, WallCollision=current_z))
break
t += delta_t
return traj
# Main loop
clock = pygame.time.Clock()
while True:
clock.tick(60) # 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Mouse events
elif event.type == pygame.MOUSEBUTTONDOWN and not ball_launched:
mouse_x, mouse_y = event.pos
# Convert screen to simulation coordinates
sim_y = (mouse_x - WIDTH / 2) * 2 / SCALE_Y
sim_z = (HEIGHT - mouse_y) / SCALE_Z
ball_pos = [sim_y, sim_z]
elif event.type == pygame.KEYDOWN and not ball_launched:
if event.key == pygame.K_SPACE:
# Launch the ball
# For simplicity, let's set velocity based on position
# Alternatively, you can implement dragging to set velocity
pass
# Drawing
screen.fill(WHITE)
# Draw wall
wall_screen_start = sim_to_screen(WALL_Y, 0)
wall_screen_end = sim_to_screen(WALL_Y, WALL_HEIGHT)
pygame.draw.line(screen, BLACK, wall_screen_start, wall_screen_end, 5)
# Draw floor
pygame.draw.line(screen, BLACK, (0, HEIGHT), (WIDTH, HEIGHT), 2)
# Draw ball
if not ball_launched:
screen_pos = sim_to_screen(ball_pos[0], ball_pos[1])
pygame.draw.circle(screen, BLUE, screen_pos, max(int(BALL_RADIUS * SCALE_Z), 5))
# Draw buttons
predict_button.draw(screen)
launch_button.draw(screen)
reset_button.draw(screen)
# Display instructions
instructions = [
"Click to set ball position.",
"Press 'P' to Predict.",
"Press 'L' to Launch.",
"Press 'R' to Reset."
]
for i, text in enumerate(instructions):
text_surface = font.render(text, True, BLACK)
screen.blit(text_surface, (50, 20 + i * 20))
# Handle button clicks
mouse_pressed = pygame.mouse.get_pressed()
if mouse_pressed[0]:
mouse_pos = pygame.mouse.get_pos()
if predict_button.is_clicked(mouse_pos):
# Ask for velocity and angle
# For simplicity, using preset values or you can implement input dialogs
# Here we'll use keyboard input to set velocity and angle
# But Pygame doesn't provide easy text input, so we can skip for now
pass
elif launch_button.is_clicked(mouse_pos):
# Launch the ball with predefined velocity and angle
# For demo purposes, set some velocity and angle
v0 = 3000 # units/s
theta_deg = 45 # degrees
clear = predict_clear(ball_pos[0], ball_pos[1], v0, theta_deg)
if clear:
print("Prediction: Ball will clear the wall.")
else:
print("Prediction: Ball will NOT clear the wall.")
# Simulate and set velocity
theta_rad = math.radians(theta_deg)
vy = v0 * math.cos(theta_rad)
vz = v0 * math.sin(theta_rad)
trajectory = simulate_trajectory(ball_pos[0], ball_pos[1], vy, vz)
ball_velocity = [vy, vz]
ball_launched = True
freeze = False
elif reset_button.is_clicked(mouse_pos):
# Reset the simulation
ball_pos = [0, 0]
ball_velocity = [0, 0]
ball_launched = False
trajectory = []
freeze = False
# Handle keyboard inputs
keys = pygame.key.get_pressed()
if not ball_launched:
if keys[pygame.K_p]:
# Predict
# For simplicity, let's set velocity and angle
# You can enhance this by adding input prompts
v0 = 3000 # Example velocity
theta_deg = 45 # Example angle
clear = predict_clear(ball_pos[0], ball_pos[1], v0, theta_deg)
prediction_text = "Clear" if clear else "Not Clear"
print(f"Prediction: {prediction_text}")
pygame.time.wait(200) # Prevent multiple prints
if keys[pygame.K_l]:
# Launch
v0 = 3000 # Example velocity
theta_deg = 45 # Example angle
clear = predict_clear(ball_pos[0], ball_pos[1], v0, theta_deg)
if clear:
print("Prediction: Ball will clear the wall.")
else:
print("Prediction: Ball will NOT clear the wall.")
# Simulate and set velocity
theta_rad = math.radians(theta_deg)
vy = v0 * math.cos(theta_rad)
vz = v0 * math.sin(theta_rad)
trajectory = simulate_trajectory(ball_pos[0], ball_pos[1], vy, vz)
ball_velocity = [vy, vz]
ball_launched = True
freeze = False
# Simulate trajectory
if ball_launched and not freeze:
if len(trajectory) > 0:
pos = trajectory.pop(0)
if isinstance(pos, tuple) and 'WallCollision' in pos:
freeze = True
else:
ball_pos = list(pos)
else:
ball_launched = False # Trajectory finished
# Draw trajectory
for point in trajectory:
y, z = point
screen_point = sim_to_screen(y, z)
pygame.draw.circle(screen, RED, screen_point, 2)
# Update display
pygame.display.flip()