import pygame
pygame.init()
screen = pygame.display.set_mode((1280,720))
clock = pygame.time.Clock()
running = True
class Ball:
def __init__(self,p,v,m) -> None:
self.p = p
self.m = m
self.v = v
self.a = [0,0]
def force(self, li):
self.a[0] = li[0] / self.m
self.a[1] = li[1] / self.m
self.v[0] += self.a[0]
self.v[1] += self.a[1]
self.p[0] = self.p[0] + self.v[0]
self.p[1] = self.p[1] + self.v[1]
def draw(self,surface:pygame.Surface):
pygame.draw.circle(surface,"red",(self.p[0],self.p[1]),8)
balls = []
while running:
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
qq = pygame.mouse.get_pos()
xx = qq[0]
yy = qq[1]
if event.type == pygame.MOUSEBUTTONUP:
ww = pygame.mouse.get_pos()
sudo = (((ww[0]-xx)**2 + (ww[1]-yy)**2)**0.5)*0.01
ball = Ball(
p = [xx,yy],
v = [sudo*((ww[0]-xx)/((ww[0]-xx)**2 + (ww[1]-yy)**2)**0.5),sudo*((ww[1]-yy)/((ww[0]-xx)**2 + (ww[1]-yy)**2)**0.5)],
m = 100
)
balls.append(ball)
for ball in balls:
r_2 = (640-ball.p[0])**2 + (360-ball.p[1])**2
li_2 = 5000*ball.m/r_2
li = [li_2*(640-ball.p[0])/r_2**0.5,li_2*(360-ball.p[1])/r_2**0.5]
ball.force(li)
screen.fill('black')
for ball in balls:
ball.draw(screen)
pygame.draw.circle(screen,"red",(640,360),8)
pygame.display.update()
pygame.quit()
python Pygame 根据万有引力模拟行星绕恒星运动
最新推荐文章于 2024-08-28 16:14:15 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)