To simulate a tree’s shadow changing as the sun rises in the east and sets in the west, we can use Python 3 and the math library to calculate the angle of the sun’s position at a given time, and the Pygame library to draw the tree and its shadow.
Here is an example program that simulates the tree’s shadow changing throughout the day:
pythonCopy codeimport pygame
import math
# Initialize Pygame
pygame.init()
# Define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# Set up the window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Tree Shadow Simulation")
# Set up the tree
TREE_HEIGHT = 200
TREE_WIDTH = 50
tree_rect = pygame.Rect((WINDOW_WIDTH - TREE_WIDTH) / 2, WINDOW_HEIGHT - TREE_HEIGHT, TREE_WIDTH, TREE_HEIGHT)
# Set up the sun
SUN_RADIUS = 20
sun_position = (WINDOW_WIDTH / 2, -SUN_RADIUS)
# Define the time of day in minutes (0 = midnight, 720 = noon, 1440 = midnight)
time_of_day = 0
# Define the function to calculate the sun's position based on the time of day
def calculate_sun_position(time_of_day):
# Convert time of day to radians
time_in_radians = (time_of_day / 1440) * 2 * math.pi
# Calculate the sun's position based on the time of day
x = (WINDOW_WIDTH / 2) + (WINDOW_WIDTH / 2 - SUN_RADIUS) * math.cos(time_in_radians)
y = SUN_RADIUS + (WINDOW_HEIGHT / 2 - SUN_RADIUS) * math.sin(time_in_radians)
return (x, y)
# Define the main loop
running = True
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Clear the screen
window.fill(WHITE)
# Draw the tree
pygame.draw.rect(window, GREEN, tree_rect)
# Draw the sun
sun_position = calculate_sun_position(time_of_day)
pygame.draw.circle(window, YELLOW, sun_position, SUN_RADIUS)
# Calculate the angle of the sun's position
dx = sun_position[0] - tree_rect.centerx
dy = sun_position[1] - tree_rect.centery
angle = math.atan2(dy, dx)
# Calculate the length of the shadow
shadow_length = TREE_HEIGHT / math.tan(angle)
# Draw the shadow
shadow_start = (tree_rect.centerx, tree_rect.centery)
shadow_end = (shadow_start[0] + shadow_length * math.cos(angle), shadow_start[1] + shadow_length * math.sin(angle))
pygame.draw.line(window, BLUE, shadow_start, shadow_end)
# Update the display
pygame.display.update()
# Increment the time of day
time_of_day += 1
# Wrap the time of day back to 0 at midnight
if time_of_day >= 1440:
time_of_day = 0
# Clean up Pygame
pygame.quit()
This program defines the tree and the sun, calculates the position of the sun based on the time of day, calculates the angle of the sun’s position relative to the tree, and then calculates the length and position of the shadow. It