main.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import pygame
  2. import pymunk.pygame_util
  3. from cv import recognize
  4. import cv2
  5. image = cv2.imread('project/image.png')
  6. polys, shape = recognize(image)
  7. print(shape)
  8. RES = WIDTH, HEIGHT = shape[0], shape[1]
  9. FPS = 60
  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, 5
  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, 20)
  32. while True:
  33. surface.fill(pygame.Color('white'))
  34. pygame.draw.circle(surface, pygame.Color('BLUE'), circle_position, 5)
  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_LEFT:
  40. circle_position = (circle_position[0] + 10, circle_position[1])
  41. if i.key == pygame.K_RIGHT:
  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)