main.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import pygame
  2. import pymunk.pygame_util
  3. from cv import recognize
  4. import cv2
  5. image = cv2.imread('falling_ball/image.png')
  6. RES = WIDTH, HEIGHT = 1200, 1000
  7. BALL_RADIUS = min(RES) / 30
  8. FPS = 60
  9. polys = recognize(image, RES)
  10. pygame.init()
  11. surface = pygame.display.set_mode(RES)
  12. clock = pygame.time.Clock()
  13. draw_options = pymunk.pygame_util.DrawOptions(surface)
  14. space = pymunk.Space()
  15. space.gravity = 0, 2000
  16. def create_ball(space, pos: tuple[int ,int]):
  17. ball_mass, ball_radius = 10, BALL_RADIUS
  18. ball_moment = pymunk.moment_for_circle(ball_mass, 0, ball_radius)
  19. ball_body = pymunk.Body(ball_mass, ball_moment)
  20. ball_body.position = pos
  21. ball_shape = pymunk.Circle(ball_body, ball_radius)
  22. ball_shape.elasticity = 0.2
  23. space.add(ball_body, ball_shape)
  24. def draw_by_lines(space, lines=list[tuple[int, int]]):
  25. for line_i in range(len(lines)):
  26. line = pymunk.Segment(space.static_body, lines[line_i], lines[(line_i+1)%4], 2)
  27. line.elasticity = 0.1
  28. space.add(line)
  29. for poly in polys:
  30. draw_by_lines(space, poly)
  31. circle_position = (350, BALL_RADIUS+1)
  32. while True:
  33. surface.fill(pygame.Color('white'))
  34. pygame.draw.circle(surface, pygame.Color('BLUE'), circle_position, BALL_RADIUS)
  35. for i in pygame.event.get():
  36. if i.type == pygame.KEYDOWN:
  37. if i.key == pygame.K_SPACE:
  38. create_ball(space, circle_position)
  39. if i.key == pygame.K_RIGHT:
  40. circle_position = (circle_position[0] + 10, circle_position[1])
  41. if i.key == pygame.K_LEFT:
  42. circle_position = (circle_position[0] - 10, circle_position[1])
  43. if i.type == pygame.QUIT:
  44. exit()
  45. space.step(1 / FPS)
  46. space.debug_draw(draw_options)
  47. pygame.display.flip()
  48. clock.tick(FPS)