python
import pygame
import math
import sys
# 初始化 Pygame
pygame.init()
# 设置屏幕尺寸
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Ball in Rotating Hexagon')
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 物理常数
gravity = 0.5
friction = 0.99
elasticity = 0.8
# 球的属性
ball_radius = 15
ball_pos = [width // 2, height // 2]
ball_vel = [0, 0]
# 六边形的属性
hex_center = [width // 2, height // 2]
hex_radius = 200
hex_angle = 0 # 旋转角度
hex_sides = 6
# 计算六边形顶点
def calculate_hexagon_points(center, radius, angle):
points = []
for i in range(hex_sides):
angle_rad = math.radians(angle + i * 360 / hex_sides)
x = center[0] + radius * math.cos(angle_rad)
y = center[1] + radius * math.sin(angle_rad)
points.append((x, y))
return points
# 检查球与六边形的碰撞
def check_collision(ball_pos, ball_radius, hex_points):
for i in range(len(hex_points)):
p1 = hex_points[i]
p2 = hex_points[i - 1]
normal = [p2[1] - p1[1], p1[0] - p2[0]]
length = math.hypot(normal[0], normal[1])
normal = [normal[0] / length, normal[1] / length]
ball_to_line = [ball_pos[0] - p1[0], ball_pos[1] - p1[1]]
distance = normal[0] * ball_to_line[0] + normal[1] * ball_to_line[1]
if distance < ball_radius:
# 计算反射向量
projection = [normal[0] * distance, normal[1] * distance]
ball_vel_normal = [normal[0] * ball_vel[0] + normal[1] * ball_vel[1]]
ball_vel_tangent = [ball_vel[0] - normal[0] * ball_vel_normal, ball_vel[1] - normal[1] * ball_vel_normal]
# 反射并应用弹性和摩擦力
ball_vel[0] = ball_vel_tangent[0] - normal[0] * 2 * ball_vel_normal * elasticity
ball_vel[1] = ball_vel_tangent[1] - normal[1] * 2 * ball_vel_normal * elasticity
# 调整球的位置以防止卡在墙壁内
ball_pos[0] += normal[0] * (ball_radius - distance) * 1.01
ball_pos[1] += normal[1] * (ball_radius - distance) * 1.01
# 主循环
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新球的速度和位置
ball_vel[1] += gravity
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
# 更新六边形的角度
hex_angle += 1
# 计算六边形的顶点
hex_points = calculate_hexagon_points(hex_center, hex_radius, hex_angle)
# 检查碰撞
check_collision(ball_pos, ball_radius, hex_points)
# 应用摩擦力
ball_vel[0] *= friction
ball_vel[1] *= friction
# 绘制背景
screen.fill(black)
# 绘制六边形
pygame.draw.polygon(screen, white, hex_points)
# 绘制球
pygame.draw.circle(screen, red, (int(ball_pos[0]), int(ball_pos[1])), ball_radius)
# 更新显示
pygame.display.flip()
# 控制帧率
clock.tick(60)
pygame.quit()
sys.exit()