pgzero-plus 0.1.0a3__tar.gz → 1.0.1__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 (60) hide show
  1. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/PKG-INFO +27 -11
  2. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/README.md +9 -7
  3. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/pyproject.toml +20 -4
  4. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/__init__.py +4 -0
  5. pgzero_plus-1.0.1/src/pgzero/_install_check.py +56 -0
  6. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/actor.py +8 -21
  7. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/builtins.py +4 -4
  8. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/game.py +52 -29
  9. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/loaders.py +29 -17
  10. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/rect.py +6 -1
  11. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/runner.py +6 -1
  12. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/sprites.py +0 -7
  13. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/storage.py +23 -11
  14. pgzero_plus-1.0.1/src/pgzero/tilemaps.py +1125 -0
  15. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/tone.py +1 -1
  16. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero_plus.egg-info/PKG-INFO +27 -11
  17. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero_plus.egg-info/SOURCES.txt +3 -0
  18. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero_plus.egg-info/requires.txt +3 -3
  19. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_actor_features.py +14 -1
  20. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_builtins.py +1 -1
  21. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_game_state.py +95 -18
  22. pgzero_plus-1.0.1/test/test_install_check.py +61 -0
  23. pgzero_plus-1.0.1/test/test_loader_case.py +77 -0
  24. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_runner.py +1 -1
  25. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_sprites.py +1 -19
  26. pgzero_plus-1.0.1/test/test_storage.py +154 -0
  27. pgzero_plus-1.0.1/test/test_tilemaps.py +1474 -0
  28. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_tone.py +7 -0
  29. pgzero_plus-0.1.0a3/src/pgzero/tilemaps.py +0 -358
  30. pgzero_plus-0.1.0a3/test/test_storage.py +0 -56
  31. pgzero_plus-0.1.0a3/test/test_tilemaps.py +0 -580
  32. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/COPYING +0 -0
  33. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/setup.cfg +0 -0
  34. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/__main__.py +0 -0
  35. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/animation.py +0 -0
  36. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/clock.py +0 -0
  37. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/constants.py +0 -0
  38. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/data/icon.png +0 -0
  39. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/data/joypad.png +0 -0
  40. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/keyboard.py +0 -0
  41. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/music.py +0 -0
  42. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/ptext.py +0 -0
  43. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/screen.py +0 -0
  44. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/soundfmt.py +0 -0
  45. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero/spellcheck.py +0 -0
  46. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero_plus.egg-info/dependency_links.txt +0 -0
  47. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero_plus.egg-info/entry_points.txt +0 -0
  48. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzero_plus.egg-info/top_level.txt +0 -0
  49. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/src/pgzrun.py +1 -1
  50. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_actor.py +0 -0
  51. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_animation.py +0 -0
  52. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_event_dispatch.py +0 -0
  53. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_keyboard.py +0 -0
  54. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_music.py +0 -0
  55. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_rect_actor.py +0 -0
  56. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_screen.py +0 -0
  57. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_sound_formats.py +0 -0
  58. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_spellcheck.py +0 -0
  59. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_transform_anchor.py +0 -0
  60. {pgzero_plus-0.1.0a3 → pgzero_plus-1.0.1}/test/test_webp_loader.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pgzero-plus
3
- Version: 0.1.0a3
3
+ Version: 1.0.1
4
4
  Summary: An enhanced fork of Pygame Zero with additional features for teaching and developing 2D games
5
5
  Author-email: Michael D'Argenio <mjdargen@gmail.com>
6
6
  License-Expression: LGPL-3.0-or-later
@@ -9,16 +9,30 @@ Project-URL: Documentation, https://pgzero-plus.readthedocs.io/
9
9
  Project-URL: Source, https://github.com/mjdargen/pgzero
10
10
  Project-URL: Issues, https://github.com/mjdargen/pgzero/issues
11
11
  Keywords: pygame,pgzero,games,education
