batframework 0.1.13__py3-none-any.whl → 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. batFramework/__init__.py +41 -46
  2. batFramework/action.py +42 -20
  3. batFramework/actionContainer.py +43 -4
  4. batFramework/animatedSprite.py +26 -20
  5. batFramework/camera.py +177 -47
  6. batFramework/constants.py +26 -51
  7. batFramework/cutscene.py +15 -15
  8. batFramework/cutsceneBlocks.py +11 -9
  9. batFramework/dynamicEntity.py +7 -6
  10. batFramework/easing.py +28 -23
  11. batFramework/entity.py +87 -49
  12. batFramework/enums.py +14 -0
  13. batFramework/fontManager.py +57 -0
  14. batFramework/gui/__init__.py +2 -2
  15. batFramework/gui/button.py +82 -31
  16. batFramework/gui/constraints.py +137 -104
  17. batFramework/gui/container.py +27 -28
  18. batFramework/gui/debugger.py +92 -42
  19. batFramework/gui/frame.py +15 -15
  20. batFramework/gui/image.py +37 -17
  21. batFramework/gui/indicator.py +18 -14
  22. batFramework/gui/interactiveWidget.py +11 -10
  23. batFramework/gui/label.py +60 -56
  24. batFramework/gui/layout.py +50 -47
  25. batFramework/gui/root.py +43 -30
  26. batFramework/gui/shape.py +34 -41
  27. batFramework/gui/slider.py +5 -0
  28. batFramework/gui/toggle.py +31 -27
  29. batFramework/gui/widget.py +148 -128
  30. batFramework/manager.py +18 -13
  31. batFramework/particles.py +16 -13
  32. batFramework/resourceManager.py +55 -0
  33. batFramework/scene.py +141 -83
  34. batFramework/sceneManager.py +21 -16
  35. batFramework/sprite.py +31 -0
  36. batFramework/stateMachine.py +1 -0
  37. batFramework/tileset.py +7 -9
  38. batFramework/time.py +61 -50
  39. batFramework/transition.py +20 -12
  40. batFramework/utils.py +2 -65
  41. batframework-1.0.1.dist-info/LICENCE +21 -0
  42. {batframework-0.1.13.dist-info → batframework-1.0.1.dist-info}/METADATA +3 -2
  43. batframework-1.0.1.dist-info/RECORD +48 -0
  44. {batframework-0.1.13.dist-info → batframework-1.0.1.dist-info}/WHEEL +1 -1
  45. batFramework/debugger.py +0 -48
  46. batframework-0.1.13.dist-info/RECORD +0 -43
  47. {batframework-0.1.13.dist-info → batframework-1.0.1.dist-info}/top_level.txt +0 -0
batFramework/scene.py CHANGED
@@ -1,14 +1,23 @@
1
1
  from __future__ import annotations
2
2
  import re
3
- from typing import TYPE_CHECKING,Any
3
+ from typing import TYPE_CHECKING, Any
4
+
4
5
  if TYPE_CHECKING:
5
6
  from .manager import Manager
7
+ from .sceneManager import SceneManager
6
8
  import pygame
7
9
  import batFramework as bf
8
10
 
9
11
 
10
12
  class Scene:
11
- def __init__(self, name, enable_alpha=True) -> None:
13
+ def __init__(self, name: str, enable_alpha: bool = True) -> None:
14
+ """
15
+ Initialize the Scene object.
16
+
17
+ Args:
18
+ name: Name of the scene.
19
+ enable_alpha (bool, optional): Enable alpha channel for the scene surfaces. Defaults to True.
20
+ """
12
21
  self._name = name
13
22
  self._active = False
14
23
  self._visible = False
@@ -16,71 +25,107 @@ class Scene:
16
25
  self._hud_entities: list[bf.Entity] = []
17
26
  self.manager: Manager | None = None
18
27
  self.actions: bf.ActionContainer = bf.ActionContainer()
19
- self.camera: bf.Camera = bf.Camera()
20
28
  self.scene_index = 0
