Verlet integrator, to deal with an argument from the pub.

main.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # Import the pygame library and initialise the game engine
  2. import pygame
  3. import numpy as np
  4. from verlet import Ball, Spring
  5. pygame.init()
  6. # Initialize Pygame
  7. SIZE = (800, 800)
  8. WHITE = (255, 255, 255)
  9. screen = pygame.display.set_mode(SIZE)
  10. pygame.display.set_caption("Patrick")
  11. running = True
  12. clock = pygame.time.Clock()
  13. data = []
  14. def physics():
  15. for ball in balls:
  16. ball.update()
  17. for spring in springs:
  18. spring.update()
  19. def draw():
  20. for ball in balls:
  21. ball.render(screen)
  22. for spring in springs:
  23. spring.render(screen)
  24. def boost():
  25. vector = springs[0].b.pos - springs[0].a.pos
  26. length = springs[0].compute_length()
  27. vector /= length
  28. norm = np.array([vector[1], -vector[0]])
  29. balls[1].velocity += norm * .5
  30. def modulate():
  31. x = pygame.mouse.get_pos()[0]
  32. fraction = x / SIZE[0]
  33. springs[-1].k = fraction*3 + 0.05
  34. springs[-2].k = fraction*3 + 0.05
  35. pygame.draw.rect(screen, (30, 30, 30), (0, 0, x, SIZE[1]))
  36. if __name__ == '__main__':
  37. balls = [Ball(0., 0., fixed=True),
  38. Ball(0., 100.),
  39. Ball(20., 120.),
  40. Ball(-20., 120.),
  41. Ball(0., 80.),
  42. Ball(40., 100.),
  43. Ball(-40., 100.)]
  44. springs = [
  45. Spring(balls[0], balls[1], length=100, k=3),
  46. Spring(balls[1], balls[2], k=5),
  47. Spring(balls[1], balls[3], k=5),
  48. Spring(balls[2], balls[3], k=5),
  49. Spring(balls[1], balls[4], k=5),
  50. Spring(balls[2], balls[4], k=5),
  51. Spring(balls[3], balls[4], k=5),
  52. Spring(balls[3], balls[5], k=.1, color=(255, 0, 0)),
  53. Spring(balls[2], balls[6], k=.1, color=(255, 0, 0))
  54. ]
  55. while running:
  56. for event in pygame.event.get():
  57. if event.type == pygame.QUIT:
  58. running = False
  59. screen.fill((0, 0, 0))
  60. physics()
  61. physics()
  62. boost()
  63. modulate()
  64. draw()
  65. pygame.display.flip()
  66. clock.tick(60)
  67. pygame.quit()