黎明zxc 发表于 2021-11-1 21:14:05

pygame编写的万有引力效果演示

pygame编写的万有引力效果演示

GMm_mian.py
import pygame
from GMm_ import *
pygame.init()

m1 =
m2 =
m3 =
m1 = speed_v(m2, m1-m2, m1-m2)
m3 = -speed_v(m2, m3-m2, m3-m2)

window = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
pygame.display.set_caption("star")

zhong = star(m1)
zhong1 = star(m2)
diqiou = star(m3)
stars_ = stars()
stars_.add(zhong)
stars_.add(zhong1)
stars_.add(diqiou)

window.fill((255, 255, 255))
FPS = 60
clock = pygame.time.Clock()
CREATE_ENEMY_EVENT = pygame.USEREVENT
pygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)


while True:

    clock.tick(FPS)

    pygame.draw.circle(window, (211, 211, 211), (zhong.x, zhong.y), 10)
    pygame.draw.circle(window, (0, 0, 0), (zhong.x, zhong.y), 5)
    pygame.draw.circle(window, (211, 211, 211), (zhong1.x, zhong1.y), 10)
    pygame.draw.circle(window, (0, 0, 0), (zhong1.x, zhong1.y), 5)
    pygame.draw.circle(window, (211, 211, 211), (diqiou.x, diqiou.y), 10)
    pygame.draw.circle(window, (0, 0, 0), (diqiou.x, diqiou.y), 5)

    pygame.display.update()

    pygame.draw.circle(window, (211, 211, 211), (zhong.x, zhong.y), 5)
    pygame.draw.circle(window, (211, 211, 211), (zhong1.x, zhong1.y), 5)
    pygame.draw.circle(window, (211, 211, 211), (diqiou.x, diqiou.y), 5)

    stars_.gravitation(zhong)
    stars_.gravitation(zhong1)
    stars_.gravitation(diqiou)

    for event in pygame.event.get():

      if event.type == pygame.QUIT:
            exit()

      elif event.type == CREATE_ENEMY_EVENT:
            print(zhong.speed_x, zhong.speed_y, zhong1.speed_x, zhong1.speed_y, diqiou.speed_x, diqiou.speed_y)

GMm_.py
G = 6.67e-11
WIN_WIDTH = 1000
WIN_HEIGHT = 600


def speed_v(M, x, y):
    return (G * M / ((x ** 2 + y ** 2) ** 0.5)) ** 0.5


class star:
    def __init__(self, li):
      self.m = li
      self.x = li
      self.y = li
      self.speed_x = li
      self.speed_y = li

    def motion(self):
      self.x += self.speed_x
      self.y += self.speed_y

    def acceleration(self, q_x, q_y):
      self.speed_x += q_x
      self.speed_y += q_y


class stars:
    def __init__(self):
      self.li = []

    def add(self, star_):
      self.li.append(star_)

    def gravitation(self, star_):
      a = 0
      b = 0
      for i in self.li:
            if i == star_:
                continue
            else:
                x = i.x - star_.x
                y = i.y - star_.y
                r = (x ** 2 + y ** 2) ** 0.5
                q = G * i.m / r ** 2
                a += x / r * q
                b += y / r * q
      star_.acceleration(a, b)
      star_.motion()

https://s3.bmp.ovh/imgs/2021/11/920e102d651fab8e.png

Python初学者8号 发表于 2021-11-2 09:18:10

牛蛙,哈哈,坐等更新三体
页: [1]
查看完整版本: pygame编写的万有引力效果演示