12
+ Classifier: Development Status :: 5 - Production/Stable
12
13
  Classifier: Intended Audience :: Education
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
13
17
  Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.6
20
+ Classifier: Programming Language :: Python :: 3.7
21
+ Classifier: Programming Language :: Python :: 3.8
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
14
28
  Classifier: Topic :: Education
15
29
  Classifier: Topic :: Games/Entertainment
16
30
  Requires-Python: >=3.6
17
31
  Description-Content-Type: text/markdown
18
32
  License-File: COPYING
19
- Requires-Dist: pygame>=2.6.1; python_version < "3.10"
20
- Requires-Dist: pygame-ce>=2.5.8; python_version >= "3.10"
21
- Requires-Dist: numpy
33
+ Requires-Dist: pygame<3,>=2.6.1; python_version < "3.10"
34
+ Requires-Dist: pygame-ce<3,>=2.5.8; python_version >= "3.10"
35
+ Requires-Dist: numpy<3
22
36
  Requires-Dist: importlib-metadata==4.8.3; python_version < "3.8"
23
37
  Dynamic: license-file
24
38
 
@@ -37,7 +51,9 @@ This fork adds features and quality-of-life improvements for introductory comput
37
51
 
38
52
  ## Installation
39
53
 
40
- The PyPI distribution is named `pgzero-plus`, but it provides the same `pgzero` Python package and `pgzrun` command as the original Pygame Zero. **Do not install both distributions in the same Python environment.**
54
+ Pygame Zero Plus needs Python 3.6 or newer, on Windows, macOS or Linux.
55
+
56
+ The PyPI distribution is named `pgzero-plus`, but it provides the same `pgzero` Python package and `pgzrun` command as the original Pygame Zero. **Do not install both distributions in the same Python environment.** If they are, or if both `pygame` and `pygame-ce` are installed, games print a warning with the commands to fix it.
41
57
 
42
58
  ### Install or Update
43
59
 
@@ -178,19 +194,19 @@ GitHub Actions runs pre-commit, the tests on every supported Python version, the
178
194
 
179
195
  Pushing a version tag triggers the release workflow, which tests, builds, publishes to PyPI, and creates a GitHub Release.
180
196
 
