Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- import sys, pygame
- from pygame.locals import *
- import math
- class Point(object):
- def __init__(self, x=0, y=0):
- self.x = x
- self.y = y
- class Body(object):
- def __init__(self, mass=1, pos=(0, 0), vel=Point(0, 0), radius=0):
- self.pos = pos
- self.radius = radius
- self.acc = Point(0, 0)
- self.vel = vel
- self.mass = mass
- def move(self, dx, dy):
- self.pos.x += dx
- self.pos.y += dy
- def resetForce(self):
- self.acc = Point(0, 0)
- def applyForce(self, force):
- self.acc.x += force.x / self.mass
- self.acc.y += force.y / self.mass
- def update(self):
- self.vel.x += self.acc.x# * 10000
- self.vel.y += self.acc.y# * 10000
- self.move(self.vel.x, self.vel.y)
- def draw(self, screen, color=(0, 0, 0), width=1):
- pygame.draw.circle(screen, color, (int(self.pos.x), int(self.pos.y)), self.radius, width)
- def getEvents():
- for event in pygame.event.get():
- if event.type == KEYDOWN:
- if event.key == K_UP:
- planetC.move(0, -5)
- if event.key == K_DOWN:
- planetC.move(0, 5)
- if event.key == K_LEFT:
- planetC.move(-5, 0)
- if event.key == K_RIGHT:
- planetC.move(5, 0)
- if event.key == ord('q'):
- return False
- return True
- def getGravity(bodyA, bodyB):
- dx = bodyA.pos.x - bodyB.pos.x
- dy = bodyA.pos.y - bodyB.pos.y
- d = dx**2 + dy**2
- if d == 0:
- return Point(0, 0)
- else:
- f = ((6.673*(10**-11)) * bodyA.mass * bodyB.mass) / d
- a = math.atan2(dy, dx)
- fx = f * -math.cos(a)
- fy = f * -math.sin(a)
- #print('dx: ' + str(int(dx)) + '; dy: ' + str(int(dy)))
- #print('fx: ' + str(int(fx)) + '; fy: ' + str(int(fy)))
- #print('f: ' + str(int(f)) + '; a: ' + str(int(a * (math.pi/180.0))))
- return Point(fx, fy)
- def invertForce(force):
- return Point(-force.x, -force.y)
- pygame.init()
- screen = pygame.display.set_mode((600, 400))
- pygame.display.set_caption('Gravity simulator')
- pygame.mouse.set_visible(0)
- clock = pygame.time.Clock()
- planetA = Body(10**8, Point(200, 200), Point(0, 0.065), 25)
- planetB = Body(10**8, Point(400, 200), Point(0, -0.065), 25)
- planetC = Body(5*10**9, Point(300, 200), Point(0, 0), 10)
- running = True
- while running:
- running = getEvents()
- for i in range(1, 500):
- planetA.resetForce()
- planetB.resetForce()
- planetC.resetForce()
- f = getGravity(planetA, planetB)
- planetA.applyForce(f)
- planetB.applyForce(invertForce(f))
- f = getGravity(planetC, planetA)
- planetC.applyForce(f)
- planetA.applyForce(invertForce(f))
- f = getGravity(planetC, planetB)
- planetC.applyForce(f)
- planetB.applyForce(invertForce(f))
- planetA.update()
- planetB.update()
- planetC.update()
- pygame.draw.rect(screen, (0, 0, 0), pygame.Rect(0, 0, 600, 400))
- planetA.draw(screen, (255, 0, 0), 5)
- planetB.draw(screen, (0, 255, 0), 5)
- planetC.draw(screen, (0, 0, 255), 3)
- clock.tick(15)
- pygame.display.flip()
- print('Terminating')
Add Comment
Please, Sign In to add comment