21
- self.hud_camera: bf.Camera = bf.Camera()
22
- if enable_alpha:
23
- self.camera.surface = self.camera.surface.convert_alpha()
24
- self.hud_camera.surface = self.camera.surface.convert_alpha()
25
-
26
- self.camera.set_clear_color((0, 0, 0))
27
- self.hud_camera.set_clear_color((0, 0, 0, 0))
29
+ self.camera: bf.Camera = bf.Camera(convert_alpha=enable_alpha)
30
+ self.hud_camera: bf.Camera = bf.Camera(convert_alpha=enable_alpha)
28
31
 
29
- self.root : bf.Root = bf.Root()
32
+ self.root: bf.Root = bf.Root()
30
33
  self.root.set_center(*self.hud_camera.get_center())
31
34
  self.add_hud_entity(self.root)
32
35
  self.blit_calls = 0
33
36
 
34
- def set_scene_index(self,index):
37
+
38
+ def get_world_entity_count(self)->int:
39
+ return len(self._world_entities)
40
+
41
+
42
+ def get_hud_entity_count(self)->int:
43
+ return len(self._world_entities) + self.root.count_children_recursive() -1
44
+
45
+
46
+ def set_scene_index(self, index: int):
47
+ """Set the scene index."""
35
48
  self.scene_index = index
36
49
 
37
- def get_scene_index(self):
50
+ def get_scene_index(self) -> int:
51
+ """Get the scene index."""
38
52
  return self.scene_index
39
53
 
40
- def set_sharedVar(self, name, value)->bool:
41
- if not self.manager : return False
54
+ def set_sharedVar(self, name: str, value: Any) -> bool:
55
+ """
56
+ Set a shared variable in the manager.
57
+
58
+ Args:
59
+ name: Name of the shared variable.
60
+ value: Value to set.
61
+
62
+ Returns:
63
+ bool: True if setting was successful, False otherwise.
64
+ """
65
+ if not self.manager:
66
+ return False
42
67
  return self.manager.set_sharedVar(name, value)
43
68
 
44
- def get_sharedVar(self, name)->Any:
45
- if not self.manager : return False
69
+ def get_sharedVar(self, name: str) -> Any:
70
+ """
71
+ Get a shared variable from the manager.
72
+
73
+ Args:
74
+ name: Name of the shared variable.
75
+
76
+ Returns:
77
+ Any: Value of the shared variable.
78
+ """
79
+ if not self.manager:
80
+ return False
46
81
  return self.manager.get_sharedVar(name)
47
82
 
48
83
  def do_when_added(self):
49
84
  pass
50
85
 
51
- def set_clear_color(self, color: pygame.Color|tuple):
86
+ def set_clear_color(self, color: pygame.Color | tuple):
87
+ """Set the clear color for the camera."""
52
88
  self.camera.set_clear_color(color)
53
- # self.hud_camera.set_clear_color(color)
54
89
 
55
90
  def set_manager(self, manager_link: Manager):
91
+ """Set the manager link for the scene."""
56
92
  self.manager = manager_link
93
+ self.manager.update_scene_states()
57
94
 
58
95
  def set_visible(self, value: bool):
96
+ """Set the visibility of the scene."""
59
97
  self._visible = value
60
- if self.manager : self.manager.update_scene_states()
98
+ if self.manager:
99
+ self.manager.update_scene_states()
61
100
 
62
101
  def set_active(self, value):
102
+ """Set the activity of the scene."""
63
103
  self._active = value
64
- if self.manager : self.manager.update_scene_states()
104
+ if self.manager:
105
+ self.manager.update_scene_states()
65
106
 
66
107
  def is_active(self) -> bool:
108
+ """Check if the scene is active."""
67
109
  return self._active
68
110
 
69
111
  def is_visible(self) -> bool:
112
+ """Check if the scene is visible."""
70
113
  return self._visible
71
114
 
72
115
  def get_name(self) -> str:
116
+ """Get the name of the scene."""
73
117
  return self._name
74
118
 
75
119
  def add_world_entity(self, *entity: bf.Entity):
120
+ """Add world entities to the scene."""
76
121
  for e in entity:
77
- if e not in self._world_entities:
78
-
79
- self._world_entities.append(e)
80
- e.parent_scene = self
81
- e.do_when_added()
122
+ self._world_entities.append(e)
123
+ e.parent_scene = self
124
+ e.do_when_added()
125
+ self.sort_entities()
82
126
 