181
- **1. Update the version** in `pyproject.toml`:
197
+ **1. Update the version** in `pyproject.toml`, and its heading in `doc/changelog.rst`. Use [semantic versioning](https://semver.org): from 1.0.0 on, a release that changes or removes anything students use needs a new major version (2.0.0).
182
198
 
183
199
  ```toml
184
- version = "0.1.0a2"
200
+ version = "1.0.0"
185
201
  ```
186
202
 
187
- **2. Commit and push changes:**
203
+ **2. Commit, and get the changes onto `main`.** Work on a branch and merge it once Code Checks passes on it, or commit to `main` directly:
188
204
 
189
205
  ```bash
190
206
  git switch main
191
207
  git status
192
208
  git add .
193
- git commit -m "Prepare v0.1.0a2"
209
+ git commit -m "Prepare v1.0.0"
194
210
  git push origin main
195
211
  ```
196
212
 
@@ -199,8 +215,8 @@ git push origin main
199
215
  **4. Create and push the release tag:**
200
216
 
201
217
  ```bash
202
- git tag -a v0.1.0a2 -m "Release v0.1.0a2"
203
- git push origin v0.1.0a2
218
+ git tag -a v1.0.0 -m "Release v1.0.0"
219
+ git push origin v1.0.0
204
220
  ```
205
221
 
206
222
  **5. Verify publication:**
@@ -13,7 +13,9 @@ This fork adds features and quality-of-life improvements for introductory comput
13
13
 
14
14
  ## Installation
15
15
 
16
- The PyPI distribution is named `pgzero-plus`, but it provides the same `pgzero` Python package and `pgzrun` command as the original Pygame Zero. **Do not install both distributions in the same Python environment.**
16
+ Pygame Zero Plus needs Python 3.6 or newer, on Windows, macOS or Linux.
17
+
18
+ The PyPI distribution is named `pgzero-plus`, but it provides the same `pgzero` Python package and `pgzrun` command as the original Pygame Zero. **Do not install both distributions in the same Python environment.** If they are, or if both `pygame` and `pygame-ce` are installed, games print a warning with the commands to fix it.
17
19
 
18
20
  ### Install or Update
19
21
 
@@ -154,19 +156,19 @@ GitHub Actions runs pre-commit, the tests on every supported Python version, the
154
156
 
155
157
  Pushing a version tag triggers the release workflow, which tests, builds, publishes to PyPI, and creates a GitHub Release.
156
158
 
157
- **1. Update the version** in `pyproject.toml`:
159
+ **1. Update the version** in `pyproject.toml`, and its heading in `doc/changelog.rst`. Use [semantic versioning](https://semver.org): from 1.0.0 on, a release that changes or removes anything students use needs a new major version (2.0.0).
158
160
 
159
161
  ```toml
160
- version = "0.1.0a2"
162
+ version = "1.0.0"
161
163
  ```
162
164
 
163
- **2. Commit and push changes:**
165
+ **2. Commit, and get the changes onto `main`.** Work on a branch and merge it once Code Checks passes on it, or commit to `main` directly:
164
166
 
165
167
  ```bash
166
168
  git switch main
167
169
  git status
168
170
  git add .
169
- git commit -m "Prepare v0.1.0a2"
171
+ git commit -m "Prepare v1.0.0"
170
172
  git push origin main
171
173
  ```
172
174
 
@@ -175,8 +177,8 @@ git push origin main
175
177
  **4. Create and push the release tag:**
176
178
 
177
179
  ```bash
178
- git tag -a v0.1.0a2 -m "Release v0.1.0a2"
179
- git push origin v0.1.0a2
180
+ git tag -a v1.0.0 -m "Release v1.0.0"
181
+ git push origin v1.0.0
180
182
  ```
181
183
 
182
184
  **5. Verify publication:**
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pgzero-plus"
3
- version = "0.1.0a3"
3
+ version = "1.0.1"
4
4
  description = "An enhanced fork of Pygame Zero with additional features for teaching and developing 2D games"
5
5
  readme = "README.md"
6
6
  license = "LGPL-3.0-or-later"
@@ -12,15 +12,31 @@ requires-python = ">=3.6"
12
12
  dependencies = [
13
13
  # Both provide the pygame module. pygame-ce is actively developed but
14
14
  # needs Python 3.10+, so older Pythons use pygame.
15
- "pygame>=2.6.1; python_version < '3.10'",
16
- "pygame-ce>=2.5.8; python_version >= '3.10'",
17
- "numpy",
15
+ # The upper limits stop a future major version from changing students'
16
+ # installs overnight; raise them after testing the new version.
17
+ "pygame>=2.6.1,<3; python_version < '3.10'",
18
+ "pygame-ce>=2.5.8,<3; python_version >= '3.10'",
19
+ "numpy<3",
18
20
  "importlib-metadata==4.8.3; python_version < '3.8'",
19
21
  ]
20
22
  keywords = ["pygame", "pgzero", "games", "education"]
21
23
  classifiers = [
24
+ "Development Status :: 5 - Production/Stable",
22
25
  "Intended Audience :: Education",
26
+ "Operating System :: Microsoft :: Windows",
27
+ "Operating System :: MacOS",
28
+ "Operating System :: POSIX :: Linux",
23
29
  "Programming Language :: Python :: 3",
30
+ "Programming Language :: Python :: 3 :: Only",
31
+ "Programming Language :: Python :: 3.6",
32
+ "Programming Language :: Python :: 3.7",
33
+ "Programming Language :: Python :: 3.8",
34
+ "Programming Language :: Python :: 3.9",
35
+ "Programming Language :: Python :: 3.10",
36
+ "Programming Language :: Python :: 3.11",
37
+ "Programming Language :: Python :: 3.12",
38
+ "Programming Language :: Python :: 3.13",
39
+ "Programming Language :: Python :: 3.14",
24
40
  "Topic :: Education",
25
41
  "Topic :: Games/Entertainment",
26
42
  ]
@@ -24,9 +24,13 @@ except ImportError:
24
24
  # Python 3.6 and 3.7
25
25
  from importlib_metadata import PackageNotFoundError, version
26
26
 
27
+ from ._install_check import warn_about_clashing_installs
28
+
27
29
  try:
28
30
  __version__ = version("pgzero-plus")
29
31
  except PackageNotFoundError:
30
32
  __version__ = "unknown"
31
33
 
34
+ warn_about_clashing_installs()
35
+
32
36
  __all__ = ["__version__"]
@@ -0,0 +1,56 @@
1
+ """Warn about installs that clash, which is the most common classroom problem.
2
+
3
+ pygame and pygame-ce both install a package called pygame, and pgzero and
4
+ pgzero-plus both install packages called pgzero and pgzrun. pip can't stop
5
+ both of a pair being installed, and when they are, files from one overwrite
6
+ the other's, so games crash or behave strangely in ways that are hard to
7
+ trace back to the install.
8
+ """
9
+
10
+ import sys
11
+
12
+ try:
13
+ from importlib.metadata import PackageNotFoundError, distribution
14
+ except ImportError:
15
+ # Python 3.6 and 3.7
16
+ from importlib_metadata import PackageNotFoundError, distribution
17
+
18
+ # Pairs of distributions that install the same Python packages.
19
+ CLASHING_PAIRS = [("pygame", "pygame-ce"), ("pgzero", "pgzero-plus")]
20
+
21
+
22
+ def _installed(name):
23
+ try:
24
+ distribution(name)
25
+ except PackageNotFoundError:
26
+ return False
27
+ return True
28
+
29
+
30
+ def clashing_installs(installed=_installed):
31
+ """Return the pairs from CLASHING_PAIRS that are both installed."""
32
+ return [pair for pair in CLASHING_PAIRS if installed(pair[0]) and installed(pair[1])]
33
+
34
+
35
+ def warning_message(clashes, python=None):
36
+ """Return a message explaining the clashes and how to fix them."""
37
+ python = python or sys.executable
38
+ names = ", ".join(" and ".join(pair) for pair in clashes)
39
+ return (
40
+ "Warning: {} are both installed. They overwrite each other's files, so "
41
+ "games may crash or behave strangely. To fix it, run these two "
42
+ "commands, then restart your editor:\n"
43
+ ' "{python}" -m pip uninstall -y pgzero pgzero-plus pygame pygame-ce\n'
44
+ ' "{python}" -m pip install pgzero-plus'.format(names, python=python)
45
+ )
46
+
47
+
48
+ def warn_about_clashing_installs():
49
+ """Print a warning if clashing distributions are installed."""
50
+ try:
51
+ clashes = clashing_installs()
52
+ except Exception:
53
+ # Never stop a game from starting because the check went wrong.
54
+ return
55
+ if clashes:
56
+ print(warning_message(clashes), file=sys.stderr)
@@ -1,4 +1,3 @@
1
- import warnings
2
1
  import pygame
3
2
  from math import radians, sin, cos, atan2, degrees, sqrt
4
3
 
@@ -166,7 +165,9 @@ def _set_angle(actor, current_surface):
166
165
 
167
166
  class Actor:
168
167
  EXPECTED_INIT_KWARGS = SYMBOLIC_POSITIONS
169
- DELEGATED_ATTRIBUTES = [a for a in dir(rect.ZRect) if not a.startswith("_")]
168
+ # A set, because __getattr__ and __setattr__ check it on every access to
169
+ # an attribute like x, left or center, and a set finds a name at once.
170
+ DELEGATED_ATTRIBUTES = frozenset(a for a in dir(rect.ZRect) if not a.startswith("_"))
170
171
 
171
172
  function_order = [_set_opacity, _set_scale, _set_flip, _set_angle]
172
173
 
@@ -278,7 +279,7 @@ class Actor:
278
279
 
279
280
  def __dir__(self):
280
281
  standard_attributes = [key for key in self.__dict__.keys() if not key.startswith("_")]
281
- return standard_attributes + self.__class__.DELEGATED_ATTRIBUTES
282
+ return standard_attributes + sorted(self.__class__.DELEGATED_ATTRIBUTES)
282
283
 
283
284
  def _handle_unexpected_kwargs(self, kwargs):
284
285
  unexpected_kwargs = set(kwargs.keys()) - self.EXPECTED_INIT_KWARGS
@@ -784,7 +785,9 @@ class Actor:
784
785
 
785
786
  @property
786
787
  def collision_rect(self):
787
- return self._rect
788
+ """The collision rectangle that was set: (width, height),
789
+ (width, height, offset_x, offset_y), or None for the whole image."""
790
+ return self._collision_rect_spec
788
791
 
789
792
  @collision_rect.setter
790
793
  def collision_rect(self, value):
@@ -803,7 +806,7 @@ class Actor:
803
806
  self._move_body_to_preserve_image_topleft(old_image_topleft)
804
807
 
805
808
  def draw_collision_rect(self):
806
- r = self.collision_rect
809
+ r = self._rect
807
810
  pygame.draw.rect(
808
811
  game.screen,
809
812
  (255, 0, 0),
@@ -858,19 +861,3 @@ class Actor:
858
861
  def unload_image(self):
859
862
  if self._image_name is not None:
860
863
  loaders.images.unload(self._image_name)
861
-
862
-
863
- class SpriteActor(Actor):
864
- """Deprecated: Actor plays Sprites itself, e.g. Actor(fox_walk).
865
-
866
- Kept so that games written for older versions still run.
867
- """
868
-
869
- def __init__(self, *args, **kwargs):
870
- warnings.warn(
871
- "SpriteActor is no longer needed and will be removed. "
872
- "Use Actor instead, e.g. Actor(fox_walk).",
873
- DeprecationWarning,
874
- stacklevel=2,
875
- )
876
- super().__init__(*args, **kwargs)
@@ -2,7 +2,7 @@
2
2
  from . import clock
3
3
  from . import music
4
4
  from . import tone
5
- from .actor import Actor, SpriteActor
5
+ from .actor import Actor
6
6
  from .sprites import Sprite
7
7
  from .storage import storage
8
8
  from .keyboard import keyboard
@@ -11,7 +11,7 @@ from .rect import Rect, ZRect
11
11
  from .loaders import images, sounds
12
12
  from .constants import mouse, keys, keymods
13
13
  from .game import Game, exit
14
- from .tilemaps import load_tile_map_actors
14
+ from .tilemaps import load_tile_map, load_tile_map_actors
15
15
 
16
16
  # The actual screen will be installed here
17
17
  from .screen import screen_instance as screen
@@ -25,7 +25,6 @@ __all__ = [
25
25
  "Actor",
26
26
  "images",
27
27
  "Sprite", # graphics
28
- "SpriteActor", # deprecated, kept so older games still run
29
28
  "sounds",
30
29
  "music",
31
30
  "tone", # sound
@@ -41,5 +40,6 @@ __all__ = [
41
40
  "Game",
42
41
  "game",
43
42
  "exit",
44
- "load_tile_map_actors",
43
+ "load_tile_map",
44
+ "load_tile_map_actors", # the old name of load_tile_map, kept so older games still run
45
45
  ]
@@ -1,3 +1,4 @@
1
+ import inspect
1
2
  import sys
2
3
  import operator
3
4
  import time
@@ -22,7 +23,6 @@ DISPLAY_FLAGS = pygame.SHOWN
22
23
 
23
24
 
24
25
  class Game:
25
- ENDED_STATES = ("won", "lost", "over")
26
26
  """
27
27
  Simple game-wide state container for beginner projects.
28
28
 
@@ -30,6 +30,8 @@ class Game:
30
30
  the current game state without needing lots of global variables.
31
31
  """
32
32
 
33
+ ENDED_STATES = ("won", "lost", "over")
34
+
33
35
  def __init__(self):
34
36
  self._start_callback = None
35
37
  self._clock = None
@@ -51,8 +53,6 @@ class Game:
51
53
  self.timer = 0
52
54
  self.frame_count = 0
53
55
 
54
- self.data = {}
55
-
56
56
  def restart(self, delay=0.0, clear_clock="immediate"):
57
57
  """
58
58
  Restart the game.
@@ -151,10 +151,6 @@ class Game:
151
151
  def over(self, restart_after=None, clear_clock="immediate"):
152
152
  self._end("over", restart_after, clear_clock)
153
153
 
154
- def start(self):
155
- """Start or resume normal gameplay."""
156
- self.state = "playing"
157
-
158
154
  def pause(self):
159
155
  """Pause the game."""
160
156
  if self.state == "playing":
@@ -421,10 +417,34 @@ class PGZeroGame:
421
417
  return draw
422
418
 
423
419
  def get_start_func(self):
424
- """Get the start() function from the user module if it exists."""
420
+ """Get the start() function from the user module if it exists.
421
+
422
+ Pygame Zero calls start() with no arguments when the game starts and
423
+ on every restart. A game written for Pygame Zero may already use the
424
+ name start for something else, such as a start position or its own
425
+ start(level) function, so those are left alone.
426
+ """
425
427
  start = getattr(self.mod, "start", None)
426
- if start is not None and not callable(start):
427
- raise TypeError(f"{start!r} is not callable")
428
+ if start is None or not callable(start):
429
+ return None
430
+ try:
431
+ params = inspect.signature(start).parameters.values()
432
+ except (TypeError, ValueError):
433
+ return start
434
+ required = [
435
+ p.name for p in params
436
+ if p.default is p.empty and p.kind in (p.POSITIONAL_ONLY, p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)
437
+ ]
438
+ if required:
439
+ print(
440
+ "Note: start() needs {} ({}), so Pygame Zero won't call it when "
441
+ "the game starts. To have it called automatically, give start() "
442
+ "no parameters.".format(
443
+ "an argument" if len(required) == 1 else "arguments", ", ".join(required)
444
+ ),
445
+ file=sys.stderr,
446
+ )
447
+ return None
428
448
  return start
429
449
 
430
450
  def run(self):
@@ -469,21 +489,23 @@ class PGZeroGame:
469
489
  self.handlers[pygame.KEYDOWN] = key_down
470
490
  self.handlers[pygame.KEYUP] = key_up
471
491
 
472
- def tick_game_state(self, dt):
473
- """Tick the global game object if it exists."""
474
- game_obj = getattr(self.mod, "game", None)
492
+ def get_game_obj(self):
493
+ """Return Pygame Zero's Game object for this game, or None.
475
494
 
476
- if game_obj is None:
477
- game_obj = getattr(builtins, "game", None)
495
+ Only a Game counts: a game written for Pygame Zero may have its own
496
+ variable called game, which must be left alone.
497
+ """
498
+ for game_obj in (getattr(self.mod, "game", None), getattr(builtins, "game", None)):
499
+ if isinstance(game_obj, Game):
500
+ return game_obj
501
+ return None
478
502
 
503
+ def tick_game_state(self, dt):
504
+ """Tick the global game object if it exists."""
505
+ game_obj = self.get_game_obj()
479
506
  if game_obj is None:
480
507
  return False
481
-
482
- tick = getattr(game_obj, "tick", None)
483
- if not callable(tick):
484
- return False
485
-
486
- tick(dt)
508
+ game_obj.tick(dt)
487
509
  return True
488
510
 
489
511
  def handle_events(self, dt, update) -> bool:
@@ -505,9 +527,13 @@ class PGZeroGame:
505
527
  handler(event)
506
528
  updated = True
507
529
 
508
- clock = pgzero.clock.clock
509
- clock.tick(dt)
510
- updated |= clock.fired
530
+ # While the game is paused, clock timers and animate() wait too, and
531
+ # carry on from where they were when it resumes.
532
+ game_obj = self.get_game_obj()
533
+ if game_obj is None or game_obj.state != "paused":
534
+ clock = pgzero.clock.clock
535
+ clock.tick(dt)
536
+ updated |= clock.fired
511
537
 
512
538
  updated |= self.tick_game_state(dt)
513
539
 
@@ -526,11 +552,8 @@ class PGZeroGame:
526
552
  draw = self.get_draw_func()
527
553
  start = self.get_start_func()
528
554
 
529
- game_obj = getattr(self.mod, "game", None)
530
- if game_obj is None:
531
- game_obj = getattr(builtins, "game", None)
532
-
533
- if game_obj is not None and hasattr(game_obj, "_bind_engine"):
555
+ game_obj = self.get_game_obj()
556
+ if game_obj is not None:
534
557
  game_obj._bind_engine(start_callback=start, clock=pgzero.clock.clock)
535
558
 
536
559
  global current_game
@@ -32,20 +32,33 @@ class InvalidCase(Exception):
32
32
  """Indicate case errors early so they don't bite cross-platform users."""
33
33
 
34
34
 
35
- try:
36
- import win32api
37
- except ImportError:
38
-
39
- def real_path(path):
40
- return path
41
-
42
- else:
43
-
44
- def real_path(path):
45
- """Get the real capitalisation of a path on Windows."""
46
- if not os.path.exists(path):
47
- return path
48
- return win32api.GetLongPathNameW(win32api.GetShortPathName(path))
35
+ def real_relpath(relpath, start=None):
36
+ """Return relpath, below the folder start, with each part capitalised the
37
+ way it really is on disk.
38
+
39
+ Windows and macOS don't care about capitalisation, so a game can load
40
+ 'alien' from Alien.PNG there and then fail on Linux (e.g. Codio). Reading
41
+ the names in each folder works the same on every operating system, and
42
+ only looks at the part of the path below the game's own folder.
43
+ """
44
+ current = root if start is None else start
45
+ real_parts = []
46
+ for part in os.path.normpath(relpath).split(os.sep):
47
+ if part in ("", os.curdir, os.pardir):
48
+ real_parts.append(part)
49
+ current = os.path.join(current, part)
50
+ continue
51
+ try:
52
+ names = os.listdir(current)
53
+ except OSError:
54
+ return relpath # can't look inside this folder, so can't check
55
+ if part not in names:
56
+ matches = [name for name in names if name.lower() == part.lower()]
57
+ if matches:
58
+ part = matches[0]
59
+ real_parts.append(part)
60
+ current = os.path.join(current, part)
61
+ return os.path.join(*real_parts) if real_parts else relpath
49
62
 
50
63
 
51
64
  def validate_lowercase(relpath):
@@ -61,11 +74,10 @@ def validate_lowercase(relpath):
61
74
 
62
75
  def validate_compatible_path(path):
63
76
  """Validate that the given path can be loaded cross-platform."""
64
- relpath = os.path.relpath(path, root)
77
+ relpath = os.path.normpath(os.path.relpath(path, root))
65
78
  validate_lowercase(relpath)
66
79
 
67
- real = real_path(os.path.join(root, relpath))
68
- real_rel = os.path.relpath(real, root)
80
+ real_rel = real_relpath(relpath)
69
81
 
70
82
  if real_rel != relpath:
71
83
  raise InvalidCase(
@@ -492,7 +492,12 @@ class ZRect:
492
492
  )
493
493
 
494
494
  def colliderect(self, *other):
495
- rect = self.__class__(*other)
495
+ # Collision checks run thousands of times a frame against tile maps,
496
+ # so compare with another rect directly instead of copying it first.
497
+ if len(other) == 1 and isinstance(other[0], RECT_CLASSES):
498
+ rect = other[0]
499
+ else:
500
+ rect = self.__class__(*other)
496
501
  return (
497
502
  self.x < rect.x + rect.w and
498
503
  self.y < rect.y + rect.h and
@@ -235,4 +235,9 @@ def run_mod(mod, **kwargs):
235
235
  pygame.display.quit()
236
236
  pygame.display.init()
237
237
 
238
- PGZeroGame(mod, **kwargs).run()
238
+ try:
239
+ PGZeroGame(mod, **kwargs).run()
240
+ finally:
241
+ # Save storage when the game ends, however it ends, so that high
242
+ # scores and other saved values are there next time.
243
+ storage.Storage.save_all()
@@ -1,5 +1,3 @@
1
- import copy
2
-
3
1
  import pygame
4
2
  import pygame.surfarray
5
3
 
@@ -162,8 +160,3 @@ class Sprite:
162
160
  "visible frames."
163
161
  )
164
162
  return images
165
-
166
- def copy(self):
167
- # Older versions needed a copy of a Sprite for each actor. Sprites can
168
- # now be shared, but this is kept so that code still works.
169
- return copy.copy(self)
@@ -1,6 +1,7 @@
1
1
  import json
2
2
  import os
3
3
  import platform
4
+ import sys
4
5
  from hashlib import sha1
5
6
 
6
7
 
@@ -63,12 +64,7 @@ class Storage(dict):
63
64
  @classmethod
64
65
  def _ensure_save_path(cls):
65
66
  """Ensure that the directory for all save game data exists."""
66
- try:
67
- os.makedirs(cls.STORAGE_DIR)
68
- except (IsADirectoryError, PermissionError):
69
- pass
70
- except FileExistsError:
71
- pass
67
+ os.makedirs(cls.STORAGE_DIR, exist_ok=True)
72
68
 
73
69
  def _set_filename_from_path(self, file_path):
74
70
  """Set the path to save to from the given filename.
@@ -110,9 +106,21 @@ class Storage(dict):
110
106
  except FileNotFoundError:
111
107
  # If no file exists, it's fine
112
108
  pass
113
- except json.JSONDecodeError:
114
- raise StorageCorruptionException(
115
- "Storage is corrupted. Couldn't load the data."
109
+ except (json.JSONDecodeError, UnicodeDecodeError):
110
+ # A damaged save file (e.g. the computer turned off while it was
111
+ # being written) shouldn't stop the game from starting. Keep it
112
+ # as a .bak file, in case it can be fixed by hand, and start
113
+ # with empty storage.
114
+ backup = self.path + '.bak'
115
+ try:
116
+ os.replace(self.path, backup)
117
+ except OSError:
118
+ backup = None
119
+ print(
120
+ "Warning: the saved data for this game was damaged, so the "
121
+ "game is starting without it."
122
+ + (" The damaged file was kept as {}".format(backup) if backup else ""),
123
+ file=sys.stderr,
116
124
  )
117
125
  else:
118
126
  self.update(data)
@@ -141,10 +149,14 @@ class Storage(dict):
141
149
  )
142
150
  )
143
151
  else:
152
+ self._ensure_save_path()
144
153
  path = self.path
145
- with open(path, 'w+') as f:
154
+ # Write to a temporary file, then swap it in, so the save file is
155
+ # never left half-written if the game is closed while saving.
156
+ temp_path = path + '.tmp'
157
+ with open(temp_path, 'w') as f:
146
158
  f.write(data)
147
- print("Saved storage to", path)
159
+ os.replace(temp_path, path)
148
160
 
149
161
  # Constants for use with isinstance in _get_json_error_keys()
150
162
  JSON_PRIMITIVES = (float, int, str, bool, type(None))