doku2d 0.1.0__tar.gz

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 (96) hide show
  1. doku2d-0.1.0/LICENSE +21 -0
  2. doku2d-0.1.0/PKG-INFO +95 -0
  3. doku2d-0.1.0/README.md +55 -0
  4. doku2d-0.1.0/doku2d/__init__.py +18 -0
  5. doku2d-0.1.0/doku2d/__main__.py +4 -0
  6. doku2d-0.1.0/doku2d/animation/__init__.py +8 -0
  7. doku2d-0.1.0/doku2d/animation/animatedsprite.py +302 -0
  8. doku2d-0.1.0/doku2d/animation/animationplayer.py +131 -0
  9. doku2d-0.1.0/doku2d/animation/motion.py +39 -0
  10. doku2d-0.1.0/doku2d/animation/tween.py +143 -0
  11. doku2d-0.1.0/doku2d/animation/values.py +82 -0
  12. doku2d-0.1.0/doku2d/assets/LICENSE +21 -0
  13. doku2d-0.1.0/doku2d/assets/fonts/NotoSans.ttf +0 -0
  14. doku2d-0.1.0/doku2d/assets/fonts/OFL.txt +93 -0
  15. doku2d-0.1.0/doku2d/assets/fonts/README.md +7 -0
  16. doku2d-0.1.0/doku2d/audio/__init__.py +4 -0
  17. doku2d-0.1.0/doku2d/audio/audio.py +277 -0
  18. doku2d-0.1.0/doku2d/audio/mixer.py +95 -0
  19. doku2d-0.1.0/doku2d/cli/__init__.py +136 -0
  20. doku2d-0.1.0/doku2d/cli/template/.gitignore +4 -0
  21. doku2d-0.1.0/doku2d/cli/template/README.md +21 -0
  22. doku2d-0.1.0/doku2d/cli/template/assets/level.tmj +583 -0
  23. doku2d-0.1.0/doku2d/cli/template/assets/player.png +0 -0
  24. doku2d-0.1.0/doku2d/cli/template/assets/tiles.png +0 -0
  25. doku2d-0.1.0/doku2d/cli/template/doku2d.toml +16 -0
  26. doku2d-0.1.0/doku2d/cli/template/main.py +100 -0
  27. doku2d-0.1.0/doku2d/cli/template/pyproject.toml +5 -0
  28. doku2d-0.1.0/doku2d/cli/template/requirements.txt +1 -0
  29. doku2d-0.1.0/doku2d/config.py +85 -0
  30. doku2d-0.1.0/doku2d/core/__init__.py +11 -0
  31. doku2d-0.1.0/doku2d/core/canvas.py +62 -0
  32. doku2d-0.1.0/doku2d/core/debug.py +233 -0
  33. doku2d-0.1.0/doku2d/core/entity.py +184 -0
  34. doku2d-0.1.0/doku2d/core/game.py +774 -0
  35. doku2d-0.1.0/doku2d/core/input.py +304 -0
  36. doku2d-0.1.0/doku2d/core/resource.py +78 -0
  37. doku2d-0.1.0/doku2d/core/scope.py +72 -0
  38. doku2d-0.1.0/doku2d/core/signal.py +58 -0
  39. doku2d-0.1.0/doku2d/core/singleton.py +56 -0
  40. doku2d-0.1.0/doku2d/core/storage.py +77 -0
  41. doku2d-0.1.0/doku2d/gui/__init__.py +8 -0
  42. doku2d-0.1.0/doku2d/gui/base.py +245 -0
  43. doku2d-0.1.0/doku2d/gui/buttons.py +235 -0
  44. doku2d-0.1.0/doku2d/gui/choices.py +539 -0
  45. doku2d-0.1.0/doku2d/gui/clipboard.py +18 -0
  46. doku2d-0.1.0/doku2d/gui/control.py +13 -0
  47. doku2d-0.1.0/doku2d/gui/effects.py +62 -0
  48. doku2d-0.1.0/doku2d/gui/graphics.py +80 -0
  49. doku2d-0.1.0/doku2d/gui/layout.py +177 -0
  50. doku2d-0.1.0/doku2d/gui/range.py +108 -0
  51. doku2d-0.1.0/doku2d/gui/ranges.py +325 -0
  52. doku2d-0.1.0/doku2d/gui/runtime.py +212 -0
  53. doku2d-0.1.0/doku2d/gui/text.py +854 -0
  54. doku2d-0.1.0/doku2d/gui/theme.py +181 -0
  55. doku2d-0.1.0/doku2d/gui/utils.py +288 -0
  56. doku2d-0.1.0/doku2d/physics/__init__.py +8 -0
  57. doku2d-0.1.0/doku2d/physics/body.py +284 -0
  58. doku2d-0.1.0/doku2d/physics/collision.py +53 -0
  59. doku2d-0.1.0/doku2d/physics/navigation.py +50 -0
  60. doku2d-0.1.0/doku2d/physics/pathfollower.py +192 -0
  61. doku2d-0.1.0/doku2d/physics/physical.py +371 -0
  62. doku2d-0.1.0/doku2d/physics/shapes.py +80 -0
  63. doku2d-0.1.0/doku2d/physics/world.py +281 -0
  64. doku2d-0.1.0/doku2d/rendering/__init__.py +12 -0
  65. doku2d-0.1.0/doku2d/rendering/autotile.py +30 -0
  66. doku2d-0.1.0/doku2d/rendering/camera.py +169 -0
  67. doku2d-0.1.0/doku2d/rendering/compositing.py +187 -0
  68. doku2d-0.1.0/doku2d/rendering/light.py +192 -0
  69. doku2d-0.1.0/doku2d/rendering/lighting.py +171 -0
  70. doku2d-0.1.0/doku2d/rendering/other.py +10 -0
  71. doku2d-0.1.0/doku2d/rendering/parallax.py +2 -0
  72. doku2d-0.1.0/doku2d/rendering/particles.py +321 -0
  73. doku2d-0.1.0/doku2d/rendering/shader.py +2 -0
  74. doku2d-0.1.0/doku2d/rendering/sprite.py +166 -0
  75. doku2d-0.1.0/doku2d/rendering/tilecollision.py +189 -0
  76. doku2d-0.1.0/doku2d/rendering/tiledparser.py +351 -0
  77. doku2d-0.1.0/doku2d/rendering/tilemap.py +780 -0
  78. doku2d-0.1.0/doku2d/rendering/tilenavigation.py +161 -0
  79. doku2d-0.1.0/doku2d.egg-info/PKG-INFO +95 -0
  80. doku2d-0.1.0/doku2d.egg-info/SOURCES.txt +94 -0
  81. doku2d-0.1.0/doku2d.egg-info/dependency_links.txt +1 -0
  82. doku2d-0.1.0/doku2d.egg-info/entry_points.txt +2 -0
  83. doku2d-0.1.0/doku2d.egg-info/requires.txt +5 -0
  84. doku2d-0.1.0/doku2d.egg-info/top_level.txt +1 -0
  85. doku2d-0.1.0/pyproject.toml +32 -0
  86. doku2d-0.1.0/setup.cfg +4 -0
  87. doku2d-0.1.0/tests/test_core.py +274 -0
  88. doku2d-0.1.0/tests/test_engine_features.py +233 -0
  89. doku2d-0.1.0/tests/test_gameplay.py +288 -0
  90. doku2d-0.1.0/tests/test_gui.py +421 -0
  91. doku2d-0.1.0/tests/test_navigation_audio_debug.py +127 -0
  92. doku2d-0.1.0/tests/test_navigation_clearance_profile.py +97 -0
  93. doku2d-0.1.0/tests/test_platform.py +326 -0
  94. doku2d-0.1.0/tests/test_preferences_pathfollower.py +104 -0
  95. doku2d-0.1.0/tests/test_project_workflow.py +181 -0
  96. doku2d-0.1.0/tests/test_world.py +368 -0
