0% found this document useful (0 votes)
18 views14 pages

New Microsoft Word Document

This document is a Python script that uses Pygame to create an interactive pendulum simulation. It allows users to select different planetary gravity values, reset the pendulum, and view recorded swing times. The simulation includes graphical elements like a gradient background, pendulum rod, and user interface buttons for interaction.

Uploaded by

Ayesha Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views14 pages

New Microsoft Word Document

This document is a Python script that uses Pygame to create an interactive pendulum simulation. It allows users to select different planetary gravity values, reset the pendulum, and view recorded swing times. The simulation includes graphical elements like a gradient background, pendulum rod, and user interface buttons for interaction.

Uploaded by

Ayesha Hassan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

import pygame

import math

import time

# Initialize pygame

pygame.init()

# Screen dimensions

WIDTH, HEIGHT = 1280, 720

screen = pygame.display.set_mode((WIDTH, HEIGHT))

pygame.display.set_caption("Interactive Pendulum Simulation")

# Colors

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

BLUE = (0, 0, 255)

DARK_GRAY = (50, 50, 50)

LIGHT_GRAY = (200, 200, 200)

BROWN = (139, 69, 19)

GREEN = (0, 255, 0)

YELLOW = (255, 255, 0)

# Gravity values (in m/s^2)

GRAVITY_VALUES = {

"Earth": 9.8,

"Mars": 3.71,

"Moon": 1.625,

"Jupiter": 24.79,
"Pluto": 0.62,

# Pendulum parameters

pivot = (WIDTH // 2, HEIGHT // 4) # Fixed point

length = 200 # Length of the pendulum rope

angle = 0 # Initial angle (at rest position)

angular_velocity = 0 # Initial angular velocity

angular_acceleration = 0 # Initial angular acceleration

gravity = GRAVITY_VALUES["Earth"] # Default gravity (Earth)

# Timer

start_time = None

elapsed_time = 0

timer_active = False

# Swing times

swing_times = []

best_swing_time = None

# Damping factor

damping = 0.99

# Mouse interaction variables

dragging = False

# Clock for controlling the frame rate

clock = pygame.time.Clock()

FPS = 60
# Fonts

font = pygame.font.Font(None, 36)

large_font = pygame.font.Font(None, 48)

# Gradient background

def draw_gradient_background():

for y in range(HEIGHT):

# Ensure the color values are within the valid range

red = max(0, min(255, 135 - y // 5))

green = max(0, min(255, 206 - y // 10))

blue = max(0, min(255, 235 - y // 15))

color = (red, green, blue)

pygame.draw.line(screen, color, (0, y), (WIDTH, y))

# Draw the planet selection buttons

def draw_planet_buttons():

button_width = 120

button_height = 50

planets = list(GRAVITY_VALUES.keys())

for i, planet in enumerate(planets):

x = 20

y = 50 + i * (button_height + 10)

pygame.draw.rect(screen, LIGHT_GRAY, (x, y, button_width, button_height), border_radius=5)

text = font.render(planet, True, BLACK)

screen.blit(text, (x + (button_width - text.get_width()) // 2, y + (button_height - text.get_height()) //


2))
return planets

# Draw the reset button

def draw_reset_button():

button_width = 120

button_height = 50

x = 20

y = HEIGHT - 70

pygame.draw.rect(screen, GREEN, (x, y, button_width, button_height), border_radius=5)

text = font.render("Reset", True, BLACK)

screen.blit(text, (x + (button_width - text.get_width()) // 2, y + (button_height - text.get_height()) //


2))

# Draw the swing times table

def draw_swing_times_table():

table_x = WIDTH - 300

table_y = 20

pygame.draw.rect(screen, LIGHT_GRAY, (table_x, table_y, 280, 200))

pygame.draw.rect(screen, BLACK, (table_x, table_y, 280, 200), 2) # Table border

# Table header

header_text = font.render("Swing Times (s)", True, BLACK)

screen.blit(header_text, (table_x + 20, table_y + 10))

# Draw the rows of recorded swing times

for i, recorded_time in enumerate(swing_times[-5:]):

time_text = font.render(f"{i + 1}. {recorded_time:.2f}", True, BLACK)

screen.blit(time_text, (table_x + 20, table_y + 40 + i * 30))


# Highlight best swing time

if best_swing_time:

best_text = font.render(f"Best: {best_swing_time:.2f}s", True, RED)

screen.blit(best_text, (table_x + 20, table_y + 160))

# Draw the wooden rod

def draw_wooden_rod():

rod_length = 60

rod_width = 10

rod_top_left = (pivot[0] - rod_length // 2, pivot[1] - rod_width // 2)

pygame.draw.rect(screen, BROWN, pygame.Rect(rod_top_left, (rod_length, rod_width)))

# Main loop

running = True

while running:

screen.fill(WHITE)

draw_gradient_background()

planets = draw_planet_buttons()

draw_reset_button()

draw_swing_times_table()

draw_wooden_rod()

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

if event.type == pygame.MOUSEBUTTONDOWN:

mouse_x, mouse_y = pygame.mouse.get_pos()


# Check if a planet button is clicked

for i, planet in enumerate(planets):

x = 20

y = 50 + i * (50 + 10)

if x <= mouse_x <= x + 120 and y <= mouse_y <= y + 50:

gravity = GRAVITY_VALUES[planet]

print(f"Selected {planet}, gravity: {gravity} m/s^2")

# Check if reset button is clicked

reset_x = 20

reset_y = HEIGHT - 70

if reset_x <= mouse_x <= reset_x + 120 and reset_y <= mouse_y <= reset_y + 50:

# Reset pendulum to initial state

angle = 0

angular_velocity = 0

start_time = None

elapsed_time = 0

timer_active = False

swing_times.clear()

best_swing_time = None

# Start dragging the pendulum with the mouse

pendulum_x = pivot[0] + length * math.sin(angle)

pendulum_y = pivot[1] + length * math.cos(angle)

if math.hypot(mouse_x - pendulum_x, mouse_y - pendulum_y) < 20:

dragging = True

angular_velocity = 0

if event.type == pygame.MOUSEBUTTONUP and dragging:


dragging = False

start_time = time.time()

timer_active = True

# Drag the pendulum with the mouse

if dragging:

mouse_x, mouse_y = pygame.mouse.get_pos()

dx = mouse_x - pivot[0]

dy = mouse_y - pivot[1]

angle = math.atan2(dx, dy)

# Simulate pendulum motion if not dragging

if not dragging:

angular_acceleration = -(gravity / length) * math.sin(angle)

angular_velocity += angular_acceleration

angle += angular_velocity

angular_velocity *= damping

# Stop timer when pendulum is fully at rest

if timer_active and abs(angular_velocity) < 0.001 and abs(angle) < 0.01:

elapsed_time = time.time() - start_time

swing_times.append(elapsed_time)

if best_swing_time is None or elapsed_time > best_swing_time:

best_swing_time = elapsed_time

timer_active = False

# Calculate pendulum position

x = pivot[0] + length * math.sin(angle)

y = pivot[1] + length * math.cos(angle)


pendulum_pos = (int(x), int(y))

# Draw pendulum shadow

shadow_x = pendulum_pos[0]

shadow_y = HEIGHT - 50

pygame.draw.ellipse(screen, LIGHT_GRAY, (shadow_x - 20, shadow_y - 5, 40, 10))

# Draw pendulum rope

pygame.draw.line(screen, DARK_GRAY, pivot, pendulum_pos, 3)

# Draw pendulum bob with 3D effect

pygame.draw.circle(screen, BLACK, pendulum_pos, 20)

pygame.draw.circle(screen, RED, pendulum_pos, 18)

pygame.draw.circle(screen, LIGHT_GRAY, (pendulum_pos[0] - 5, pendulum_pos[1] - 5), 8)

# Display timer

if start_time is not None:

current_time = elapsed_time if not timer_active else time.time() - start_time

timer_text = f"Time: {current_time:.2f} seconds"

text_surface = font.render(timer_text, True, BLACK)

screen.blit(text_surface, (WIDTH // 2 - text_surface.get_width() // 2, HEIGHT - 50))

pygame.display.flip()

clock.tick(FPS)

pygame.quit()

You might also like