83
127
  def remove_world_entity(self, *entity: bf.Entity):
128
+ """Remove world entities from the scene."""
84
129
  for e in entity:
85
130
  if e not in self._world_entities:
86
131
  return False
@@ -90,13 +135,16 @@ class Scene:
90
135
  return True
91
136
 
92
137
  def add_hud_entity(self, *entity: bf.Entity):
138
+ """Add HUD entities to the scene."""
93
139
  for e in entity:
94
- if e not in self._hud_entities:
95
- self._hud_entities.append(e)
96
- e.parent_scene = self
97
- e.do_when_added()
140
+ self._hud_entities.append(e)
141
+ e.parent_scene = self
142
+ e.do_when_added()
143
+ self.sort_entities()
144
+ return True
98
145
 
99
146
  def remove_hud_entity(self, *entity: bf.Entity):
147
+ """Remove HUD entities from the scene."""
100
148
  for e in entity:
101
149
  if e in self._hud_entities:
102
150
  e.do_when_removed()
@@ -104,30 +152,44 @@ class Scene:
104
152
  self._hud_entities.remove(e)
105
153
 
106
154
  def add_action(self, *action):
155
+ """Add actions to the scene."""
107
156
  self.actions.add_action(*action)
108
157
 
109
158
  def get_by_tags(self, *tags):