doku2d-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Metehan Özbek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
doku2d-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: doku2d
3
+ Version: 0.1.0
4
+ Summary: Python için kod odaklı 2D oyun framework'ü
5
+ Author: Metehan Özbek
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 Metehan Özbek
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Classifier: Intended Audience :: Developers
29
+ Classifier: Operating System :: OS Independent
30
+ Classifier: Programming Language :: Python :: 3
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Requires-Python: >=3.11
33
+ Description-Content-Type: text/markdown
34
+ License-File: LICENSE
35
+ Requires-Dist: sfml>=3.0.2.0
36
+ Requires-Dist: pymunk>=7.0
37
+ Provides-Extra: build
38
+ Requires-Dist: nuitka>=2.6; extra == "build"
39
+ Dynamic: license-file
40
+
41
+ # Doku2D
42
+
43
+ Python ile kod odaklı 2D oyun framework'ü. Nesneler doğrudan `Game` içine kaydolur;
44
+ özel Scene, root veya sahne ağacı gerektirmez.
45
+
46
+ ## Kurulum ve ilk proje
47
+
48
+ Depoyu kullandığın Python ortamına kur:
49
+
50
+ ```sh
51
+ python -m pip install -e .
52
+ python -m doku2d create benim_oyunum
53
+ cd benim_oyunum
54
+ python -m doku2d run
55
+ ```
56
+
57
+ Şablon; harita, karakter, toplama, gece-gündüz, CanvasGroup HUD ve kaydet/yükle
58
+ özellikleriyle çalışır. Proje ayarları `doku2d.toml`, kaynaklar `assets/` içindedir.
59
+ F5 kaydeder, F9 yükler. Nuitka derlemesi için motor deposunda `python -m pip install -e ".[build]"` ile derleme bağımlılığını kur. Oyun klasöründe:
60
+
61
+ ```sh
62
+ python -m doku2d build
63
+ ```
64
+
65
+ `build`, Nuitka ile hedef işletim sisteminde bağımsız bir uygulama üretir.
66
+ Windows'ta uygulama `dist/<app_id>.dist/<app_id>.exe` altında bulunur.
67
+
68
+ ## Örnekler
69
+
70
+ `python -m examples.gallery` ile örneklerin tamamını düğmelerle açabilirsin.
71
+ Galeride Gece ve Kum temaları aynı kontroller üzerinde denenebilir.
72
+
73
+ | Komut | İçerik |
74
+ | --- | --- |
75
+ | `python -m doku2d run --project examples/starter_project` | Yeni başlangıç projesi; CanvasGroup, gece-gündüz ve kayıt. |
76
+ | `python -m examples.gui_demo` | GUI kontrolleri. |
77
+ | `python -m examples.collect_game` | Üstten görünüşlü toplama oyunu. |
78
+ | `python -m examples.world_demo` | Tiled, kamera ve konumsal ses. |
79
+ | `python -m examples.platform_demo` | Platform fiziği ve animasyonlu autotile boyama. |
80
+ | `python -m examples.effects_demo` | Tween, zaman çizelgesi, parçacıklar ve gölgeler. |
81
+
82
+ ## Belgeler
83
+
84
+ - [Başlangıç ve çekirdek](doc/using.md)
85
+ - [CanvasGroup, ortam rengi, kaynaklar ve kayıt](doc/runtime.md)
86
+ - [Proje araçları ve paketleme](doc/project.md)
87
+ - [API temizliği ve geçiş notları](doc/api.md)
88
+ - [GUI](doc/gui.md)
89
+ - [Girdi, sprite animasyonu ve temel fizik](doc/gameplay.md)
90
+ - [TileMap, Tiled, kamera ve ses](doc/world.md)
91
+ - [Platform ve autotile](doc/platform.md)
92
+ - [Efektler ve ışık](doc/effects.md)
93
+
94
+ Motor kodu MIT lisanslıdır. Birlikte verilen Noto Sans, kendi OFL 1.1 lisansıyla
95
+ dağıtılır; `doku2d/assets/fonts/OFL.txt` dosyasına bakın.
doku2d-0.1.0/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # Doku2D
2
+
3
+ Python ile kod odaklı 2D oyun framework'ü. Nesneler doğrudan `Game` içine kaydolur;
4
+ özel Scene, root veya sahne ağacı gerektirmez.
5
+
6
+ ## Kurulum ve ilk proje
7
+
8
+ Depoyu kullandığın Python ortamına kur:
9
+
10
+ ```sh
11
+ python -m pip install -e .
12
+ python -m doku2d create benim_oyunum
13
+ cd benim_oyunum
14
+ python -m doku2d run
15
+ ```
16
+
17
+ Şablon; harita, karakter, toplama, gece-gündüz, CanvasGroup HUD ve kaydet/yükle
18
+ özellikleriyle çalışır. Proje ayarları `doku2d.toml`, kaynaklar `assets/` içindedir.
19
+ F5 kaydeder, F9 yükler. Nuitka derlemesi için motor deposunda `python -m pip install -e ".[build]"` ile derleme bağımlılığını kur. Oyun klasöründe:
20
+
21
+ ```sh
22
+ python -m doku2d build
23
+ ```
24
+
25
+ `build`, Nuitka ile hedef işletim sisteminde bağımsız bir uygulama üretir.
26
+ Windows'ta uygulama `dist/<app_id>.dist/<app_id>.exe` altında bulunur.
27
+
28
+ ## Örnekler
29
+
30
+ `python -m examples.gallery` ile örneklerin tamamını düğmelerle açabilirsin.
31
+ Galeride Gece ve Kum temaları aynı kontroller üzerinde denenebilir.
32
+
33
+ | Komut | İçerik |
34
+ | --- | --- |
35
+ | `python -m doku2d run --project examples/starter_project` | Yeni başlangıç projesi; CanvasGroup, gece-gündüz ve kayıt. |
36
+ | `python -m examples.gui_demo` | GUI kontrolleri. |
37
+ | `python -m examples.collect_game` | Üstten görünüşlü toplama oyunu. |
38
+ | `python -m examples.world_demo` | Tiled, kamera ve konumsal ses. |
39
+ | `python -m examples.platform_demo` | Platform fiziği ve animasyonlu autotile boyama. |
40
+ | `python -m examples.effects_demo` | Tween, zaman çizelgesi, parçacıklar ve gölgeler. |
41
+
42
+ ## Belgeler
43
+
44
+ - [Başlangıç ve çekirdek](doc/using.md)
45
+ - [CanvasGroup, ortam rengi, kaynaklar ve kayıt](doc/runtime.md)
46
+ - [Proje araçları ve paketleme](doc/project.md)
47
+ - [API temizliği ve geçiş notları](doc/api.md)
48
+ - [GUI](doc/gui.md)
49
+ - [Girdi, sprite animasyonu ve temel fizik](doc/gameplay.md)
50
+ - [TileMap, Tiled, kamera ve ses](doc/world.md)
51
+ - [Platform ve autotile](doc/platform.md)
52
+ - [Efektler ve ışık](doc/effects.md)
53
+
54
+ Motor kodu MIT lisanslıdır. Birlikte verilen Noto Sans, kendi OFL 1.1 lisansıyla
55
+ dağıtılır; `doku2d/assets/fonts/OFL.txt` dosyasına bakın.
@@ -0,0 +1,18 @@
1
+ """The supported public Doku2D API."""
2
+ from sfml.graphics import Color
3
+ from sfml.system import Vector2
4
+ from .config import ProjectConfig
5
+ __version__="0.1.0"
6
+ from .gui import *
7
+ from .rendering import *
8
+ from .core import *
9
+ from .physics import *
10
+ from .audio import *
11
+ from .animation import *
12
+ from .gui import __all__ as _gui
13
+ from .rendering import __all__ as _rendering
14
+ from .core import __all__ as _core
15
+ from .physics import __all__ as _physics
16
+ from .audio import __all__ as _audio
17
+ from .animation import __all__ as _animation
18
+ __all__=list(dict.fromkeys(['Color','Vector2','ProjectConfig']+_core+_gui+_rendering+_physics+_audio+_animation))
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
@@ -0,0 +1,8 @@
1
+ from .animatedsprite import *
2
+ from .animationplayer import Timeline, AnimationPlayer
3
+
4
+ from .motion import MotionAnimation
5
+
6
+ from .tween import Tween, PropertyTweener
7
+
8
+ __all__=["AnimatedSprite","Animation","Timeline","AnimationPlayer","MotionAnimation","Tween","PropertyTweener"]
@@ -0,0 +1,302 @@
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+ from math import isfinite
4
+ from types import MappingProxyType
5
+ from sfml.graphics import Texture
6
+ from sfml.system import Vector2
7
+ from ..core.entity import Entity
8
+ from ..core.signal import Signal
9
+ from ..rendering.sprite import Sprite
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Animation:
14
+ frames: tuple = (0,)
15
+ fps: float = 8.0
16
+ loop: bool = True
17
+
18
+
19
+ class AnimatedSprite(Entity):
20
+ animation_changed = Signal()
21
+ animation_finished = Signal()
22
+ animation_looped = Signal()
23
+ frame_changed = Signal()
24
+ sprite_frames_changed = Signal()
25
+
26
+ def __init__(self, texture=None, *, frame_size=None, name=None, resources=None):
27
+ super().__init__(name)
28
+ self._resources=resources;self._texture_path=None
29
+ self._visual = Sprite(resources=resources)
30
+ self._motion = None
31
+ self._frame_size = None
32
+ self._clips = {}
33
+ self._animation = ""
34
+ self._frame = 0
35
+ self._speed_scale = 1.0
36
+ self._playback_speed = 1.0
37
+ self._playing = False
38
+ self._finished = False
39
+ self._time = 0.0
40
+ if frame_size is not None:
41
+ self.frame_size = frame_size
42
+ if texture is not None:
43
+ self.texture = texture
44
+
45
+ @property
46
+ def motion(self):return self._motion
47
+
48
+ def follow_motion(self,body,**options):
49
+ from .motion import MotionAnimation
50
+ self._motion=MotionAnimation(self,body,**options) if body is not None else None
51
+ return self._motion
52
+
53
+ @staticmethod
54
+ def _clip(frames, fps, loop):
55
+ frames = tuple(frames)
56
+ if not frames or any(not isinstance(index,int) or index < 0 for index in frames):
57
+ raise ValueError("Animation frames must be a nonempty list of nonnegative indices")
58
+ if not isfinite(fps) or fps <= 0:
59
+ raise ValueError("Animation fps must be positive and finite")
60
+ return Animation(frames,float(fps),bool(loop))
61
+
62
+ def _grid(self, texture, frame_size):
63
+ if texture is None or frame_size is None:
64
+ return (1,1)
65
+ width,height = frame_size
66
+ if texture.size.x % width or texture.size.y % height:
67
+ raise ValueError("The texture must contain whole sprite-sheet cells")
68
+ return (int(texture.size.x/width),int(texture.size.y/height))
69
+
70
+ def _validate_frames(self, clip, count):
71
+ if self.texture is not None and max(clip.frames) >= count:
72
+ raise ValueError("Animation frame is outside the sprite sheet")
73
+
74
+ @property
75
+ def texture(self):
76
+ return self._visual.texture
77
+
78
+ @texture.setter
79
+ def texture(self, value):
80
+ if isinstance(value,(str,Path)):
81
+ self._texture_path=value
82
+ resources=self._resources or (self.game.resources if self.game else None)
83
+ value=resources.get_texture(value) if resources else None
84
+ else:self._texture_path=None
85
+ if value is not None and not isinstance(value,Texture):
86
+ raise TypeError("texture must be an SFML Texture, path or None")
87
+ columns,rows = self._grid(value,self._frame_size)
88
+ if value is not None and any(max(clip.frames) >= columns*rows for clip in self._clips.values()):
89
+ raise ValueError("The texture is too small for the existing animations")
90
+ self._visual.texture = value
91
+ self._visual.hframes,self._visual.vframes = columns,rows
92
+ self._apply_frame()
93
+
94
+ def _bind_resources(self,resources):
95
+ self._resources=resources;self._visual._bind_resources(resources)
96
+ if self._texture_path is not None:self._load_texture()
97
+
98
+ def _load_texture(self):
99
+ path=self._texture_path
100
+ if path is not None:
101
+ self.texture=self._resources.get_texture(path) if self._resources else Texture.from_file(str(path))
102
+ self._texture_path=path
103
+
104
+ @property
105
+ def frame_size(self):
106
+ return Vector2(*self._frame_size) if self._frame_size is not None else None
107
+
108
+ @frame_size.setter
109
+ def frame_size(self, value):
110
+ width,height = value
111
+ if not isfinite(width) or not isfinite(height) or width <= 0 or height <= 0 or int(width) != width or int(height) != height:
112
+ raise ValueError("Frame size must contain positive integer dimensions")
113
+ columns,rows = self._grid(self.texture,(width,height))
114
+ for clip in self._clips.values():
115
+ self._validate_frames(clip,columns*rows)
116
+ self._frame_size = (int(width),int(height))
117
+ self._visual.hframes,self._visual.vframes = columns,rows
118
+ self._apply_frame()
119
+
120
+ @property
121
+ def sprite_frames(self):
122
+ return MappingProxyType(self._clips)
123
+
124
+ @sprite_frames.setter
125
+ def sprite_frames(self, values):
126
+ clips = {}
127
+ for name,config in values.items():
128
+ if isinstance(config,Animation):
129
+ clip = self._clip(config.frames,config.fps,config.loop)
130
+ else:
131
+ clip = self._clip(config["frames"],config.get("fps",8),config.get("loop",True))
132
+ self._validate_frames(clip,self._visual.hframes*self._visual.vframes)
133
+ clips[name] = clip
134
+ self._clips = clips
135
+ self._animation = self._animation if self._animation in clips else next(iter(clips),"")
136
+ self._frame = 0
137
+ self._time = 0
138
+ self._playing = False
139
+ self._apply_frame()
140
+ self.sprite_frames_changed.emit()
141
+
142
+ def add_animation(self, name, frames, *, fps=8, loop=True):
143
+ if not isinstance(name,str) or not name:
144
+ raise ValueError("Animation names must be nonempty strings")
145
+ clip = self._clip(frames,fps,loop)
146
+ self._validate_frames(clip,self._visual.hframes*self._visual.vframes)
147
+ self._clips[name] = clip
148
+ if not self.animation:
149
+ self._animation = name
150
+ if self.animation == name:
151
+ self._frame = min(self._frame,len(clip.frames)-1)
152
+ self._apply_frame()
153
+ self.sprite_frames_changed.emit()
154
+ return self
155
+
156
+ @property
157
+ def animation(self):
158
+ return self._animation
159
+
160
+ @animation.setter
161
+ def animation(self, name):
162
+ if name not in self._clips:
163
+ raise KeyError(f"Unknown animation: {name}")
164
+ if name != self.animation:
165
+ self._animation = name
166
+ self._frame,self._time = 0,0
167
+ self._apply_frame()
168
+ self.animation_changed.emit()
169
+
170
+ @property
171
+ def frame(self):
172
+ return self._frame
173
+
174
+ @frame.setter
175
+ def frame(self, value):
176
+ clip = self._clips.get(self.animation)
177
+ if not isinstance(value,int) or clip is None or not 0 <= value < len(clip.frames):
178
+ raise ValueError("Frame is outside the current animation")
179
+ if self._frame != value:
180
+ self._frame = value
181
+ self._apply_frame()
182
+ self.frame_changed.emit()
183
+
184
+ @property
185
+ def speed_scale(self):
186
+ return self._speed_scale
187
+
188
+ @speed_scale.setter
189
+ def speed_scale(self, value):
190
+ if not isfinite(value):
191
+ raise ValueError("speed_scale must be finite")
192
+ self._speed_scale = float(value)
193
+
194
+ @property
195
+ def playing(self):
196
+ return self._playing
197
+
198
+ def is_playing(self):
199
+ return self.playing
200
+
201
+ def play(self, name=None, *, speed=1.0, from_end=False):
202
+ name = name or self.animation
203
+ if name not in self._clips:
204
+ raise KeyError(f"Unknown animation: {name}")
205
+ if not isfinite(speed):
206
+ raise ValueError("Playback speed must be finite")
207
+ self.animation = name
208
+ if self._finished:
209
+ self.frame = 0 if speed*self.speed_scale >= 0 else len(self._clips[name].frames)-1
210
+ self._time = 0
211
+ self._finished = False
212
+ if from_end:
213
+ self.frame = len(self._clips[name].frames)-1
214
+ self._time = 0
215
+ self._playback_speed = float(speed)
216
+ self._playing = True
217
+
218
+ def pause(self):
219
+ self._playing = False
220
+
221
+ def stop(self):
222
+ self.pause()
223
+ self._finished = False
224
+ self._time = 0
225
+ if self.animation:
226
+ self.frame = 0
227
+
228
+ def _apply_frame(self):
229
+ clip = self._clips.get(self.animation)
230
+ if clip is not None and self.texture is not None:
231
+ self._visual.frame = clip.frames[self.frame]
232
+
233
+ def advance(self, dt):
234
+ if self.motion is not None:self.motion.update()
235
+ if not isfinite(dt) or dt < 0:
236
+ raise ValueError("Delta time must be finite and nonnegative")
237
+ speed = self.speed_scale*self._playback_speed
238
+ if not self.playing or not speed:
239
+ return
240
+ name = self.animation
241
+ clip = self._clips[name]
242
+ self._time += dt*abs(speed)
243
+ steps = int((self._time+1e-10)*clip.fps)
244
+ self._time = max(0,self._time-steps/clip.fps)
245
+ direction = 1 if speed > 0 else -1
246
+ for _ in range(steps):
247
+ if not self.playing or self.animation != name or self._clips.get(name) is not clip:
248
+ break
249
+ index = self.frame+direction
250
+ if 0 <= index < len(clip.frames):
251
+ self.frame = index
252
+ elif clip.loop:
253
+ self.frame = index%len(clip.frames)
254
+ self.animation_looped.emit()
255
+ else:
256
+ self._playing = False
257
+ self._finished = True
258
+ self._time = 0
259
+ self.animation_finished.emit()
260
+ break
261
+
262
+ def _advance(self, dt):
263
+ self.advance(dt)
264
+
265
+ def render(self, target, states):
266
+ if self.texture is None and self._texture_path is not None:self._load_texture()
267
+ self._visual.render(target,states)
268
+
269
+ @property
270
+ def centered(self):
271
+ return self._visual.centered
272
+
273
+ @centered.setter
274
+ def centered(self, value):
275
+ self._visual.centered = value
276
+
277
+ @property
278
+ def offset(self):
279
+ return self._visual.offset
280
+
281
+ @offset.setter
282
+ def offset(self, value):
283
+ self._visual.offset = value
284
+
285
+ @property
286
+ def flip_h(self):
287
+ return self._visual.flip_h
288
+
289
+ @flip_h.setter
290
+ def flip_h(self, value):
291
+ self._visual.flip_h = value
292
+
293
+ @property
294
+ def flip_v(self):
295
+ return self._visual.flip_v
296
+
297
+ @flip_v.setter
298
+ def flip_v(self, value):
299
+ self._visual.flip_v = value
300
+
301
+
302
+ __all__ = ["AnimatedSprite","Animation"]
@@ -0,0 +1,131 @@
1
+ """Property, callback and signal tracks using direct object references."""
2
+ from types import MappingProxyType
3
+ from math import isfinite
4
+ from bisect import bisect_right
5
+ from ..core.entity import Entity
6
+ from ..core.signal import Signal
7
+ from .values import Binding,interpolate,easing,duration
8
+
9
+
10
+ class Timeline:
11
+ def __init__(self,length=None,*,loop=False):
12
+ self._length=None if length is None else duration(length)
13
+ self.loop=bool(loop);self._tracks=[];self._events=[]
14
+ @property
15
+ def length(self):
16
+ return self._length if self._length is not None else max([keys[-1][0] for binding,keys,ease,mode in self._tracks]+[event[0] for event in self._events]+[0])
17
+ def _check_time(self,time):
18
+ time=duration(time)
19
+ if self._length is not None and time>self._length:raise ValueError('Key exceeds the timeline length')
20
+ return time
21
+ def property(self,target,path,keys,*,ease='linear',interpolation='linear'):
22
+ keys=tuple(sorted(((self._check_time(t),v) for t,v in keys),key=lambda item:item[0]))
23
+ if not keys or len({t for t,v in keys})!=len(keys):raise ValueError('Use nonempty keys with unique times')
24
+ if interpolation not in ('linear','step'):raise ValueError('Interpolation must be linear or step')
25
+ easing(ease,.5)
26
+ self._tracks.append((Binding(target,path),keys,ease,interpolation));return self
27
+ def call(self,time,callback,*args,**kwargs):
28
+ if not callable(callback):raise TypeError('Expected a callback')
29
+ self._events.append((self._check_time(time),callback,args,kwargs));self._events.sort(key=lambda event:event[0]);return self
30
+ def signal(self,time,signal,*args):return self.call(time,signal.emit,*args)
31
+ def sample(self,time):
32
+ for binding,keys,ease,mode in self._tracks:
33
+ index=bisect_right([key[0] for key in keys],time)-1
34
+ if index<0:value=keys[0][1]
35
+ elif index>=len(keys)-1 or mode=='step':value=keys[index][1]
36
+ else:
37
+ a,v1=keys[index];b,v2=keys[index+1]
38
+ value=interpolate(v1,v2,easing(ease,(time-a)/(b-a)))
39
+ binding.set(value)
40
+
41
+
42
+ class AnimationPlayer(Entity):
43
+ animation_started=Signal()
44
+ animation_finished=Signal()
45
+ animation_looped=Signal()
46
+ def __init__(self,name=None,*,autoplay=None):
47
+ super().__init__(name)
48
+ self._animations={};self._animation='';self._playhead=0.0
49
+ self._playing=False;self._speed_scale=1.0;self._playback_speed=1.0
50
+ self._generation=0;self._pending_start=False;self.autoplay=autoplay
51
+ @property
52
+ def animations(self):return MappingProxyType(self._animations)
53
+ @property
54
+ def animation(self):return self._animation
55
+ @property
56
+ def playback_position(self):return self._playhead
57
+ @property
58
+ def playing(self):return self._playing
59
+ @property
60
+ def speed_scale(self):return self._speed_scale
61
+ @speed_scale.setter
62
+ def speed_scale(self,value):
63
+ if not isfinite(value):raise ValueError('Animation speed must be finite')
64
+ self._speed_scale=float(value)
65
+ def add_animation(self,name,timeline):
66
+ if not isinstance(name,str) or not name or not isinstance(timeline,Timeline):raise ValueError('Give a name and Timeline')
67
+ if timeline.loop and timeline.length==0:raise ValueError('Looping timeline must have a positive length')
68
+ self._animations[name]=timeline;return timeline
69
+ def play(self,name=None,*,speed=1,from_end=False):
70
+ name=name or self.animation
71
+ if name not in self._animations:raise KeyError(f'Unknown animation: {name}')
72
+ if not isfinite(speed):raise ValueError('Playback speed must be finite')
73
+ self._generation+=1;self._animation=name;self._playback_speed=float(speed)
74
+ self._playhead=self.animations[name].length if from_end else 0
75
+ self._playing=True;self._pending_start=True
76
+ self.animations[name].sample(self.playback_position);self.animation_started.emit(name)
77
+ def play_backwards(self,name=None):self.play(name,speed=-1,from_end=True)
78
+ def pause(self):self._playing=False
79
+ def resume(self):
80
+ if self.animation:self._playing=True
81
+ def stop(self,*,reset=True):
82
+ self._generation+=1;self._playing=False;self._pending_start=False
83
+ if reset and self.animation:self._playhead=0;self.animations[self.animation].sample(0)
84
+ def seek(self,time,*,update=True,events=False):
85
+ if not self.animation:raise RuntimeError('Choose an animation before seeking')
86
+ timeline=self.animations[self.animation];time=duration(time)
87
+ if time>timeline.length:raise ValueError('Seek exceeds timeline length')
88
+ old=self.playback_position;self._playhead=time;self._pending_start=False;self._generation+=1
89
+ if update:timeline.sample(time)
90
+ if events:self._events(timeline,old,time,self._generation,playback=False)
91
+ def _events(self,timeline,old,new,generation,include_start=False,playback=True):
92
+ reverse=new<old or new==old and self.speed_scale*self._playback_speed<0
93
+ events=reversed(timeline._events) if reverse else timeline._events
94
+ for time,callback,args,kwargs in tuple(events):
95
+ crossed=(new<=time<old if reverse else old<time<=new) or include_start and time==old
96
+ if crossed:
97
+ callback(*args,**kwargs)
98
+ if generation!=self._generation or playback and not self.playing:return False
99
+ return True
100
+ def _advance(self,dt):
101
+ if not self.playing:return
102
+ speed=self.speed_scale*self._playback_speed
103
+ if not speed:return
104
+ timeline=self.animations[self.animation];generation=self._generation
105
+ if self._pending_start:
106
+ self._pending_start=False
107
+ if not self._events(timeline,self.playback_position,self.playback_position,generation,True):return
108
+ remaining=dt*abs(speed);direction=1 if speed>0 else -1
109
+ while self.playing:
110
+ boundary=timeline.length if direction>0 else 0
111
+ span=abs(boundary-self.playback_position);consumed=min(span,remaining)
112
+ old=self.playback_position;self._playhead+=direction*consumed;remaining-=consumed
113
+ if span-consumed<=1e-10:self._playhead=boundary
114
+ timeline.sample(self.playback_position)
115
+ if generation!=self._generation or not self.playing:return
116
+ if not self._events(timeline,old,self.playback_position,generation):return
117
+ if abs(self.playback_position-boundary)>1e-9:return
118
+ if not timeline.loop:
119
+ self._playing=False;self.animation_finished.emit(self.animation);return
120
+ if timeline.length<=0:raise ValueError('Looping timeline must have a positive length')
121
+ self._playhead=0 if direction>0 else timeline.length
122
+ timeline.sample(self.playback_position);self.animation_looped.emit(self.animation)
123
+ if generation!=self._generation or not self.playing:return
124
+ if not self._events(timeline,self.playback_position,self.playback_position,generation,True):return
125
+ if remaining<=1e-10:return
126
+ def on_added(self):
127
+ if self.autoplay:self.play(self.autoplay)
128
+ def on_removed(self):self.stop(reset=False)
129
+
130
+
131
+ __all__=['Timeline','AnimationPlayer']
@@ -0,0 +1,39 @@
1
+ """Small opt-in animation policy, independent of a scene or state-machine tree."""
2
+ from math import hypot, isfinite
3
+ from sfml.system import Vector2
4
+ from ..core.signal import Signal
5
+
6
+
7
+ class MotionAnimation:
8
+ changed=Signal()
9
+ def __init__(self,sprite,body,*,idle='idle',run='run',jump='jump',fall='fall',run_speed=200,flip=True):
10
+ if not hasattr(body,'velocity'):raise TypeError('Motion animation needs a body with velocity')
11
+ if not isfinite(run_speed) or run_speed<=0:raise ValueError('run_speed must be positive')
12
+ self.sprite,self.body=sprite,body
13
+ self.animations={'idle':idle,'run':run,'jump':jump,'fall':fall}
14
+ required=('idle','run','jump','fall') if getattr(body,'motion_mode',None)=='grounded' else ('idle','run')
15
+ for state in required:
16
+ if self.animations[state] not in sprite.sprite_frames:raise KeyError(f'Missing {state} animation: {self.animations[state]}')
17
+ self.run_speed=float(run_speed)
18
+ self.flip=bool(flip)
19
+ self.enabled=True
20
+ self._state=''
21
+ @property
22
+ def state(self):return self._state
23
+ def update(self):
24
+ if not self.enabled:return
25
+ velocity=self.body.velocity
26
+ up=getattr(self.body,'up_direction',Vector2(0,-1))
27
+ horizontal=velocity.x*(-up.y)+velocity.y*up.x
28
+ vertical=velocity.x*up.x+velocity.y*up.y
29
+ if getattr(self.body,'motion_mode',None)=='grounded' and not self.body.is_on_floor():
30
+ state='jump' if vertical>1 else 'fall'
31
+ else:state='run' if hypot(*velocity)>.5 else 'idle'
32
+ if self.flip and abs(horizontal)>.5:self.sprite.flip_h=horizontal<0
33
+ name=self.animations[state]
34
+ magnitude=abs(horizontal) if getattr(self.body,'motion_mode',None)=='grounded' else hypot(*velocity)
35
+ speed=max(.25,min(2,magnitude/self.run_speed)) if state=='run' else 1
36
+ self.sprite.play(name,speed=speed)
37
+ if state!=self.state:
38
+ self._state=state
39
+ self.changed.emit(state)