main.py 1.8 KB

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