110
- res = [
159
+ """Get entities by their tags."""
160
+ res = [
111
161
  entity
112
162
  for entity in self._world_entities + self._hud_entities
113
- if any(entity.has_tag(t) for t in tags)
163
+ if any(entity.has_tags(t) for t in tags)
114
164
  ]
115
- res.extend(
116
- list(self.root.get_by_tags(*tags))
117
- )
165
+ res.extend(list(self.root.get_by_tags(*tags)))
118
166
  return res
119
167
 
120
168
  def get_by_uid(self, uid) -> bf.Entity | None:
121
- return next(
122
- (
123
- entity
124
- for entity in self._world_entities + self._hud_entities
125
- if entity.uid == uid
126
- ),
127
- None,
128
- )
129
- # TODO
130
- # ADD FOR WIDGETS TOO TOO
169
+ """Get an entity by its unique identifier."""
170
+ res = self._find_entity_by_uid(uid, self._world_entities + self._hud_entities)
171
+ if res is None:
172
+ res = self._recursive_search_by_uid(uid, self.root)
173
+ return res
174
+
175
+ def _find_entity_by_uid(self, uid, entities) -> bf.Entity | None:
176
+ """Search for entity by uid in a list of entities."""
177
+ for entity in entities:
178
+ if entity.uid == uid:
179
+ return entity
180
+ return None
181
+
182
+ def _recursive_search_by_uid(self, uid, widget) -> bf.Entity | None:
183
+ """Recursively search for entity by uid in the widget's children."""
184
+ if widget.uid == uid:
185
+ return widget
186
+
187
+ for child in widget.children:
188
+ res = self._recursive_search_by_uid(uid, child)
189
+ if res is not None:
190
+ return res
191
+
192
+ return None
131
193
 
132
194
  # called before process event
133
195
  def do_early_process_event(self, event: pygame.Event) -> bool:
@@ -140,20 +202,19 @@ class Scene:
140
202
  Propagates event to child events. Calls early process event first, if returns False then stops. Processes scene's action_container, then custom do_handle_event function.
141
203
  Finally resets the action_container, and propagates to all child entities. if any of them returns True, the propagation is stopped.
142
204
  """
143
- if self.get_sharedVar("in_transition"):
144
- return
205
+
145
206
  if self.do_early_process_event(event):
146
207
  return
147
208
  self.actions.process_event(event)
148
209
  self.do_handle_actions()
149
210
  self.do_handle_event(event)
150
- for entity in self._world_entities + self._hud_entities:
211
+ for entity in self._hud_entities + self._world_entities:
151
212
  if entity.process_event(event):
152
213
  break
153
-
154
- self.actions.reset()
155
214
 
156
- def do_handle_actions(self)->None:
215
+
216
+ def do_handle_actions(self) -> None:
217
+ """Handle actions within the scene."""
157
218
  pass
158
219
 
159
220
  def do_handle_event(self, event: pygame.Event):
@@ -161,13 +222,16 @@ class Scene:
161
222
  pass
162
223
 
163
224
  def update(self, dt):
225
+ """Update the scene. Do NOT override"""
164
226
  for entity in self._world_entities + self._hud_entities:
165
227
  entity.update(dt)
166
228
  self.do_update(dt)
167
229
  self.camera.update(dt)
168
230
  self.hud_camera.update(dt)
231
+ self.actions.reset()
169
232
 
170
233
  def do_update(self, dt):
234
+ """Specific update within the scene."""
171
235
  pass
172
236
 
173
237
  def debug_entity(self, entity: bf.Entity, camera: bf.Camera):
@@ -176,56 +240,52 @@ class Scene:
176
240
  return
177
241
  # print(entity,entity.visible)
178
242
  for data in entity.get_bounding_box():
179
- if isinstance(data,pygame.FRect):
243
+ if isinstance(data, pygame.FRect):
180
244
  rect = data
181
- color = entity._debug_color
245
+ color = entity.debug_color
182
246
  else:
183
247
  rect = data[0]
184
248
  color = data[1]
185
- if not isinstance(color,pygame.Color): color = pygame.Color(color)
249
+ # if not isinstance(color, pygame.Color):
250
+ # color = pygame.Color(color)
186
251
 
187
- pygame.draw.rect(camera.surface, color , camera.transpose(rect), 1)
252
+ pygame.draw.rect(camera.surface, color, camera.transpose(rect), 1)
188
253
 
189
- def draw(self, surface: pygame.Surface):
190
- self._world_entities.sort(key=lambda e: (e.z_depth, e.render_order))
191
- self._hud_entities.sort(key=lambda e: (e.z_depth, e.render_order))
254
+ def sort_entities(self) -> None:
255
+ """Sort entities within the scene based on their rendering order."""
256
+ self._world_entities.sort(key=lambda e: e.render_order)
257
+ self._hud_entities.sort(key=lambda e: e.render_order)
192
258
 
259
+ def draw(self, surface: pygame.Surface):
193
260
  total_blit_calls = 0
261
+ if not self.manager : return
194
262
  self.camera.clear()
195
263
  self.hud_camera.clear()
196
264
 
197
- debug_2_or_3 = self.manager and self.manager._debugging in [2, 3]
198
- debug_3 = debug_2_or_3 and self.manager._debugging == 3
265
+ show_outlines = self.manager._debugging in [2, 3]
266
+ show_only_visible_outlines = self.manager._debugging != 3
199
267
 
200
- total_blit_calls += sum(
201
- entity.draw(self.camera) for entity in self._world_entities
202
- if not (debug_2_or_3 and ((debug_3 and not entity.visible) or not debug_3))
203
- )
204
268
 
205
- if debug_2_or_3:
206
- for entity in self._world_entities:
207
- if debug_3 and not entity.visible:
208
- continue
209
- self.debug_entity(entity, self.camera)
269
+ # draw all world entities
270
+ total_blit_calls += sum(entity.draw(self.camera) for entity in self._world_entities)
210
271
 
211
- total_blit_calls += sum(
212
- entity.draw(self.hud_camera) for entity in self._hud_entities
213
- if not (debug_2_or_3 and ((debug_3 and not entity.visible) or not debug_3))
214
- )
272
+ #
273
+ if show_outlines:
274
+ [self.debug_entity(entity, self.camera) for entity\
275
+ in self._world_entities if not show_only_visible_outlines\
276
+ or (show_only_visible_outlines and entity.visible)]
215
277
 
216
- if debug_2_or_3:
217
- for entity in self._hud_entities:
218
- if debug_3 and not entity.visible:
219
- continue
220
- self.debug_entity(entity, self.hud_camera)
278
+ total_blit_calls += sum(entity.draw(self.hud_camera) for entity in self._hud_entities)
221
279
 
280
+ if show_outlines:
281
+ [self.debug_entity(entity, self.hud_camera) for entity\
282
+ in self._hud_entities if not show_only_visible_outlines\
283
+ or (show_only_visible_outlines and entity.visible)]
222
284
 
223
285
  self.do_early_draw(surface)
224
286
  self.camera.draw(surface)
225
- self.do_post_world_draw(surface)
226
287
  self.hud_camera.draw(surface)
227
288
  self.do_final_draw(surface)
228
-
229
289
  self.blit_calls = total_blit_calls
230
290
 
231
291
  def do_early_draw(self, surface: pygame.Surface):
@@ -242,10 +302,8 @@ class Scene:
242
302
  self.set_visible(True)
243
303
  self.root.build()
244
304
 
245
-
246
305
  def on_exit(self):
247
- self.root.focus_on(None)
248
- self.root.hover = None
306
+ self.root.reset()
249
307
  self.set_active(False)
250
308
  self.set_visible(False)
251
309
  self.actions.hard_reset()
@@ -2,18 +2,17 @@ import batFramework as bf
2
2
  import pygame
3
3
 
4
4
 
5
-
6
5
  class SceneManager:
7
6
  def __init__(self, *initial_scenes: bf.Scene) -> None:
8
7
  self._debugging = 0
9
8
  self.sharedVarDict = {}
10
9
 
11
10
  self.transitions: list[bf.BaseTransition] = []
12
- self.set_sharedVar("is_debugging_func", lambda: self._debugging)
11
+ self.set_sharedVar("debugging_mode",self._debugging)
13
12
  self.set_sharedVar("in_cutscene", False)
14
13
 
15
14
  self._scenes: list[bf.Scene] = list(initial_scenes)
16
- for index,s in enumerate(self._scenes):
15
+ for index, s in enumerate(self._scenes):
17
16
  s.set_manager(self)
18
17
  s.set_scene_index(index)
19
18
  s.do_when_added()
@@ -22,7 +21,7 @@ class SceneManager:
22
21
 
23
22
  def print_status(self):
24
23
  print("-" * 40)
25
- print([(s._name, s._active, s._visible,s.scene_index) for s in self._scenes])
24
+ print([(s._name, s._active, s._visible, s.scene_index) for s in self._scenes])
26
25
  print(f"[Debugging] = {self._debugging}")
27
26
  print("---SHARED VARIABLES---")
28
27
  _ = [
@@ -39,11 +38,11 @@ class SceneManager:
39
38
  if name not in self.sharedVarDict:
40
39
  return None
41
40
  return self.sharedVarDict[name]
42
-
43
- def get_current_scene_name(self)-> str:
44
- return self._scenes[0].name
45
-
46
- def get_current_scene(self)->bf.Scene:
41
+
42
+ def get_current_scene_name(self) -> str:
43
+ return self._scenes[0].get_name()
44
+
45
+ def get_current_scene(self) -> bf.Scene:
47
46
  return self._scenes[0]
48
47
 
49
48
  def update_scene_states(self):
@@ -72,20 +71,25 @@ class SceneManager:
72
71
 
73
72
  def transition_to_scene(self, dest_scene_name, transition, **kwargs):
74
73
  self.set_scene(dest_scene_name)
75
-
76
- def set_scene(self, name,index=0):
77
- if len(self._scenes)==0 or not self.has_scene(name) or index>=len(self._scenes):return
78
74
 
75
+ def set_scene(self, name, index=0):
79
76
  target_scene = self.get_scene(name)
77
+ if (
78
+ len(self._scenes) == 0
79
+ or not target_scene
80
+ or index >= len(self._scenes)
81
+ or index < 0
82
+ ):
83
+ return
84
+
80
85
  old_scene = self._scenes[index]
81
- #switch
86
+ # switch
82
87
  old_scene.on_exit()
83
88
  self.remove_scene(name)
84
- self._scenes.insert(index,target_scene)
85
- _ = [s.set_scene_index(i) for i,s in enumerate(self._scenes)]
89
+ self._scenes.insert(index, target_scene)
90
+ _ = [s.set_scene_index(i) for i, s in enumerate(self._scenes)]
86
91
  target_scene.on_enter()
87
92
 
88
-
89
93
  def process_event(self, event: pygame.Event):
90
94
  keys = pygame.key.get_pressed()
91
95
  if (
@@ -94,6 +98,7 @@ class SceneManager:
94
98
  and event.key == pygame.K_d
95
99
  ):
96
100
  self._debugging = (self._debugging + 1) % 4
101
+ self.set_sharedVar("debugging_mode",self._debugging)
97
102
  return
98
103
  if (
99
104
  keys[pygame.K_LCTRL]
batFramework/sprite.py ADDED
@@ -0,0 +1,31 @@
1
+ import batFramework as bf
2
+ import pygame
3
+ from typing import Self
4
+
5
+ class Sprite(bf.DynamicEntity):
6
+ def __init__(
7
+ self,
8
+ data: pygame.Surface | str,
9
+ size: None | tuple[int, int] = None,
10
+ convert_alpha: bool = True,
11
+ ):
12
+ self.original_surface = None
13
+ super().__init__(convert_alpha=convert_alpha)
14
+ if data:
15
+ self.set_image(data, size)
16
+
17
+ def set_image(
18
+ self, data: pygame.Surface | str, size: None | tuple[int, int] = None
19
+ ):
20
+ if isinstance(data, str):
21
+ tmp = bf.ResourceManager().get_image(data,self.convert_alpha)
22
+ self.original_surface = tmp
23
+ elif isinstance(data, pygame.Surface):
24
+ self.original_surface = data
25
+ if self.convert_alpha:
26
+ self.original_surface = self.original_surface.convert_alpha()
27
+ if not size:
28
+ size = self.original_surface.get_size()
29
+ self.surface = pygame.transform.scale(self.original_surface, size)
30
+ self.rect = self.surface.get_frect(center=self.rect.center)
31
+
@@ -44,6 +44,7 @@ class StateMachine:
44
44
  self.current_state.on_exit()
45
45
  self.current_state = self.states[state_name]
46
46
  self.current_state.on_enter()
47
+
47
48
  def get_current_state(self) -> State:
48
49
  return self.current_state
49
50
 
batFramework/tileset.py CHANGED
@@ -1,15 +1,15 @@
1
- import pygame
1
+ import pygame
2
2
  from .utils import Utils
3
3
 
4
+
4
5
  class Tileset:
5
6
  _tilesets = {}
6
7
  _flip_cache = {} # {"tileset":tileset,"index","flipX","flipY"}
7
8
 
8
- def __init__(self, source: pygame.Surface|str, tilesize) -> None:
9
-
10
- if isinstance(source,str):
9
+ def __init__(self, source: pygame.Surface | str, tilesize) -> None:
10
+ if isinstance(source, str):
11
11
  source = pygame.image.load(Utils.get_path(source)).convert_alpha()
12
-
12
+
13
13
  self.tile_dict = {}
14
14
  self.surface = source
15
15
  self.tile_size = tilesize
@@ -48,13 +48,11 @@ class Tileset:
48
48
  return self.tile_dict[(x, y)]
49
49
 
50
50
  @staticmethod
51
- def load_tileset(path: str, name: str, tilesize)->"Tileset":
51
+ def load_tileset(path: str, name: str, tilesize) -> "Tileset":
52
52
  if name in Tileset._tilesets:
53
53
  return Tileset._tilesets[name]
54
54
  else:
55
- img = pygame.image.load(
56
- Utils.get_path(path)
57
- ).convert_alpha()
55
+ img = pygame.image.load(Utils.get_path(path)).convert_alpha()
58
56
  tileset = Tileset(img, tilesize)
59
57
  Tileset._tilesets[name] = tileset
60
58
  return tileset
batFramework/time.py CHANGED
@@ -1,74 +1,85 @@
1
1
  import pygame
2
2
  import batFramework as bf
3
+ from typing import Self
3
4
 
4
5
  class Timer:
5
- _highest_count = 0
6
- def __init__(self, name=None, duration=1000, loop=False, end_callback=None,reusable:bool=False):
7
- # Initialize timer properties
8
- self.start_time = None
9
- self.stopped = True
10
- self.name = name if name is not None else self._highest_count
11
- Timer._highest_count += 1
12
- self.duration = duration
13
- self.loop = loop
14
- self.elapsed_progress = 0.0
6
+ _count :int = 0
7
+ def __init__(self,duration:int,end_callback,loop:bool=False)->None:
8
+ self.name = Timer._count
9
+ Timer._count+=1
15
10
  self.end_callback = end_callback
16
- self.reusable:bool = reusable
17
- def start(self):
18
- # Start the timer and set the start time
19
- if self.start_time is None:
20
- Time().add_timer(self)
21
-
22
- self.start_time = pygame.time.get_ticks()
23
- self.stopped = False
24
- self.elapsed_progress = 0.0
25
-
26
- def update(self):
27
- if self.stopped : return False
28
- current_time = pygame.time.get_ticks()
29
- if self.elapsed_progress < 1:
30
- # Calculate elapsed progress
31
- self.elapsed_progress = (current_time - self.start_time) / self.duration
32
- if self.elapsed_progress >= 1:
33
- # Timer has completed
34
- self.end()
35
- return True
36
- elif self.loop:
37
- # If looping, restart the timer
38
- self.start()
39
- return False
11
+ self.duration : int = duration
12
+ self.paused : bool = False
13
+ self.elapsed_time : int = -1
14
+ self.over : bool = False
15
+ self.do_delete:bool = False
16
+ self.is_looping :bool = loop
40
17
 
41
- def stop(self):
42
- # Stop the timer
43
- self.stopped = True
18
+ def stop(self)->Self:
19
+ self.elapsed_time =-1
20
+ self.over = False
21
+ self.paused = False
22
+ return self
23
+
24
+ def start(self)->Self:
25
+ if self.elapsed_time >= 0 : return self
26
+ self.elapsed_time = 0
27
+ self.paused = False
28
+ self.over = False
29
+ bf.TimeManager().add_timer(self)
30
+ return self
31
+
32
+ def pause(self)->Self:
33
+ self.paused = True
34
+ return self
44
35
 
36
+ def resume(self)->Self:
37
+ self.paused = False
38
+ return self
39
+ def delete(self)->Self:
40
+ self.do_delete = True
41
+ return self
42
+ def get_progression(self)->float:
43
+ if self.elapsed_time < 0 : return 0
44
+ if self.elapsed_time >= self.duration: return 1
45
+ return self.elapsed_time / self.duration
46
+
47
+ def update(self,dt)->None:
48
+ if self.elapsed_time < 0 or self.paused: return
49
+ self.elapsed_time += dt
50
+ # print("update :",self.elapsed_time,self.duration)
51
+ if self.get_progression() == 1:
52
+ self.end()
53
+
45
54
  def end(self):
46
- self.elapsed_progress = 1
47
- self.stopped = False
48
- if self.end_callback:
49
- self.end_callback()
55
+ print("END")
56
+ self.end_callback()
57
+ if self.is_looping:
58
+ self.elapsed_time = -1
59
+ self.start()
60
+ return
61
+
62
+ self.over = True
50
63
 
51
- def ended(self):
52
- if self.start_time is None:
53
- return False
54
- return (not self.loop) and (self.elapsed_progress >= 1) and (not self.stopped) and not self.reusable
64
+ def has_ended(self)->bool:
65
+ return self.over or self.do_delete
55
66
 
56
67
 
57
- class Time(metaclass=bf.Singleton):
68
+ class TimeManager(metaclass=bf.Singleton):
58
69
  def __init__(self):
59
- # Initialize the Time class with a dictionary of timers
70
+ # Initialize the TimeManager class with a dictionary of timers
60
71
  self.timers = {}
61
72
 
62
73
  def add_timer(self, timer):
63
74
  # Add a timer to the dictionary
64
75
  self.timers[timer.name] = timer
65
76
 
66
- def update(self):
77
+ def update(self,dt):
67
78
  # Update all timers and remove completed ones
68
79
  for timer in list(self.timers.values()):
69
- timer.update()
80
+ timer.update(dt)
70
81
 
71
- to_remove = [name for name, timer in self.timers.items() if timer.ended()]
82
+ to_remove = [name for name, timer in self.timers.items() if timer.has_ended()]
72
83
 
73
84
  for name in to_remove:
74
85
  # print(self.timers.pop(name).name,"removed !")