animation.py 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # coding: utf-8
  2. import typing
  3. import pyglet
  4. import cocos
  5. class AnimatedInterface(object):
  6. def get_images_for_animation(self, animation_name: str) -> typing.List[pyglet.image.TextureRegion]:
  7. raise NotImplementedError()
  8. def get_inanimate_image(self) -> pyglet.image.TextureRegion:
  9. """
  10. Use this function to specify what image have to be used when animation is finished.
  11. :return: non inanimate pyglet.image.TextureRegion
  12. """
  13. raise NotImplementedError()
  14. def update_image(self, new_image: pyglet.image.TextureRegion):
  15. raise NotImplementedError()
  16. # TODO: regarder pyglet.image.Animation
  17. class Animate(cocos.actions.IntervalAction):
  18. def __init__(
  19. self,
  20. animation_name: str,
  21. duration: float,
  22. cycle_duration: float,
  23. direction: int=1,
  24. ):
  25. super().__init__()
  26. self.animation_name = animation_name
  27. self.duration = duration
  28. self.animation_images = [] # type: typing.List[pyglet.image.TextureRegion]
  29. self.last_step_elapsed = 0.0 # type: float
  30. self.step_interval = None # type: float
  31. self.cycle_duration = cycle_duration
  32. self.current_step = 0 # typ: int
  33. self.target = typing.cast(AnimatedInterface, self.target)
  34. self.direction = direction
  35. def __reversed__(self):
  36. return self.__class__(
  37. self.animation_name,
  38. self.duration,
  39. self.cycle_duration,
  40. self.direction * -1,
  41. )
  42. def start(self):
  43. super().start()
  44. self.animation_images = self.target.get_images_for_animation(self.animation_name)
  45. self.step_interval = self.cycle_duration / len(self.animation_images)
  46. def stop(self):
  47. self.target.update_image(self.target.get_inanimate_image())
  48. super().stop()
  49. def update(self, t):
  50. if not self.is_time_for_new_image():
  51. return
  52. self.current_step += self.direction
  53. try:
  54. new_image = self.animation_images[self.current_step]
  55. except IndexError:
  56. self.current_step = 0
  57. new_image = self.animation_images[0]
  58. self.target.update_image(new_image)
  59. self.last_step_elapsed = self._elapsed
  60. def is_time_for_new_image(self) -> bool:
  61. return self._elapsed - self.last_step_elapsed >= self.step_interval