diff --git a/.github/ISSUE_TEMPLATE/blank_issue.md b/.github/ISSUE_TEMPLATE/blank_issue.md index 3364940bb3..02205dc269 100644 --- a/.github/ISSUE_TEMPLATE/blank_issue.md +++ b/.github/ISSUE_TEMPLATE/blank_issue.md @@ -2,7 +2,7 @@ name: 🗎 Blank Issue about: A blank issue. For those who know what they are doing. title: '' -labels: +labels: assignees: '' ---- \ No newline at end of file +--- diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index d49c959f84..795e661cfd 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -11,7 +11,7 @@ assignees: '' **Environment:** -If possible, please include the output of `pygame.print_debug_info()` from your program in your bug report. It looks something +If possible, please include the output of `pygame.print_debug_info()` from your program in your bug report. It looks something like this: ``` @@ -33,7 +33,7 @@ Freetype versions: Linked: 2.11.1 Compiled: 2.11.1 Display Driver: windows Mixer Driver: wasapi ``` -If you can't get the debug output, any of the environment details included in it that you do know would be useful +If you can't get the debug output, any of the environment details included in it that you do know would be useful in diagnosing the issue & helping you. Other environment details, not included in `print_debug_info()`, that might help: diff --git a/.github/ISSUE_TEMPLATE/enhancement.md b/.github/ISSUE_TEMPLATE/enhancement.md index d51828ae3f..8166019d92 100644 --- a/.github/ISSUE_TEMPLATE/enhancement.md +++ b/.github/ISSUE_TEMPLATE/enhancement.md @@ -9,4 +9,4 @@ assignees: '' **Description** -Describe your enhancement, as clearly as possible. \ No newline at end of file +Describe your enhancement, as clearly as possible. diff --git a/.github/workflows/build-debian-multiarch.yml b/.github/workflows/build-debian-multiarch.yml index 24c55f334c..0ce4cd8315 100644 --- a/.github/workflows/build-debian-multiarch.yml +++ b/.github/workflows/build-debian-multiarch.yml @@ -107,7 +107,7 @@ jobs: export SDL_VIDEODRIVER=dummy export SDL_AUDIODRIVER=disk python3 -m pygame.tests -v --exclude opengl,music,timing --time_out 300 - + # Upload the generated files under github actions assets section - name: Upload dist uses: actions/upload-artifact@v4 diff --git a/.github/workflows/build-macos.yml b/.github/workflows/build-macos.yml index 05f08ddc9e..ecbb6c8ee9 100644 --- a/.github/workflows/build-macos.yml +++ b/.github/workflows/build-macos.yml @@ -1,7 +1,7 @@ name: macOS -# Run CI only when a release is created, on changes to main branch, or any PR -# to main. Do not run CI on any other branch. Also, skip any non-source changes +# Run CI only when a release is created, on changes to main branch, or any PR +# to main. Do not run CI on any other branch. Also, skip any non-source changes # from running on CI on: push: @@ -27,7 +27,7 @@ on: - '.github/workflows/*.yml' # re-include current file to not be excluded - '!.github/workflows/build-macos.yml' - + # the github release drafter can call this workflow workflow_call: @@ -54,7 +54,7 @@ jobs: uses: actions/cache@v4.0.2 with: path: ${{ github.workspace }}/pygame_mac_deps_${{ matrix.macarch }} - # The hash of all files in buildconfig manylinux-build and macdependencies is + # The hash of all files in buildconfig manylinux-build and macdependencies is # the key to the cache. If anything changes here, the deps are built again key: macdep-${{ hashFiles('buildconfig/manylinux-build/**') }}-${{ hashFiles('buildconfig/macdependencies/*.sh') }}-${{ matrix.macarch }}-${{ matrix.os }} lookup-only: true @@ -145,4 +145,3 @@ jobs: name: pygame-wheels-macos-${{ matrix.macarch }} path: ./wheelhouse/*.whl compression-level: 0 # wheels are already zip files, no need for more compression - diff --git a/.github/workflows/build-manylinux.yml b/.github/workflows/build-manylinux.yml index 981d7f7676..a8a0169a83 100644 --- a/.github/workflows/build-manylinux.yml +++ b/.github/workflows/build-manylinux.yml @@ -1,7 +1,7 @@ name: ManyLinux -# Run CI only when a release is created, on changes to main branch, or any PR -# to main. Do not run CI on any other branch. Also, skip any non-source changes +# Run CI only when a release is created, on changes to main branch, or any PR +# to main. Do not run CI on any other branch. Also, skip any non-source changes # from running on CI on: push: @@ -27,7 +27,7 @@ on: - '.github/workflows/*.yml' # re-include current file to not be excluded - '!.github/workflows/build-manylinux.yml' - + # the github release drafter can call this workflow workflow_call: @@ -42,12 +42,12 @@ jobs: permissions: contents: read packages: write - + strategy: fail-fast: false # if a particular matrix build fails, don't skip the rest matrix: arch: [x86_64, i686] - + env: CIBW_ARCHS: ${{ matrix.arch }} @@ -60,7 +60,7 @@ jobs: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - + - name: Inspect image, skip build if image exists id: inspect continue-on-error: true @@ -100,4 +100,3 @@ jobs: name: pygame-wheels-manylinux-${{ matrix.arch }} path: ./wheelhouse/*.whl compression-level: 0 # wheels are already zip files, no need for more compression - diff --git a/.github/workflows/build-ubuntu-sdist.yml b/.github/workflows/build-ubuntu-sdist.yml index bd82a5f210..3d90e3fdbc 100644 --- a/.github/workflows/build-ubuntu-sdist.yml +++ b/.github/workflows/build-ubuntu-sdist.yml @@ -7,8 +7,8 @@ name: Ubuntu sdist -# Run CI only when a release is created, on changes to main branch, or any PR -# to main. Do not run CI on any other branch. Also, skip any non-source changes +# Run CI only when a release is created, on changes to main branch, or any PR +# to main. Do not run CI on any other branch. Also, skip any non-source changes # from running on CI on: push: @@ -34,7 +34,7 @@ on: - '.github/workflows/*.yml' # re-include current file to not be excluded - '!.github/workflows/build-ubuntu-sdist.yml' - + # the github release drafter can call this workflow workflow_call: @@ -44,7 +44,7 @@ concurrency: jobs: build: - runs-on: ${{ matrix.os }} + runs-on: ${{ matrix.os }} strategy: fail-fast: false # if a particular matrix build fails, don't skip the rest matrix: @@ -74,7 +74,7 @@ jobs: SDL_VIDEODRIVER: "dummy" SDL_AUDIODRIVER: "disk" run: python3 -m pygame.tests -v --exclude opengl,music,timing --time_out 300 - + - name: Test typestubs if: matrix.os == 'ubuntu-22.04' # run stubtest only once run: | @@ -89,4 +89,3 @@ jobs: name: pygame-wheels-sdist path: dist/*.tar.gz compression-level: 0 # already compressed, no need for more compression - diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml index bfc36200f5..a0264e2616 100644 --- a/.github/workflows/build-windows.yml +++ b/.github/workflows/build-windows.yml @@ -27,7 +27,7 @@ on: - '.github/workflows/*.yml' # re-include current file to not be excluded - '!.github/workflows/build-windows.yml' - + # the github release drafter can call this workflow workflow_call: diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index c2e3793dfd..dba4697836 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -5,6 +5,26 @@ # Then in the project root directory run `pre-commit install` repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: end-of-file-fixer + exclude: | + (?x)^( + ^docs/licenses/.*$ + | ^.*\.svg$ + | ^.*\.sfd$ + | docs/LGPL.txt + )$ + - id: trailing-whitespace + exclude: | + (?x)^( + ^docs/licenses/.*$ + | ^.*\.svg$ + | ^.*\.sfd$ + | docs/LGPL.txt + )$ + - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.4.2 hooks: # See pyproject.toml for configuration options. diff --git a/buildconfig/Setup.Emscripten.SDL2.in b/buildconfig/Setup.Emscripten.SDL2.in index d7273a6d7e..28e86f1e42 100644 --- a/buildconfig/Setup.Emscripten.SDL2.in +++ b/buildconfig/Setup.Emscripten.SDL2.in @@ -75,5 +75,3 @@ _sdl2.touch src_c/void.c #transform src_c/simd_transform_sse2.c src_c/simd_transform_avx2.c src_c/transform.c src_c/rotozoom.c src_c/scale2x.c src_c/scale_mmx.c src_c/simd_surface_fill_avx2.c src_c/simd_surface_fill_sse2.c $(SDL) $(DEBUG) -D_NO_MMX_FOR_X86_64 transform src_c/void.c - - diff --git a/buildconfig/ci/circleci/pull_circleci_artifacts.py b/buildconfig/ci/circleci/pull_circleci_artifacts.py index dbfc4425c1..43494ae66a 100644 --- a/buildconfig/ci/circleci/pull_circleci_artifacts.py +++ b/buildconfig/ci/circleci/pull_circleci_artifacts.py @@ -2,7 +2,7 @@ A script to automate downloading CircleCI artifacts. Usage: python3 pull_circleci_artifacts.py - TOKEN: + TOKEN: CircleCI "personal access token" of a github (preferably machine) user. This is secret! diff --git a/buildconfig/config_emsdk.py b/buildconfig/config_emsdk.py index d5ef458fdc..5063d24520 100644 --- a/buildconfig/config_emsdk.py +++ b/buildconfig/config_emsdk.py @@ -267,4 +267,3 @@ def main(auto_config=False): if __name__ == "__main__": print("This is the configuration subscript for Emscripten.") print('Please run "config.py" for full configuration.') - diff --git a/buildconfig/config_unix.py b/buildconfig/config_unix.py index c5d0b457ec..a9ebc83945 100644 --- a/buildconfig/config_unix.py +++ b/buildconfig/config_unix.py @@ -141,7 +141,7 @@ def main(auto_config=False): origincdirs = ['/include', '/include/SDL2'] origlibdirs = ['/lib', '/lib64', '/X11R6/lib'] - # If we are on a debian based system, we also need to handle + # If we are on a debian based system, we also need to handle # /lib/ # We have a few commands to get the correct , we try those # one by one till we get something that works diff --git a/buildconfig/config_win.py b/buildconfig/config_win.py index 886d860b4e..13dc13b611 100644 --- a/buildconfig/config_win.py +++ b/buildconfig/config_win.py @@ -372,7 +372,7 @@ def _add_sdl2_dll_deps(DEPS): DEPS.add_dll(r'(z|zlib1)\.dll$', 'z', ['zlib-[1-9].*']) DEPS.add_dll(r'(lib)?webp[-0-9]*\.dll$', 'webp', ['*webp-[0-9]*']) DEPS.add_dll(r'(lib)?webpdemux[-0-9]*\.dll$', 'webpdemux', ['*webpdemux-[0-9]*']) - + def setup(): DEPS = DependencyGroup() diff --git a/buildconfig/macdependencies/README.rst b/buildconfig/macdependencies/README.rst index 81b1fbec87..2788a8547f 100644 --- a/buildconfig/macdependencies/README.rst +++ b/buildconfig/macdependencies/README.rst @@ -32,4 +32,3 @@ fi It currently relies on GNU `readlink` to build, which is provided by the coreutils homebrew package. However, this could be fixed to be cross platform, since mac `readlink` does not support `-f`. - diff --git a/buildconfig/manylinux-build/Makefile b/buildconfig/manylinux-build/Makefile index 68d7f766bb..a5532c8281 100644 --- a/buildconfig/manylinux-build/Makefile +++ b/buildconfig/manylinux-build/Makefile @@ -70,7 +70,7 @@ push-manylinux2014-x86: push-manylinux2014-aarch64: docker push pygame/manylinux2014_base_aarch64 - + # push: push-manylinux1-x64 push-manylinux1-x86 push-manylinux2010-x64 push-manylinux2010-x86 push-manylinux2014-x64 push-manylinux2014-x86 push: push-manylinux2010-x64 push-manylinux2010-x86 push-manylinux2014-x64 push-manylinux2014-x86 push-manylinux2014-aarch64 diff --git a/buildconfig/manylinux-build/docker_base/Dockerfile-aarch64 b/buildconfig/manylinux-build/docker_base/Dockerfile-aarch64 index ed26478e24..cdfc9b712e 100644 --- a/buildconfig/manylinux-build/docker_base/Dockerfile-aarch64 +++ b/buildconfig/manylinux-build/docker_base/Dockerfile-aarch64 @@ -163,4 +163,3 @@ RUN ["bash", "/portmidi_build/build-portmidi.sh"] # run strip on built libraries COPY strip-lib-so-files.sh /tmp/ RUN source /tmp/strip-lib-so-files.sh - diff --git a/buildconfig/manylinux-build/docker_base/alsa/build-alsa.sh b/buildconfig/manylinux-build/docker_base/alsa/build-alsa.sh index 9a9fdcb2b5..11ecb100af 100644 --- a/buildconfig/manylinux-build/docker_base/alsa/build-alsa.sh +++ b/buildconfig/manylinux-build/docker_base/alsa/build-alsa.sh @@ -11,6 +11,6 @@ tar xjf ${ALSA}.tar.bz2 cd ${ALSA} # alsa prefers /usr prefix as a default, so we explicitly override it -./configure $PG_BASE_CONFIGURE_FLAGS --with-configdir=$PG_DEP_PREFIX/share/alsa +./configure $PG_BASE_CONFIGURE_FLAGS --with-configdir=$PG_DEP_PREFIX/share/alsa make make install diff --git a/buildconfig/manylinux-build/docker_base/buildtools/install.sh b/buildconfig/manylinux-build/docker_base/buildtools/install.sh index b3d49e116d..95f50c050a 100644 --- a/buildconfig/manylinux-build/docker_base/buildtools/install.sh +++ b/buildconfig/manylinux-build/docker_base/buildtools/install.sh @@ -4,7 +4,7 @@ set -e -x cd $(dirname `readlink -f "$0"`) # This file installs tools (cmake and meson+ninja) needed to build dependencies -# Also installs setuptools to make sure distutils is available (on newer python +# Also installs setuptools to make sure distutils is available (on newer python # versions) because some builds may need it. # cmake is also installed via pip because it is easier than maintaining a # separate build script for it diff --git a/buildconfig/manylinux-build/docker_base/glib/build-glib.sh b/buildconfig/manylinux-build/docker_base/glib/build-glib.sh index 83543e51ce..0a1b78c895 100644 --- a/buildconfig/manylinux-build/docker_base/glib/build-glib.sh +++ b/buildconfig/manylinux-build/docker_base/glib/build-glib.sh @@ -20,4 +20,3 @@ meson setup _build $PG_BASE_MESON_FLAGS --force-fallback-for libpcre2-8 -Dtests= meson compile -C _build meson install -C _build - diff --git a/buildconfig/manylinux-build/docker_base/libmodplug/build-libmodplug.sh b/buildconfig/manylinux-build/docker_base/libmodplug/build-libmodplug.sh index de3a1211ca..b5d3ed3b72 100644 --- a/buildconfig/manylinux-build/docker_base/libmodplug/build-libmodplug.sh +++ b/buildconfig/manylinux-build/docker_base/libmodplug/build-libmodplug.sh @@ -15,4 +15,3 @@ cd ${MODPLUG_NAME} ./configure $PG_BASE_CONFIGURE_FLAGS make make install - diff --git a/buildconfig/manylinux-build/docker_base/libpng/build-png.sh b/buildconfig/manylinux-build/docker_base/libpng/build-png.sh index 92fdff9592..105b1a427f 100644 --- a/buildconfig/manylinux-build/docker_base/libpng/build-png.sh +++ b/buildconfig/manylinux-build/docker_base/libpng/build-png.sh @@ -14,4 +14,3 @@ cd $PNG ./configure --with-zlib-prefix=$PG_DEP_PREFIX $PG_BASE_CONFIGURE_FLAGS make make install - diff --git a/buildconfig/manylinux-build/docker_base/mesa/mesa/build-mesa.sh b/buildconfig/manylinux-build/docker_base/mesa/mesa/build-mesa.sh index 308f4d459e..db5c5c94bd 100644 --- a/buildconfig/manylinux-build/docker_base/mesa/mesa/build-mesa.sh +++ b/buildconfig/manylinux-build/docker_base/mesa/mesa/build-mesa.sh @@ -3,7 +3,7 @@ set -e -x cd $(dirname `readlink -f "$0"`) -# We need mesa for opengl, gbm (SDL kmsdrm driver needs it), egl (SDL +# We need mesa for opengl, gbm (SDL kmsdrm driver needs it), egl (SDL # wayland driver needs this) and glx (SDL needs it) # we don't support vulkan yet @@ -21,7 +21,7 @@ cd $MESA if [ `uname -m` == "aarch64" ]; then # On aarch64 we allow mesa to use all drivers it wants to pick by default # (because radeonsi is not used on arm platforms) - GALLIUM_DRIVERS="auto" + GALLIUM_DRIVERS="auto" else # all default except radeonsi GALLIUM_DRIVERS="r300,r600,nouveau,virgl,svga,swrast,iris,crocus,i915" diff --git a/buildconfig/manylinux-build/docker_base/ogg/build-ogg.sh b/buildconfig/manylinux-build/docker_base/ogg/build-ogg.sh index 4029ff4521..ef670d6ea8 100644 --- a/buildconfig/manylinux-build/docker_base/ogg/build-ogg.sh +++ b/buildconfig/manylinux-build/docker_base/ogg/build-ogg.sh @@ -36,4 +36,3 @@ elif [[ "$OSTYPE" == "darwin"* ]]; then fi make make install - diff --git a/buildconfig/manylinux-build/docker_base/pkg-config/build-pkg-config.sh b/buildconfig/manylinux-build/docker_base/pkg-config/build-pkg-config.sh index c2764c1ba9..fd6e0a2683 100644 --- a/buildconfig/manylinux-build/docker_base/pkg-config/build-pkg-config.sh +++ b/buildconfig/manylinux-build/docker_base/pkg-config/build-pkg-config.sh @@ -1,6 +1,6 @@ #!/bin/bash -# This file exists because pkg-config is too old on manylinux docker centos +# This file exists because pkg-config is too old on manylinux docker centos # images (the older version segfaults if it gets a cyclic dependency, like # freetype2+harfbuzz) diff --git a/buildconfig/manylinux-build/docker_base/sdl_libs/build-sdl2-libs.sh b/buildconfig/manylinux-build/docker_base/sdl_libs/build-sdl2-libs.sh index fad5829303..26a6ec525f 100644 --- a/buildconfig/manylinux-build/docker_base/sdl_libs/build-sdl2-libs.sh +++ b/buildconfig/manylinux-build/docker_base/sdl_libs/build-sdl2-libs.sh @@ -114,4 +114,3 @@ cd $MIX2 make make install - diff --git a/buildconfig/manylinux-build/docker_base/sndfile/build-sndfile.sh b/buildconfig/manylinux-build/docker_base/sndfile/build-sndfile.sh index 265ea9af15..660b932219 100644 --- a/buildconfig/manylinux-build/docker_base/sndfile/build-sndfile.sh +++ b/buildconfig/manylinux-build/docker_base/sndfile/build-sndfile.sh @@ -17,4 +17,3 @@ cd $SNDNAME ./configure $PG_BASE_CONFIGURE_FLAGS --disable-mpeg --disable-alsa make make install - diff --git a/buildconfig/manylinux-build/docker_base/zlib-ng/build-zlib-ng.sh b/buildconfig/manylinux-build/docker_base/zlib-ng/build-zlib-ng.sh index d00587d5a5..29033209ab 100644 --- a/buildconfig/manylinux-build/docker_base/zlib-ng/build-zlib-ng.sh +++ b/buildconfig/manylinux-build/docker_base/zlib-ng/build-zlib-ng.sh @@ -14,4 +14,3 @@ cd ${ZLIB_NG_NAME} cmake . $PG_BASE_CMAKE_FLAGS -DZLIB_COMPAT=1 make make install - diff --git a/buildconfig/manylinux-build/docker_base/zlib/build-zlib.sh b/buildconfig/manylinux-build/docker_base/zlib/build-zlib.sh index 6cbaae0551..9f99471caf 100644 --- a/buildconfig/manylinux-build/docker_base/zlib/build-zlib.sh +++ b/buildconfig/manylinux-build/docker_base/zlib/build-zlib.sh @@ -14,4 +14,3 @@ cd ${ZLIB_NAME} ./configure $PG_BASE_CONFIGURE_FLAGS make make install - diff --git a/buildconfig/stubs/gen_stubs.py b/buildconfig/stubs/gen_stubs.py index da679ac8f8..488ba2cfc7 100644 --- a/buildconfig/stubs/gen_stubs.py +++ b/buildconfig/stubs/gen_stubs.py @@ -74,7 +74,7 @@ "window": ["Window"], "base": ["__version__"], # need an explicit import # uncomment below line if Circle is added to the base namespace later - # "geometry": ["Circle"], + # "geometry": ["Circle"], } # pygame modules from which __init__.py does the equivalent of @@ -153,7 +153,7 @@ def get_all(mod: Any): for element in get_all(pygame.locals): constant_type = getattr(pygame.locals, element).__class__.__name__ f.write(f"{element}: {constant_type}\n") - + # copy typing.py to typing.pyi for type checkers typing_py_file = pathlib.Path(__file__).parent.parent.parent / "src_py" / "typing.py" typing_stub_file = pathlib.Path(__file__).parent / "pygame" / "typing.pyi" diff --git a/buildconfig/stubs/mypy_allow_list.txt b/buildconfig/stubs/mypy_allow_list.txt index d8f8c6c0d3..1e7c532d72 100644 --- a/buildconfig/stubs/mypy_allow_list.txt +++ b/buildconfig/stubs/mypy_allow_list.txt @@ -5,7 +5,7 @@ # cython files have this top level dunder pygame\._sdl2\..*\.__test__ -# cython classes have some special dunders for internal use, ignore that in +# cython classes have some special dunders for internal use, ignore that in # stubtest pygame\._sdl2\..*\.__pyx_.*__ diff --git a/buildconfig/stubs/pygame/rect.pyi b/buildconfig/stubs/pygame/rect.pyi index 9899c84270..79acedeab9 100644 --- a/buildconfig/stubs/pygame/rect.pyi +++ b/buildconfig/stubs/pygame/rect.pyi @@ -280,7 +280,7 @@ class _GenericRect(Collection[_N]): # Sized, Iterable and Container ABCs class Rect(_GenericRect[int]): ... - + class FRect(_GenericRect[float]): ... diff --git a/buildconfig/stubs/pygame/sprite.pyi b/buildconfig/stubs/pygame/sprite.pyi index 9185018c1c..8c129ff936 100644 --- a/buildconfig/stubs/pygame/sprite.pyi +++ b/buildconfig/stubs/pygame/sprite.pyi @@ -181,7 +181,7 @@ class Group(AbstractGroup[_TSprite]): def __init__( self, *sprites: Union[_TSprite, AbstractGroup[_TSprite], Iterable[_TSprite]] ) -> None: ... - + # these are aliased in the code too @deprecated("Use `pygame.sprite.Group` instead") class RenderPlain(Group): ... diff --git a/buildconfig/stubs/stubcheck.py b/buildconfig/stubs/stubcheck.py index 1389e07595..d0c544a4c8 100644 --- a/buildconfig/stubs/stubcheck.py +++ b/buildconfig/stubs/stubcheck.py @@ -23,7 +23,7 @@ def typing_check(): except subprocess.CalledProcessError: print("ERROR: could not validate typing.py, make sure you have mypy installed") return - + mypy_args = [*mypy_version_args, "typing_sample_app.py"] cmd = " ".join(mypy_args) print(f"Using mypy invocation: `{cmd}` (version: {version})") @@ -35,7 +35,7 @@ def typing_check(): raise RuntimeError(f"mypy process finished with unsuccessful return code {returncode}") finally: os.chdir(prev_dir) - + def stubs_check(): """ Validate the stubs files diff --git a/docs/reST/c_api/base.rst b/docs/reST/c_api/base.rst index c2117460ac..9c20197f5f 100644 --- a/docs/reST/c_api/base.rst +++ b/docs/reST/c_api/base.rst @@ -92,7 +92,7 @@ C header: src_c/include/pygame.h .. c:function:: int pg_RGBAFromObj(PyObject *obj, Uint8 *RGBA) You probably want to use the :c:func:`pg_RGBAFromObjEx` function instead of this. - + Convert the color represented by object *obj* into a red, green, blue, alpha length 4 C array *RGBA*. The object must be a length 3 or 4 sequence of numbers having values diff --git a/docs/reST/c_api/event.rst b/docs/reST/c_api/event.rst index 7f053faf3d..650dccd25b 100644 --- a/docs/reST/c_api/event.rst +++ b/docs/reST/c_api/event.rst @@ -40,7 +40,7 @@ Header file: src_c/include/pygame.h On failure raise a Python exception and return ``NULL``. .. c:function:: char* pgEvent_GetKeyDownInfo(void) - + Return an array of bools (using char) of length SDL_NUM_SCANCODES with the most recent key presses. diff --git a/docs/reST/c_api/mixer.rst b/docs/reST/c_api/mixer.rst index e9d947c42d..6cd281a2df 100644 --- a/docs/reST/c_api/mixer.rst +++ b/docs/reST/c_api/mixer.rst @@ -64,4 +64,3 @@ Header file: src_c/include/pygame_mixer.h Return the SDL mixer music channel number associated with :c:type:`pgChannel_Type` instance *x*. A macro that does no ``NULL`` or Python type check on *x*. - diff --git a/docs/reST/c_api/rwobject.rst b/docs/reST/c_api/rwobject.rst index c734442def..3507118451 100644 --- a/docs/reST/c_api/rwobject.rst +++ b/docs/reST/c_api/rwobject.rst @@ -56,4 +56,4 @@ Header file: src_c/include/pygame.h :c:func:`PyUnicode_AsEncodedString`. On error raise a Python exception and return ``NULL``, using *eclass* as the exception type if it is not ``NULL``. - If *obj* is ``NULL`` assume an exception was already raised and pass it on. \ No newline at end of file + If *obj* is ``NULL`` assume an exception was already raised and pass it on. diff --git a/docs/reST/index.rst b/docs/reST/index.rst index f26e610471..229acc023b 100644 --- a/docs/reST/index.rst +++ b/docs/reST/index.rst @@ -41,9 +41,9 @@ documentation by module. Experimental modules -------------------- -Experimental modules are work in progress, this is why you should refrain from relying on any features -provided by these modules, as they are subject to change or removal without prior notice. -If you want to test these experimental modules, you might want to understand how you import +Experimental modules are work in progress, this is why you should refrain from relying on any features +provided by these modules, as they are subject to change or removal without prior notice. +If you want to test these experimental modules, you might want to understand how you import them, this is how you can do it: .. code-block:: python @@ -54,7 +54,7 @@ them, this is how you can do it: # Or import pygame.experimental_module -Don't forget to report us any problem with the experimental features on `github`_ so we can easily +Don't forget to report us any problem with the experimental features on `github`_ so we can easily turn them to stable API in the future ^^. **Below is currently the list of experimental modules :** diff --git a/docs/reST/logos.rst b/docs/reST/logos.rst index f8db3b443f..5a6d83b20a 100644 --- a/docs/reST/logos.rst +++ b/docs/reST/logos.rst @@ -43,7 +43,7 @@ Upstream & legacy logos The pygame logo was originally created by TheCorruptor on July 29, 2001. -It was upscaled alongside its "LoFi" and "Powered" variants by Mega-JC on +It was upscaled alongside its "LoFi" and "Powered" variants by Mega-JC on August 29, 2021. .. container:: fullwidth diff --git a/docs/reST/ref/bufferproxy.rst b/docs/reST/ref/bufferproxy.rst index 4936a4102d..6b3e04089c 100644 --- a/docs/reST/ref/bufferproxy.rst +++ b/docs/reST/ref/bufferproxy.rst @@ -65,7 +65,7 @@ The callback is passed on argument, the ``"parent"`` object if given, otherwise None. The callback is useful for releasing a lock on the parent. - + The BufferProxy class supports subclassing, instance variables, and weak references. diff --git a/docs/reST/ref/code_examples/cursors_module_example.py b/docs/reST/ref/code_examples/cursors_module_example.py index 71f67b723f..517ca1fd11 100644 --- a/docs/reST/ref/code_examples/cursors_module_example.py +++ b/docs/reST/ref/code_examples/cursors_module_example.py @@ -11,11 +11,11 @@ # create bitmap cursors bitmap_1 = pygame.cursors.Cursor(*pygame.cursors.arrow) bitmap_2 = pygame.cursors.Cursor( - (24, 24), (0, 0), *pygame.cursors.compile(pygame.cursors.thickarrow_strings) + (24, 24), (0, 0), *pygame.cursors.compile(pygame.cursors.thickarrow_strings) ) # create a color cursor -surf = pygame.Surface((40, 40)) # you could also load an image +surf = pygame.Surface((40, 40)) # you could also load an image surf.fill((120, 50, 50)) # and use that as your surface color = pygame.cursors.Cursor((20, 20), surf) diff --git a/docs/reST/ref/code_examples/draw_module_example.py b/docs/reST/ref/code_examples/draw_module_example.py index 99c2c89f9d..ce13298477 100644 --- a/docs/reST/ref/code_examples/draw_module_example.py +++ b/docs/reST/ref/code_examples/draw_module_example.py @@ -77,13 +77,13 @@ # Draw a circle pygame.draw.circle(screen, "blue", [60, 250], 40) - + # Draw an antialiased circle with 3 pixels wide line pygame.draw.aacircle(screen, "green", [340, 250], 40, 3) - + # Draw an antialiased top right circle quadrant with 4 pixels wide line pygame.draw.aacircle(screen, "red", [340, 250], 20, 4, draw_top_right=True) - + # Draw an antialiased bottom left filled circle quadrant pygame.draw.aacircle(screen, "blue", [340, 250], 20, draw_bottom_left=True) diff --git a/docs/reST/ref/color.rst b/docs/reST/ref/color.rst index b257aaea37..4d36c23fcc 100644 --- a/docs/reST/ref/color.rst +++ b/docs/reST/ref/color.rst @@ -196,7 +196,7 @@ | :sl:`Gets or sets the normalized representation of the Color.` | :sg:`normalized -> tuple` - + The ``Normalized``` representation of the Color. The components of the ``Normalized`` representation represent the basic ``RGBA`` values but normalized the ranges of the values are ``r`` = [0, 1], ``g`` = [0, 1], ``b`` = [0, 1] @@ -209,7 +209,7 @@ .. versionadded:: 2.5.0 .. ## Color.normalized ## - + .. classmethod:: from_cmy | :sl:`Returns a Color object from a CMY representation` @@ -222,7 +222,7 @@ .. versionadded:: 2.3.1 .. ## Color.from_cmy ## - + .. classmethod:: from_hsva | :sl:`Returns a Color object from an HSVA representation` @@ -235,7 +235,7 @@ .. versionadded:: 2.3.1 .. ## Color.from_hsva ## - + .. classmethod:: from_hsla | :sl:`Returns a Color object from an HSLA representation` @@ -300,11 +300,11 @@ | :sl:`Set the number of elements in the Color to 1,2,3, or 4.` | :sg:`set_length(len, /) -> None` - DEPRECATED: You may unpack the values you need like so, + DEPRECATED: You may unpack the values you need like so, ``r, g, b, _ = pygame.Color(100, 100, 100)`` If you only want r, g and b - Or - ``r, g, *_ = pygame.Color(100, 100, 100)`` + Or + ``r, g, *_ = pygame.Color(100, 100, 100)`` if you only want r and g The default Color length is 4. Colors can have lengths 1,2,3 or 4. This @@ -320,8 +320,8 @@ | :sl:`returns the grayscale of a Color` | :sg:`grayscale() -> Color` - - Returns a new Color object which represents the grayscaled version of self, using the luminosity formula, + + Returns a new Color object which represents the grayscaled version of self, using the luminosity formula, which weights red, green, and blue according to their relative contribution to perceived brightness. .. versionadded:: 2.1.4 diff --git a/docs/reST/ref/common.txt b/docs/reST/ref/common.txt index 05685a1108..9373ee3e6b 100644 --- a/docs/reST/ref/common.txt +++ b/docs/reST/ref/common.txt @@ -1,2 +1 @@ .. include:: ../common.txt - diff --git a/docs/reST/ref/cursors.rst b/docs/reST/ref/cursors.rst index 1a1e8f97db..009bfa23f8 100644 --- a/docs/reST/ref/cursors.rst +++ b/docs/reST/ref/cursors.rst @@ -23,7 +23,7 @@ single tuple you can call like this: :: >>> pygame.mouse.set_cursor(*pygame.cursors.arrow) - + The following variables can be passed to ``pygame.mouse.set_cursor`` function: * ``pygame.cursors.arrow`` @@ -55,7 +55,7 @@ The following strings can be converted into cursor bitmaps with * ``pygame.cursors.sizer_y_strings`` * ``pygame.cursors.sizer_xy_strings`` - + * ``pygame.cursor.textmarker_strings`` .. function:: compile @@ -65,15 +65,15 @@ The following strings can be converted into cursor bitmaps with A sequence of strings can be used to create binary cursor data for the system cursor. This returns the binary data in the form of two tuples. - Those can be passed as the third and fourth arguments respectively of the + Those can be passed as the third and fourth arguments respectively of the :func:`pygame.mouse.set_cursor()` function. If you are creating your own cursor strings, you can use any value represent the black and white pixels. Some system allow you to set a special toggle color for the system color, this is also called the xor color. If the system does not support xor cursors, that color will simply be black. - - The height must be divisible by 8. The width of the strings must all be equal + + The height must be divisible by 8. The width of the strings must all be equal and be divisible by 8. If these two conditions are not met, ``ValueError`` is raised. An example set of cursor strings looks like this @@ -144,17 +144,17 @@ The following strings can be converted into cursor bitmaps with In pygame 2, there are 3 types of cursors you can create to give your game that little bit of extra polish. There's **bitmap** type cursors, which existed in pygame 1.x, and are compiled from a string or load from an xbm file. - Then there are **system** type cursors, where you choose a preset that will - convey the same meaning but look native across different operating systems. + Then there are **system** type cursors, where you choose a preset that will + convey the same meaning but look native across different operating systems. Finally you can create a **color** cursor, which displays a pygame surface as the cursor. **Creating a system cursor** - Choose a constant from this list, pass it into ``pygame.cursors.Cursor(constant)``, + Choose a constant from this list, pass it into ``pygame.cursors.Cursor(constant)``, and you're good to go. Be advised that not all systems support every system cursor, and you may get a substitution instead. For example, on macOS, WAIT/WAITARROW should show up as an arrow, and SIZENWSE/SIZENESW/SIZEALL - should show up as a closed hand. And on Wayland, every SIZE cursor should + should show up as a closed hand. And on Wayland, every SIZE cursor should show up as a hand. :: @@ -165,15 +165,15 @@ The following strings can be converted into cursor bitmaps with pygame.SYSTEM_CURSOR_IBEAM i-beam pygame.SYSTEM_CURSOR_WAIT wait pygame.SYSTEM_CURSOR_CROSSHAIR crosshair - pygame.SYSTEM_CURSOR_WAITARROW small wait cursor + pygame.SYSTEM_CURSOR_WAITARROW small wait cursor (or wait if not available) - pygame.SYSTEM_CURSOR_SIZENWSE double arrow pointing + pygame.SYSTEM_CURSOR_SIZENWSE double arrow pointing northwest and southeast pygame.SYSTEM_CURSOR_SIZENESW double arrow pointing northeast and southwest pygame.SYSTEM_CURSOR_SIZEWE double arrow pointing west and east - pygame.SYSTEM_CURSOR_SIZENS double arrow pointing + pygame.SYSTEM_CURSOR_SIZENS double arrow pointing north and south pygame.SYSTEM_CURSOR_SIZEALL four pointed arrow pointing north, south, east, and west @@ -181,7 +181,7 @@ The following strings can be converted into cursor bitmaps with pygame.SYSTEM_CURSOR_HAND hand **Creating a cursor without passing arguments** - + In addition to the cursor constants available and described above, you can also call ``pygame.cursors.Cursor()``, and your cursor is ready (doing that is the same as calling ``pygame.cursors.Cursor(pygame.SYSTEM_CURSOR_ARROW)``. @@ -196,34 +196,34 @@ The following strings can be converted into cursor bitmaps with **Creating a bitmap cursor** When the mouse cursor is visible, it will be displayed as a black and white - bitmap using the given bitmask arrays. The ``size`` is a sequence containing - the cursor width and height. ``hotspot`` is a sequence containing the cursor - hotspot position. - - A cursor has a width and height, but a mouse position is represented by a - set of point coordinates. So the value passed into the cursor ``hotspot`` - variable helps pygame to actually determine at what exact point the cursor + bitmap using the given bitmask arrays. The ``size`` is a sequence containing + the cursor width and height. ``hotspot`` is a sequence containing the cursor + hotspot position. + + A cursor has a width and height, but a mouse position is represented by a + set of point coordinates. So the value passed into the cursor ``hotspot`` + variable helps pygame to actually determine at what exact point the cursor is at. - - ``xormasks`` is a sequence of bytes containing the cursor xor data masks. + + ``xormasks`` is a sequence of bytes containing the cursor xor data masks. Lastly ``andmasks``, a sequence of bytes containing the cursor bitmask data. - To create these variables, we can make use of the + To create these variables, we can make use of the :func:`pygame.cursors.compile()` function. - Width and height must be a multiple of 8, and the mask arrays must be the + Width and height must be a multiple of 8, and the mask arrays must be the correct size for the given width and height. Otherwise an exception is raised. - + .. method:: copy | :sl:`copy the current cursor` | :sg:`copy() -> Cursor` - + Returns a new Cursor object with the same data and hotspot as the original. .. ## pygame.cursors.Cursor.copy ## - + .. attribute:: type - + | :sl:`get the cursor type` | :sg:`type -> string` @@ -243,7 +243,7 @@ The following strings can be converted into cursor bitmaps with .. versionaddedold:: 2.0.1 .. ## pygame.cursors.Cursor ## - + .. ## pygame.cursors ## Example code for creating and settings cursors. (Click the mouse to switch cursor) diff --git a/docs/reST/ref/draw.rst b/docs/reST/ref/draw.rst index 1c71eebe49..f9300ee153 100644 --- a/docs/reST/ref/draw.rst +++ b/docs/reST/ref/draw.rst @@ -606,4 +606,3 @@ object around the draw calls (see :func:`pygame.Surface.lock` and Example code for draw module. .. literalinclude:: code_examples/draw_module_example.py - diff --git a/docs/reST/ref/event.rst b/docs/reST/ref/event.rst index 89562572a9..b6c8349948 100644 --- a/docs/reST/ref/event.rst +++ b/docs/reST/ref/event.rst @@ -51,7 +51,7 @@ their own new events with the :func:`pygame.event.Event()` function. The event type identifier is in between the values of ``NOEVENT`` and ``NUMEVENTS``. User defined events should have a value in the inclusive range of ``USEREVENT`` to ``NUMEVENTS - 1``. User defined events can get a custom -event number with :func:`pygame.event.custom_type()`. +event number with :func:`pygame.event.custom_type()`. It is recommended all user events follow this system. Events support equality and inequality comparisons. Two events are equal if @@ -159,7 +159,7 @@ pygame 2 also supports controller hot-plugging Also in this version, ``instance_id`` attributes were added to joystick events, and the ``joy`` attribute was deprecated. -``KEYMAPCHANGED`` is a type of an event sent when keymap changes due to a +``KEYMAPCHANGED`` is a type of an event sent when keymap changes due to a system event such as an input language or keyboard layout change. ``CLIPBOARDUPDATE`` is an event sent when clipboard changes. This can still @@ -170,7 +170,7 @@ not trigger this event. .. versionaddedold:: 2.0.0 -.. versionadded:: 2.1.3 ``KEYMAPCHANGED``, ``CLIPBOARDUPDATE``, +.. versionadded:: 2.1.3 ``KEYMAPCHANGED``, ``CLIPBOARDUPDATE``, ``RENDER_TARGETS_RESET``, ``RENDER_DEVICE_RESET`` and ``LOCALECHANGED`` | @@ -301,7 +301,7 @@ On Android, the following events can be generated Returns a single event from the queue. If the queue is empty this function will wait until one is created. From pygame 2.0.0, if a ``timeout`` argument - is given, the function will return an event of type ``pygame.NOEVENT`` + is given, the function will return an event of type ``pygame.NOEVENT`` if no events enter the queue in ``timeout`` milliseconds. The event is removed from the queue once it has been returned. While the program is waiting it will sleep in an idle state. This is important for programs that want to share the diff --git a/docs/reST/ref/examples.rst b/docs/reST/ref/examples.rst index 201f20da30..88dc4d95e7 100644 --- a/docs/reST/ref/examples.rst +++ b/docs/reST/ref/examples.rst @@ -26,7 +26,7 @@ eg: python -m pygame.examples.scaletest someimage.png -Resources such as images and sounds for the examples are found in the +Resources such as images and sounds for the examples are found in the pygame/examples/data subdirectory. You can find where the example files are installed by using the following @@ -287,7 +287,7 @@ pygame much earlier. Thumbnail generation with scaling is an example of what you can do with pygame. - ``NOTE``: the pygame scale function uses SIMD acceleration if available, + ``NOTE``: the pygame scale function uses SIMD acceleration if available, and can be run in multiple threads. If ``headless_no_windows_needed.py`` is run as a program it takes the diff --git a/docs/reST/ref/font.rst b/docs/reST/ref/font.rst index acfc789212..a538a48aec 100644 --- a/docs/reST/ref/font.rst +++ b/docs/reST/ref/font.rst @@ -24,7 +24,7 @@ accessed by passing ``None`` as the font name. Before pygame 2.0.3, pygame.font accepts any UCS-2 / UTF-16 character ('\\u0001' to '\\uFFFF'). After 2.0.3, pygame.font built with SDL_ttf -2.0.15 accepts any valid UCS-4 / UTF-32 character +2.0.15 accepts any valid UCS-4 / UTF-32 character (like emojis, if the font has them) ('\\U00000001' to '\\U0010FFFF')). More about this in :func:`Font.render`. @@ -88,8 +88,8 @@ solves no longer exists, it will likely be removed in the future. Returns a tuple of integers that identify SDL_ttf's version. SDL_ttf is the underlying font rendering library, written in C, - on which pygame's font module depends. If 'linked' is True (the default), - the function returns the version of the linked TTF library. + on which pygame's font module depends. If 'linked' is True (the default), + the function returns the version of the linked TTF library. Otherwise this function returns the version of TTF pygame was compiled with .. versionadded:: 2.1.3 @@ -216,7 +216,7 @@ solves no longer exists, it will likely be removed in the future. | :sl:`Gets the font's style_name.` | :sg:`style_name -> str` - Read only. Returns the font's style name. Style names are arbitrary, can be an empty string. + Read only. Returns the font's style name. Style names are arbitrary, can be an empty string. Here are some examples: 'Black', 'Bold', 'Bold Italic', 'BoldOblique', 'Book', 'BookOblique', 'Condensed', 'Condensed Oblique', @@ -261,7 +261,7 @@ solves no longer exists, it will likely be removed in the future. .. versionaddedold:: 2.0.0 .. ## Font.underline ## - + .. attribute:: strikethrough | :sl:`Gets or sets whether the font should be rendered with a strikethrough.` @@ -311,7 +311,7 @@ solves no longer exists, it will likely be removed in the future. | :sl:`draw text on a new Surface` | :sg:`render(text, antialias, color, bgcolor=None, wraplength=0) -> Surface` - This creates a new Surface with the specified text rendered on it. + This creates a new Surface with the specified text rendered on it. :mod:`pygame.font` provides no way to directly draw text on an existing Surface: instead you must use :func:`Font.render` to create an image (Surface) of the text, then blit this image onto another Surface. @@ -405,7 +405,7 @@ solves no longer exists, it will likely be removed in the future. .. note:: This is the same as the :attr:`underline` attribute. .. ## Font.get_underline ## - + .. method:: set_strikethrough | :sl:`control if text is rendered with a strikethrough` @@ -416,7 +416,7 @@ solves no longer exists, it will likely be removed in the future. This can be mixed with the bold, italic and underline modes. .. note:: This is the same as the :attr:`strikethrough` attribute. - + .. versionadded:: 2.1.3 .. ## Font.set_strikethrough ## @@ -429,7 +429,7 @@ solves no longer exists, it will likely be removed in the future. Return True when the font strikethrough is enabled. .. note:: This is the same as the :attr:`strikethrough` attribute. - + .. versionadded:: 2.1.3 .. ## Font.get_strikethrough ## @@ -541,7 +541,7 @@ solves no longer exists, it will likely be removed in the future. Returns the point size of the font. Will not be accurate upon initializing the font object when the font name is initialized as ``None``. - + .. versionadded:: 2.3.1 .. ## Font.get_point_size ## @@ -581,7 +581,7 @@ solves no longer exists, it will likely be removed in the future. .. versionadded:: 2.1.4 - .. ## Font.set_script ## + .. ## Font.set_script ## .. method:: set_direction @@ -604,7 +604,7 @@ solves no longer exists, it will likely be removed in the future. or bottom-to-top rendering. .. versionadded:: 2.1.4 - + .. ## font.set_direction ## .. ## pygame.font.Font ## diff --git a/docs/reST/ref/freetype.rst b/docs/reST/ref/freetype.rst index bf6a74609e..04687be9ae 100644 --- a/docs/reST/ref/freetype.rst +++ b/docs/reST/ref/freetype.rst @@ -229,7 +229,7 @@ loaded. This module must be imported explicitly to be used. :: | :sl:`Gets the font's style_name.` | :sg:`style_name -> str` - Read only. Returns the font's style name. Style names are arbitrary, can be an empty string. + Read only. Returns the font's style name. Style names are arbitrary, can be an empty string. Here are some examples: 'Black', 'Bold', 'Bold Italic', 'BoldOblique', 'Book', 'BookOblique', 'Condensed', 'Condensed Oblique', diff --git a/docs/reST/ref/geometry.rst b/docs/reST/ref/geometry.rst index 57ad92f423..a7fc79e2f2 100644 --- a/docs/reST/ref/geometry.rst +++ b/docs/reST/ref/geometry.rst @@ -194,7 +194,7 @@ x, y coordinates and width, height as its argument. .. versionadded:: 2.4.0 - + .. ## Circle.colliderect ## .. method:: collideswith @@ -392,4 +392,4 @@ .. ## Circle.copy ## - .. ## pygame.Circle ## \ No newline at end of file + .. ## pygame.Circle ## diff --git a/docs/reST/ref/image.rst b/docs/reST/ref/image.rst index 3086f5b999..65438a9e82 100644 --- a/docs/reST/ref/image.rst +++ b/docs/reST/ref/image.rst @@ -63,7 +63,7 @@ following formats. * ``PNG`` * ``TGA`` - + ``JPEG`` and ``JPG``, as well as ``TIF`` and ``TIFF`` refer to the same file format @@ -244,10 +244,10 @@ following formats. the same size as how many bytes the pure pixel data of each horizontal line takes. .. note:: The use of this function is recommended over :func:`tostring` as of pygame 2.1.3. - This function was introduced so it matches nicely with other + This function was introduced so it matches nicely with other libraries (PIL, numpy, etc), and with people's expectations. - .. versionadded:: 2.1.3 + .. versionadded:: 2.1.3 .. versionchanged:: 2.2.0 Now supports keyword arguments. .. versionchanged:: 2.5.0 Added a 'pitch' argument. .. versionchanged:: 2.5.1 Added support for ABGR image format @@ -282,14 +282,14 @@ following formats. The 'pitch' argument can be used specify the pitch/stride per horizontal line of the image bytes in bytes. It must be equal to or greater than how many bytes the pixel data of each horizontal line in the image bytes occupies without any - extra padding. By default, it is ``-1``, which means that the pitch/stride is + extra padding. By default, it is ``-1``, which means that the pitch/stride is the same size as how many bytes the pure pixel data of each horizontal line takes. See the :func:`pygame.image.frombuffer()` method for a potentially faster way to transfer images into pygame. .. note:: The use of this function is recommended over :func:`fromstring` as of pygame 2.1.3. - This function was introduced so it matches nicely with other + This function was introduced so it matches nicely with other libraries (PIL, numpy, etc), and with people's expectations. .. versionadded:: 2.1.3 @@ -330,7 +330,7 @@ following formats. The 'pitch' argument can be used specify the pitch/stride per horizontal line of the image buffer in bytes. It must be equal to or greater than how many bytes the pixel data of each horizontal line in the image buffer occupies without any - extra padding. By default, it is ``-1``, which means that the pitch/stride is + extra padding. By default, it is ``-1``, which means that the pitch/stride is the same size as how many bytes the pure pixel data of each horizontal line takes. .. versionadded:: 2.1.3 BGRA format diff --git a/docs/reST/ref/joystick.rst b/docs/reST/ref/joystick.rst index bef725240d..0e89c13dcf 100644 --- a/docs/reST/ref/joystick.rst +++ b/docs/reST/ref/joystick.rst @@ -85,7 +85,7 @@ variable. See :ref:`environment variables ` for more deta | :sl:`Returns the number of joysticks.` | :sg:`get_count() -> count` - Return the number of joystick devices on the system. The count will be ``0`` + Return the number of joystick devices on the system. The count will be ``0`` if there are no joysticks on the system. When you create Joystick objects using ``Joystick(id)``, you pass an integer @@ -107,7 +107,7 @@ variable. See :ref:`environment variables ` for more deta .. versionchangedold:: 2.0.0 Joystick objects are now opened immediately on creation. - .. versionchanged:: 2.1.4 This class is also available through the ``pygame.Joystick`` + .. versionchanged:: 2.1.4 This class is also available through the ``pygame.Joystick`` alias. .. method:: init @@ -158,7 +158,7 @@ variable. See :ref:`environment variables ` for more deta .. deprecatedold:: 2.0.0 The original device index is not useful in pygame 2. Use - :meth:`.get_instance_id` instead. + :meth:`.get_instance_id` instead. .. method:: get_instance_id() -> int @@ -215,13 +215,13 @@ variable. See :ref:`environment variables ` for more deta two for the position. Controls like rudders and throttles are treated as additional axes. - The ``pygame.JOYAXISMOTION`` events will be in the range from ``-1.0`` - to ``1.0``. A value of ``0.0`` means the axis is centered. Gamepad devices - will usually be ``-1``, ``0``, or ``1`` with no values in between. Older - analog joystick axes will not always use the full ``-1`` to ``1`` range, - and the centered value will be some area around ``0``. - - Analog joysticks usually have a bit of noise in their axis, which will + The ``pygame.JOYAXISMOTION`` events will be in the range from ``-1.0`` + to ``1.0``. A value of ``0.0`` means the axis is centered. Gamepad devices + will usually be ``-1``, ``0``, or ``1`` with no values in between. Older + analog joystick axes will not always use the full ``-1`` to ``1`` range, + and the centered value will be some area around ``0``. + + Analog joysticks usually have a bit of noise in their axis, which will generate a lot of rapid small motion events. .. ## Joystick.get_numaxes ## @@ -232,9 +232,9 @@ variable. See :ref:`environment variables ` for more deta | :sg:`get_axis(axis_number, /) -> float` Returns the current position of a joystick axis. The value will range - from ``-1`` to ``1`` with a value of ``0`` being centered. You may want - to take into account some tolerance to handle jitter, and joystick drift - may keep the joystick from centering at ``0`` or using the full range of + from ``-1`` to ``1`` with a value of ``0`` being centered. You may want + to take into account some tolerance to handle jitter, and joystick drift + may keep the joystick from centering at ``0`` or using the full range of position values. The axis number must be an integer from ``0`` to ``get_numaxes() - 1``. @@ -302,8 +302,8 @@ variable. See :ref:`environment variables ` for more deta input. The ``pygame.JOYHATMOTION`` event is generated when the hat changes - position. The ``position`` attribute for the event contains a pair of - values that are either ``-1``, ``0``, or ``1``. A position of ``(0, 0)`` + position. The ``position`` attribute for the event contains a pair of + values that are either ``-1``, ``0``, or ``1``. A position of ``(0, 0)`` means the hat is centered. .. ## Joystick.get_numhats ## @@ -316,10 +316,10 @@ variable. See :ref:`environment variables ` for more deta Returns the current position of a position hat. The position is given as two values representing the ``x`` and ``y`` position for the hat. ``(0, 0)`` means centered. A value of ``-1`` means left/down and a value of ``1`` means - right/up: so ``(-1, 0)`` means left; ``(1, 0)`` means right; ``(0, 1)`` means + right/up: so ``(-1, 0)`` means left; ``(1, 0)`` means right; ``(0, 1)`` means up; ``(1, 1)`` means upper-right; etc. - This value is digital, ``i.e.``, each coordinate can be ``-1``, ``0`` or ``1`` + This value is digital, ``i.e.``, each coordinate can be ``-1``, ``0`` or ``1`` but never in-between. The hat number must be between ``0`` and ``get_numhats() - 1``. @@ -403,7 +403,7 @@ After SDL 2.24.0, The controller is recognized as "Nintendo Switch Joy-Con (L)". L Button 17 Button 14 ZL Button 19 Button 15 -Reference : D-pad Up points toward SL and SR buttons. +Reference : D-pad Up points toward SL and SR buttons. * **Hat/JoyStick**:: diff --git a/docs/reST/ref/key.rst b/docs/reST/ref/key.rst index d58adf034c..8feba790fb 100644 --- a/docs/reST/ref/key.rst +++ b/docs/reST/ref/key.rst @@ -266,10 +266,10 @@ for ``KMOD_NONE``, which should be compared using equals ``==``). For example: translate these pushed keys into a fully translated character value. See the ``pygame.KEYDOWN`` events on the :mod:`pygame.event` queue for this functionality. - + .. versionchanged:: 2.1.4 The collection of bools returned by ``get_pressed`` can not be iterated - over because the indexes of the internal tuple does not correspond to the + over because the indexes of the internal tuple does not correspond to the keycodes. .. ## pygame.key.get_pressed ## @@ -298,7 +298,7 @@ for ``KMOD_NONE``, which should be compared using equals ``==``). For example: ``KEYDOWN`` events :: - + if pygame.key.get_just_pressed()[pygame.K_b]: print("B key just pressed") @@ -310,7 +310,7 @@ for ``KMOD_NONE``, which should be compared using equals ``==``). For example: | :sl:`returns a pygame.key.ScancodeWrapper containing the most recent key releases` | :sg:`get_just_pressed() -> bools` - + Returns a mapping from key codes to booleans indicating which keys were newly released as of the last time events were processed. This can be used as a convenience function to detect keys that were released "this frame." @@ -325,7 +325,7 @@ for ``KMOD_NONE``, which should be compared using equals ``==``). For example: ``KEYUP`` events. :: - + if pygame.key.get_just_released()[pygame.K_b]: print("B key just released") diff --git a/docs/reST/ref/math.rst b/docs/reST/ref/math.rst index 4d93a46667..e359a4b899 100644 --- a/docs/reST/ref/math.rst +++ b/docs/reST/ref/math.rst @@ -11,13 +11,13 @@ The pygame math module currently provides Vector classes in two and three dimensions, ``Vector2`` and ``Vector3`` respectively. -They support the following numerical operations: ``vec + vec``, ``vec - vec``, -``vec * number``, ``number * vec``, ``vec / number``, ``vec // number``, ``vec += vec``, -``vec -= vec``, ``vec *= number``, ``vec /= number``, ``vec //= number``, ``round(vec, ndigits=0)``. +They support the following numerical operations: ``vec + vec``, ``vec - vec``, +``vec * number``, ``number * vec``, ``vec / number``, ``vec // number``, ``vec += vec``, +``vec -= vec``, ``vec *= number``, ``vec /= number``, ``vec //= number``, ``round(vec, ndigits=0)``. All these operations will be performed elementwise. -In addition ``vec * vec`` will perform a scalar-product (a.k.a. dot-product). -If you want to multiply every element from vector v with every element from +In addition ``vec * vec`` will perform a scalar-product (a.k.a. dot-product). +If you want to multiply every element from vector v with every element from vector w you can use the elementwise method: ``v.elementwise() * w`` The coordinates of a vector can be retrieved or set using attributes or @@ -145,11 +145,11 @@ Multiple coordinates can be set using slices or swizzling Example: .. code-block:: python - + > value = 50 > pygame.math.remap(0, 100, 0, 200, value) > 100.0 - + .. versionadded:: 2.5.0 @@ -167,8 +167,8 @@ Multiple coordinates can be set using slices or swizzling Some general information about the ``Vector2`` class. - .. versionchanged:: 2.1.3 - Inherited methods of vector subclasses now correctly return an instance of the + .. versionchanged:: 2.1.3 + Inherited methods of vector subclasses now correctly return an instance of the subclass instead of the superclass .. method:: dot @@ -224,7 +224,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`length_squared() -> float` calculates the Euclidean length of the vector which follows from the - Pythagorean theorem: ``vec.length_squared() == vec.x**2 + vec.y**2``. + Pythagorean theorem: ``vec.length_squared() == vec.x**2 + vec.y**2``. This is faster than ``vec.length()`` because it avoids the square root. .. ## Vector2.length_squared ## @@ -234,7 +234,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`returns a vector with the same direction but length 1.` | :sg:`normalize() -> Vector2` - Returns a new vector that has ``length`` equal to ``1`` and the same + Returns a new vector that has ``length`` equal to ``1`` and the same direction as self. .. ## Vector2.normalize ## @@ -244,7 +244,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`normalizes the vector in place so that its length is 1.` | :sg:`normalize_ip() -> None` - Normalizes the vector so that it has ``length`` equal to ``1``. + Normalizes the vector so that it has ``length`` equal to ``1``. The direction of the vector is not changed. .. ## Vector2.normalize_ip ## @@ -254,7 +254,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`tests if the vector is normalized i.e. has length == 1.` | :sg:`is_normalized() -> Bool` - Returns True if the vector has ``length`` equal to ``1``. Otherwise + Returns True if the vector has ``length`` equal to ``1``. Otherwise it returns ``False``. .. ## Vector2.is_normalized ## @@ -265,7 +265,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`scale_to_length(float, /) -> None` Scales the vector so that it has the given length. The direction of the - vector is not changed. You can also scale to length ``0``. If the vector + vector is not changed. You can also scale to length ``0``. If the vector is the zero vector (i.e. has length ``0`` thus no direction) a ``ValueError`` is raised. @@ -343,7 +343,7 @@ Multiple coordinates can be set using slices or swizzling Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self and - other the result is going to be. It must be a value between ``0`` and ``1`` + other the result is going to be. It must be a value between ``0`` and ``1`` where ``0`` means self and ``1`` means other will be returned. .. ## Vector2.lerp ## @@ -462,7 +462,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`angle_to(Vector2, /) -> float` Returns the angle from self to the passed ``Vector2`` that would rotate self - to be aligned with the passed ``Vector2`` without crossing over the negative + to be aligned with the passed ``Vector2`` without crossing over the negative x-axis. .. figure:: code_examples/angle_to.png @@ -477,7 +477,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`returns a tuple with radial distance and azimuthal angle.` | :sg:`as_polar() -> (r, phi)` - Returns a tuple ``(r, phi)`` where r is the radial distance, and phi + Returns a tuple ``(r, phi)`` where r is the radial distance, and phi is the azimuthal angle. .. ## Vector2.as_polar ## @@ -497,14 +497,14 @@ Multiple coordinates can be set using slices or swizzling | :sl:`projects a vector onto another.` | :sg:`project(Vector2, /) -> Vector2` - Returns the projected vector. This is useful for collision detection in finding the components in a certain direction (e.g. in direction of the wall). + Returns the projected vector. This is useful for collision detection in finding the components in a certain direction (e.g. in direction of the wall). For a more detailed explanation see `Wikipedia `_. .. versionaddedold:: 2.0.2 .. ## Vector2.project ## - + .. method:: copy | :sl:`Returns a copy of itself.` @@ -515,7 +515,7 @@ Multiple coordinates can be set using slices or swizzling .. versionaddedold:: 2.1.1 .. ## Vector2.copy ## - + .. method:: clamp_magnitude @@ -526,8 +526,8 @@ Multiple coordinates can be set using slices or swizzling **Experimental:** feature still in development available for testing and feedback. It may change. `Please leave clamp_magnitude feedback with authors `_ - Returns a new copy of a vector with the magnitude clamped between - ``max_length`` and ``min_length``. If only one argument is passed, it is + Returns a new copy of a vector with the magnitude clamped between + ``max_length`` and ``min_length``. If only one argument is passed, it is taken to be the ``max_length`` This function raises ``ValueError`` if ``min_length`` is greater than @@ -537,12 +537,12 @@ Multiple coordinates can be set using slices or swizzling .. versionchanged:: 2.4.0 It is now possible to use ``clamp_magnitude`` on a zero-vector as long as ``min_length`` is unspecified or 0. - + .. note:: Before pygame-ce 2.4.0, attempting to clamp a zero vector would always raise a ``ValueError`` .. ## Vector2.clamp_magnitude ## - + .. method:: clamp_magnitude_ip @@ -560,7 +560,7 @@ Multiple coordinates can be set using slices or swizzling .. versionchanged:: 2.4.0 It is now possible to use ``clamp_magnitude`` on a zero-vector as long as ``min_length`` is unspecified or 0. - + .. note:: Before pygame-ce 2.4.0, attempting to clamp a zero vector would always raise a ``ValueError`` @@ -583,11 +583,11 @@ Multiple coordinates can be set using slices or swizzling .. ## Vector2.update ## - + .. attribute:: epsilon - + | :sl:`Determines the tolerance of vector calculations.` - + Both Vector classes have a value named ``epsilon`` that defaults to ``1e-6``. This value acts as a numerical margin in various methods to account for floating point arithmetic errors. Specifically, ``epsilon`` is used in the following places: @@ -613,7 +613,7 @@ Multiple coordinates can be set using slices or swizzling print(v == u) # >> False You'll probably never have to change ``epsilon`` from the default value, but in rare situations you might - find that either the margin is too large or too small, in which case changing ``epsilon`` slightly + find that either the margin is too large or too small, in which case changing ``epsilon`` slightly might help you out. @@ -631,8 +631,8 @@ Multiple coordinates can be set using slices or swizzling Some general information about the Vector3 class. - .. versionchanged:: 2.1.3 - Inherited methods of vector subclasses now correctly return an instance of the + .. versionchanged:: 2.1.3 + Inherited methods of vector subclasses now correctly return an instance of the subclass instead of the superclass .. method:: dot @@ -667,7 +667,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`magnitude_squared() -> float` calculates the magnitude of the vector which follows from the - theorem: + theorem: ``vec.magnitude_squared() == vec.x**2 + vec.y**2 + vec.z**2``. This is faster than ``vec.magnitude()`` because it avoids the square root. @@ -680,7 +680,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`length() -> float` calculates the Euclidean length of the vector which follows from the - Pythagorean theorem: + Pythagorean theorem: ``vec.length() == math.sqrt(vec.x**2 + vec.y**2 + vec.z**2)`` .. ## Vector3.length ## @@ -691,8 +691,8 @@ Multiple coordinates can be set using slices or swizzling | :sg:`length_squared() -> float` calculates the Euclidean length of the vector which follows from the - Pythagorean theorem: - ``vec.length_squared() == vec.x**2 + vec.y**2 + vec.z**2``. + Pythagorean theorem: + ``vec.length_squared() == vec.x**2 + vec.y**2 + vec.z**2``. This is faster than ``vec.length()`` because it avoids the square root. .. ## Vector3.length_squared ## @@ -702,7 +702,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`returns a vector with the same direction but length 1.` | :sg:`normalize() -> Vector3` - Returns a new vector that has ``length`` equal to ``1`` and the same + Returns a new vector that has ``length`` equal to ``1`` and the same direction as self. .. ## Vector3.normalize ## @@ -712,7 +712,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`normalizes the vector in place so that its length is 1.` | :sg:`normalize_ip() -> None` - Normalizes the vector so that it has ``length`` equal to ``1``. The + Normalizes the vector so that it has ``length`` equal to ``1``. The direction of the vector is not changed. .. ## Vector3.normalize_ip ## @@ -722,7 +722,7 @@ Multiple coordinates can be set using slices or swizzling | :sl:`tests if the vector is normalized i.e. has length == 1.` | :sg:`is_normalized() -> Bool` - Returns True if the vector has ``length`` equal to ``1``. Otherwise it + Returns True if the vector has ``length`` equal to ``1``. Otherwise it returns ``False``. .. ## Vector3.is_normalized ## @@ -733,7 +733,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`scale_to_length(float, /) -> None` Scales the vector so that it has the given length. The direction of the - vector is not changed. You can also scale to length ``0``. If the vector + vector is not changed. You can also scale to length ``0``. If the vector is the zero vector (i.e. has length ``0`` thus no direction) a ``ValueError`` is raised. @@ -811,7 +811,7 @@ Multiple coordinates can be set using slices or swizzling Returns a Vector which is a linear interpolation between self and the given Vector. The second parameter determines how far between self an - other the result is going to be. It must be a value between ``0`` and + other the result is going to be. It must be a value between ``0`` and ``1``, where ``0`` means self and ``1`` means other will be returned. .. ## Vector3.lerp ## @@ -1096,7 +1096,7 @@ Multiple coordinates can be set using slices or swizzling | :sg:`rotate_z_ip_rad(angle, /) -> None` DEPRECATED: Use rotate_z_rad_ip() instead. - + .. deprecatedold:: 2.1.1 .. ## Vector3.rotate_z_ip_rad ## @@ -1149,13 +1149,13 @@ Multiple coordinates can be set using slices or swizzling | :sl:`projects a vector onto another.` | :sg:`project(Vector3, /) -> Vector3` - Returns the projected vector. This is useful for collision detection in finding the components in a certain direction (e.g. in direction of the wall). + Returns the projected vector. This is useful for collision detection in finding the components in a certain direction (e.g. in direction of the wall). For a more detailed explanation see `Wikipedia `_. .. versionaddedold:: 2.0.2 .. ## Vector3.project ## - + .. method:: copy | :sl:`Returns a copy of itself.` @@ -1174,8 +1174,8 @@ Multiple coordinates can be set using slices or swizzling | :sg:`clamp_magnitude(max_length, /) -> Vector3` | :sg:`clamp_magnitude(min_length, max_length, /) -> Vector3` - Returns a new copy of a vector with the magnitude clamped between - ``max_length`` and ``min_length``. If only one argument is passed, it is + Returns a new copy of a vector with the magnitude clamped between + ``max_length`` and ``min_length``. If only one argument is passed, it is taken to be the ``max_length`` This function raises ``ValueError`` if ``min_length`` is greater than @@ -1185,12 +1185,12 @@ Multiple coordinates can be set using slices or swizzling .. versionchanged:: 2.4.0 It is now possible to use ``clamp_magnitude`` on a zero-vector as long as ``min_length`` is unspecified or 0. - + .. note:: Before pygame-ce 2.4.0, attempting to clamp a zero vector would always raise a ``ValueError`` .. ## Vector3.clamp_magnitude ## - + .. method:: clamp_magnitude_ip @@ -1208,7 +1208,7 @@ Multiple coordinates can be set using slices or swizzling .. versionchanged:: 2.4.0 It is now possible to use ``clamp_magnitude`` on a zero-vector as long as ``min_length`` is unspecified or 0. - + .. note:: Before pygame-ce 2.4.0, attempting to clamp a zero vector would always raise a ``ValueError`` @@ -1233,9 +1233,9 @@ Multiple coordinates can be set using slices or swizzling .. attribute:: epsilon | :sl:`Determines the tolerance of vector calculations.` - + With lengths within this number, vectors are considered equal. For more information see :attr:`pygame.math.Vector2.epsilon` - + .. ## ## .. ## pygame.math.Vector3 ## diff --git a/docs/reST/ref/mixer.rst b/docs/reST/ref/mixer.rst index d23e2aa60a..5a441c7f81 100644 --- a/docs/reST/ref/mixer.rst +++ b/docs/reST/ref/mixer.rst @@ -68,7 +68,7 @@ The following file formats are supported Initialize the mixer module for Sound loading and playback. The default arguments can be overridden to provide specific audio mixing. Keyword - arguments are accepted. For backwards compatibility, argument values of + arguments are accepted. For backwards compatibility, argument values of 0 are replaced with the startup defaults, except for ``allowedchanges``, where -1 is used. (startup defaults may be changed by a :func:`pre_init` call). @@ -241,7 +241,7 @@ The following file formats are supported | :sg:`set_reserved(count, /) -> count` The mixer can reserve any number of channels that will not be automatically - selected for playback by Sounds. This means that whenever you play a Sound + selected for playback by Sounds. This means that whenever you play a Sound without specifying a channel, a reserved channel will never be used. If sounds are currently playing on the reserved channels they will not be stopped. @@ -292,7 +292,7 @@ The following file formats are supported | :sl:`get the soundfont for playing midi music` | :sg:`get_soundfont() -> paths` - This gets the soundfont filepaths as a string (each path is separated by a semi-colon) + This gets the soundfont filepaths as a string (each path is separated by a semi-colon) to be used in the playback of ``MID``, ``MIDI``, and ``KAR`` music file formats. If no soundfont is specified, the return type is ``None``. @@ -351,7 +351,7 @@ The following file formats are supported the initialize arguments for the mixer. A Unicode string can only be a file pathname. A bytes object can be either a pathname or a buffer object. Use the 'file' or 'buffer' keywords to avoid ambiguity; otherwise Sound may - guess wrong. If the array keyword is used, the object is expected to export + guess wrong. If the array keyword is used, the object is expected to export a new buffer interface (The object is checked for a buffer interface first.) The Sound object represents actual sound sample data. Methods that change @@ -577,11 +577,11 @@ The following file formats are supported Set the position (angle, distance) of a playing channel. `angle`: Angle is in degrees. - + `distance`: Range from 0 to 255. .. warning:: This function currently fails and raises a - :exc:`pygame.error` when using 7.1 surround sound. + :exc:`pygame.error` when using 7.1 surround sound. By default, the mixer module will use what the hardware is best suited for, so this leads to hardware specific exceptions when using this function. @@ -596,9 +596,9 @@ The following file formats are supported allowedchanges=pygame.AUDIO_ALLOW_FREQUENCY_CHANGE, ) pygame.init() - + .. versionadded:: 2.3.0 - + .. ## Channel.set_source_location ## .. method:: set_volume @@ -635,7 +635,7 @@ The following file formats are supported | :sl:`get the volume of the playing channel` | :sg:`get_volume() -> value` - Return the volume of the channel for the current playing sound + Return the volume of the channel for the current playing sound in the range of 0.0 to 1.0 (inclusive). This does not take into account stereo separation used by :meth:`Channel.set_volume`. The Sound object also has its own volume diff --git a/docs/reST/ref/music.rst b/docs/reST/ref/music.rst index be4682cc7f..e49177387b 100644 --- a/docs/reST/ref/music.rst +++ b/docs/reST/ref/music.rst @@ -59,18 +59,18 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p This will play the loaded music stream. If the music is already playing it will be restarted. - - ``loops`` is an optional integer argument, which is ``0`` by default, which - indicates how many times to repeat the music. The music repeats indefinitely if - this argument is set to ``-1``. - - ``start`` is an optional float argument, which is ``0.0`` by default, which - denotes the position in time from which the music starts playing. The starting - position depends on the format of the music played. ``MP3`` and ``OGG`` use + + ``loops`` is an optional integer argument, which is ``0`` by default, which + indicates how many times to repeat the music. The music repeats indefinitely if + this argument is set to ``-1``. + + ``start`` is an optional float argument, which is ``0.0`` by default, which + denotes the position in time from which the music starts playing. The starting + position depends on the format of the music played. ``MP3`` and ``OGG`` use the position as time in seconds. For ``MP3`` files the start time position selected may not be accurate as things like variable bit rate encoding and ID3 - tags can throw off the timing calculations. For ``MOD`` music it is the pattern - order number. Passing a start position will raise a NotImplementedError if + tags can throw off the timing calculations. For ``MOD`` music it is the pattern + order number. Passing a start position will raise a NotImplementedError if the start position cannot be set. ``fade_ms`` is an optional integer argument, which is ``0`` by default, @@ -78,7 +78,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p will fade up from volume level ``0.0`` to full volume (or the volume level previously set by :func:`set_volume`). The sample may end before the fade-in is complete. If the music is already streaming ``fade_ms`` is ignored. - + .. versionchangedold:: 2.0.0 Added optional ``fade_ms`` argument .. ## pygame.mixer.music.play ## @@ -90,7 +90,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p Resets playback of the current music to the beginning. If :func:`pause` has previously been used to pause the music, the music will remain paused. - + .. note:: :func:`rewind` supports a limited number of file types and notably ``WAV`` files are NOT supported. For unsupported file types use :func:`play` which will restart the music that's already playing (note that this @@ -135,12 +135,12 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p Fade out and stop the currently playing music. - The ``time`` argument denotes the integer milliseconds for which the + The ``time`` argument denotes the integer milliseconds for which the fading effect is generated. - Note, that this function blocks until the music has faded out. Calls - to :func:`fadeout` and :func:`set_volume` will have no effect during - this time. If an event was set using :func:`set_endevent` it will be + Note, that this function blocks until the music has faded out. Calls + to :func:`fadeout` and :func:`set_volume` will have no effect during + this time. If an event was set using :func:`set_endevent` it will be called after the music has faded. .. ## pygame.mixer.music.fadeout ## @@ -151,8 +151,8 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p | :sg:`set_volume(volume, /) -> None` Set the volume of the music playback. - - The ``volume`` argument is a float between ``0.0`` and ``1.0`` that sets + + The ``volume`` argument is a float between ``0.0`` and ``1.0`` that sets the volume level. When new music is loaded the volume is reset to full volume. If ``volume`` is a negative value it will be ignored and the volume will remain set at the current level. If the ``volume`` argument @@ -165,7 +165,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p | :sl:`get the music volume` | :sg:`get_volume() -> value` - Returns the current volume for the mixer. The value will be between ``0.0`` + Returns the current volume for the mixer. The value will be between ``0.0`` and ``1.0``. .. ## pygame.mixer.music.get_volume ## @@ -192,7 +192,7 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p This sets the position in the music file where playback will start. The meaning of "pos", a float (or a number that can be converted to a float), depends on the music format. - + For ``MOD`` files, pos is the integer pattern number in the module. For ``OGG`` it is the absolute position, in seconds, from the beginning of the sound. For ``MP3`` files, it is the relative position, @@ -285,24 +285,24 @@ For a complete list of supported file formats, see the :mod:`pygame.mixer` doc p | :sg:`get_metadata() -> dict` | :sg:`get_metadata(filename) -> dict` | :sg:`get_metadata(fileobj, namehint="") -> dict` - - If no arguments are passed returns a dictionary containing metadata - of the currently loaded music stream, raises an exception if a music stream is not loaded. - Available keys are ``"title"``, ``"album"``, ``"artist"``, ``"copyright"``. - Values are strings containing corresponding retrieved metadata. + + If no arguments are passed returns a dictionary containing metadata + of the currently loaded music stream, raises an exception if a music stream is not loaded. + Available keys are ``"title"``, ``"album"``, ``"artist"``, ``"copyright"``. + Values are strings containing corresponding retrieved metadata. If particular metadata was not found the value is an empty string. Here is an example: ``{'title': 'Small Tone', 'album': 'Tones', 'artist': 'Audacity Generator', 'copyright': ''}`` - - Refer to the :func:`pygame.mixer.music.load` function for arguments regarding specifying a file or a file-like object - whose metadata you want to retrieve. For this function all arguments are optional, + + Refer to the :func:`pygame.mixer.music.load` function for arguments regarding specifying a file or a file-like object + whose metadata you want to retrieve. For this function all arguments are optional, however, specifying only the ``namehint`` will raise an exception. - + Since the underlying functionality was introduced in version 2.6.0 of SDL_mixer, calling this function with an older version of SDL_mixer will return a dictionary with all values being set to empty strings. You can find your version of SDL_mixer by using :func:`pygame.mixer.get_sdl_mixer_version`. .. versionadded:: 2.1.4 - - .. ## pygame.mixer.music.get_metadata ## \ No newline at end of file + + .. ## pygame.mixer.music.get_metadata ## diff --git a/docs/reST/ref/pygame.rst b/docs/reST/ref/pygame.rst index d73a2fb99c..b6266f687d 100644 --- a/docs/reST/ref/pygame.rst +++ b/docs/reST/ref/pygame.rst @@ -206,7 +206,7 @@ object instead of the module, which can be used to test for availability. .. ## pygame.encode_file_path ## .. function:: print_debug_info - + | :sl:`retrieves useful information for debugging and issue-reporting purposes` | :sg:`print_debug_info(filename=None) -> None` @@ -218,7 +218,7 @@ object instead of the module, which can be used to test for availability. .. note:: If ``pygame.freetype`` has not been initialized with :func:`pygame.init` or :func:`pygame.freetype.init`, then the linked and compiled versions of FreeType will be "Unk" since this information is not - available before initialization. + available before initialization. .. versionadded:: 2.1.4 @@ -288,12 +288,12 @@ check which version of pygame has been imported. package was built. If the identifier ends with a plus sign '+' then the package contains uncommitted changes. Please include this revision number in bug reports, especially for non-release pygame builds. - - Important note: pygame development has moved to github, this variable is + + Important note: pygame development has moved to github, this variable is obsolete now. As soon as development shifted to github, this variable started - returning an empty string ``""``. + returning an empty string ``""``. It has always been returning an empty string since ``v1.9.5``. - + .. versionchangedold:: 1.9.5 Always returns an empty string ``""``. @@ -559,6 +559,3 @@ where this is set to 0 by default. This hint only affects the windows platform, other platforms can control DPI awareness via a Window creation keyword parameter called "allow_high_dpi". - - - diff --git a/docs/reST/ref/rect.rst b/docs/reST/ref/rect.rst index a936683a10..a759f3c67e 100644 --- a/docs/reST/ref/rect.rst +++ b/docs/reST/ref/rect.rst @@ -122,7 +122,7 @@ Same as the ``Rect.move()`` method, but operates in place. .. ## Rect.move_ip ## - + .. method:: move_to | :sl:`moves the rectangle to the specified position` @@ -168,7 +168,7 @@ | :sg:`scale_by(x, y) -> Rect` Returns a new rectangle with the size scaled by the given multipliers. - The rectangle remains centered around its current center. A single + The rectangle remains centered around its current center. A single scalar or separate width and height scalars are allowed. Values above one will increase the size of the rectangle, whereas values between zero and one will decrease the size of the rectangle. @@ -415,39 +415,39 @@ .. code-block:: python :linenos: - + Rect = pygame.Rect r = Rect(0, 0, 10, 10) - + list_of_rects = [Rect(1, 1, 1, 1), Rect(2, 2, 2, 2)] indices0 = r.collidelistall(list_of_rects) - + list_of_lists = [[1, 1, 1, 1], [2, 2, 2, 2]] indices1 = r.collidelistall(list_of_lists) - + list_of_tuples = [(1, 1, 1, 1), (2, 2, 2, 2)] indices2 = r.collidelistall(list_of_tuples) - + list_of_double_tuples = [((1, 1), (1, 1)), ((2, 2), (2, 2))] indices3 = r.collidelistall(list_of_double_tuples) - + class ObjectWithRectAttribute(object): def __init__(self, r): self.rect = r - + list_of_object_with_rect_attribute = [ ObjectWithRectAttribute(Rect(1, 1, 1, 1)), ObjectWithRectAttribute(Rect(2, 2, 2, 2)), ] indices4 = r.collidelistall(list_of_object_with_rect_attribute) - + class ObjectWithCallableRectAttribute(object): def __init__(self, r): self._rect = r - + def rect(self): return self._rect - + list_of_object_with_callable_rect = [ ObjectWithCallableRectAttribute(Rect(1, 1, 1, 1)), ObjectWithCallableRectAttribute(Rect(2, 2, 2, 2)), @@ -595,7 +595,7 @@ .. versionchanged:: 2.4.0 ``values`` is now accepted as a keyword argument. Type Stub updated - to use boolean ``True`` or ``False``, but any truthy or falsy value + to use boolean ``True`` or ``False``, but any truthy or falsy value will be valid. .. ## Rect.collidedict ## @@ -618,9 +618,9 @@ .. versionchanged:: 2.4.0 ``values`` is now accepted as a keyword argument. Type Stub updated - to use boolean ``True`` or ``False``, but any truthy or falsy value + to use boolean ``True`` or ``False``, but any truthy or falsy value will be valid. .. ## Rect.collidedictall ## - .. ## pygame.Rect ## \ No newline at end of file + .. ## pygame.Rect ## diff --git a/docs/reST/ref/scrap.rst b/docs/reST/ref/scrap.rst index c1d8117c1a..e44f6e28f3 100644 --- a/docs/reST/ref/scrap.rst +++ b/docs/reST/ref/scrap.rst @@ -18,7 +18,7 @@ functions. All other functions are deprecated as of pygame 2.2.0 and will be rem in a future release of pygame. .. note:: ``scrap.put_text``, ``scrap.get_text``, and ``scrap.has_text`` use the same - clipboard as the rest of the current API, but only strings are compatible with the + clipboard as the rest of the current API, but only strings are compatible with the new API as of right now. .. function:: put_text @@ -41,7 +41,7 @@ in a future release of pygame. .. ## pygame.scrap.put_text .. function:: get_text - + | :sl:`Gets text from the clipboard.` | :sg:`get_text() -> str` @@ -56,7 +56,7 @@ in a future release of pygame. .. ## pygame.scrap.get_text .. function:: has_text - + | :sl:`Checks if text is in the clipboard.` | :sg:`has_text() -> bool` @@ -140,7 +140,7 @@ For an example of how the scrap module works refer to the examples page .. note:: The scrap module requires :func:`pygame.display.set_mode()` be called before being initialized. - + .. deprecated:: 2.2.0 .. ## pygame.scrap.init ## @@ -311,4 +311,4 @@ For an example of how the scrap module works refer to the examples page .. deprecated:: 2.2.0 .. ## pygame.scrap.set_mode ## -.. ## pygame.scrap ## \ No newline at end of file +.. ## pygame.scrap ## diff --git a/docs/reST/ref/sdl2_controller.rst b/docs/reST/ref/sdl2_controller.rst index f6f965d65e..c5e61e4d9f 100644 --- a/docs/reST/ref/sdl2_controller.rst +++ b/docs/reST/ref/sdl2_controller.rst @@ -237,7 +237,7 @@ events related to controllers. | :sl:`Assign a mapping to the controller` | :sg:`set_mapping(mapping) -> int` - Rebind buttons, axes, triggers and dpads. The mapping should be a + Rebind buttons, axes, triggers and dpads. The mapping should be a dict containing all buttons, hats and axes. The easiest way to get this is to use the dict returned by :meth:`Controller.get_mapping`. To edit this mapping assign a value to the original button. The value of the diff --git a/docs/reST/ref/sdl2_video.rst b/docs/reST/ref/sdl2_video.rst index bb499ef441..47602a5d40 100644 --- a/docs/reST/ref/sdl2_video.rst +++ b/docs/reST/ref/sdl2_video.rst @@ -34,9 +34,9 @@ | :sl:`pygame object encapsulating Renderer driver information` Attributes: - + :: - + name flags num_texture_formats @@ -63,7 +63,7 @@ See :class:`pygame.Window` -.. class:: Texture +.. class:: Texture | :sl:`pygame object that represents a texture` | :sg:`Texture(renderer, size, depth=0, static=False, streaming=False, target=False, scale_quality=None) -> Texture` @@ -95,18 +95,18 @@ Since textures are stored in GPU video memory, they aren't as easy to modify as the image data of :class:`pygame.Surface` objects, which reside in RAM. - + Textures can be modified in 2 ways: - + * By drawing other textures onto them, achieved by marking them as "target" textures and setting them as the rendering target of their Renderer object (if properly configured and supported). - + * By updating them with a Surface. .. note:: A :class:`pygame.Surface`-to-:class:`Texture` update is generally considered a slow operation, as it requires image data to be uploaded from RAM to VRAM, which can have a notable overhead cost. - + .. attribute:: renderer | :sl:`Get the renderer associated with the texture (**read-only**)` @@ -133,7 +133,7 @@ | :sg:`blend_mode -> int` Gets or sets the blend mode for the texture's drawing operations. - Valid blend modes are any of the ``BLENDMODE_*`` constants or a custom one. + Valid blend modes are any of the ``BLENDMODE_*`` constants or a custom one. .. attribute:: color @@ -294,7 +294,7 @@ An origin of ``None`` means no origin was set and the Image will be rotated around its center. - + .. method:: get_rect | :sl:`Get the rectangular area of the Image` @@ -336,7 +336,7 @@ the refresh rate. :param bool target_texture: Whether the renderer should support setting :class:`Texture` objects as target textures, to - enable drawing onto them. + enable drawing onto them. :class:`Renderer` objects provide a cross-platform API for rendering 2D @@ -350,7 +350,7 @@ If configured correctly and supported by an underlying rendering driver, Renderer objects can have a :class:`Texture` object temporarily set as a target texture (the Texture object must have been created with target texture usage support), - which allows those textures to be drawn onto. + which allows those textures to be drawn onto. To present drawn content onto the window, :meth:`Renderer.present` should be called. :meth:`Renderer.clear` should be called to clear any drawn content @@ -366,7 +366,7 @@ .. attribute:: draw_blend_mode | :sl:`Get or set the blend mode used for primitive drawing operations` - | :sg:`draw_blend_mode -> int` + | :sg:`draw_blend_mode -> int` .. attribute:: draw_color @@ -422,7 +422,7 @@ :param area: A :class:`pygame.Rect` or tuple representing the drawing area on the target, or ``None`` to use the - entire area of the current rendering target. + entire area of the current rendering target. .. method:: blit @@ -472,7 +472,7 @@ | :sl:`Draw a triangle outline` | :sg:`draw_triangle(p1, p2, p3) -> None` - + :param p1: The first triangle point. :param p2: The second triangle point. :param p2: The third triangle point. @@ -528,7 +528,7 @@ :class:`pygame.Surface`. It should not be used frequently. .. method:: compose_custom_blend_mode - + | :sl:`Compose a custom blend mode` | :sg:`compose_custom_blend_mode(color_mode, alpha_mode) -> int` @@ -537,5 +537,5 @@ :param color_mode: A tuple ``(srcColorFactor, dstColorFactor, colorOperation)`` :param alpha_mode: A tuple ``(srcAlphaFactor, dstAlphaFactor, alphaOperation)`` - - :return: A blend mode to be used with :meth:`Renderer.set_draw_blend_mode` and :meth:`Texture.set_blend_mode`. \ No newline at end of file + + :return: A blend mode to be used with :meth:`Renderer.set_draw_blend_mode` and :meth:`Texture.set_blend_mode`. diff --git a/docs/reST/ref/special_flags_list.rst b/docs/reST/ref/special_flags_list.rst index 9a830cd168..25c495fb88 100644 --- a/docs/reST/ref/special_flags_list.rst +++ b/docs/reST/ref/special_flags_list.rst @@ -94,9 +94,9 @@ Special Flags List accurate blending results when the color channels are already multiplied by the surface alpha channel. You should only use this blend mode if you previously premultiplied the Surface with - :meth:`pygame.Surface.premul_alpha()`, or if you know that the Surface was already - created or loaded in with premultiplied alpha colors. You can read more about the - advantages of `premultiplied alpha blending + :meth:`pygame.Surface.premul_alpha()`, or if you know that the Surface was already + created or loaded in with premultiplied alpha colors. You can read more about the + advantages of `premultiplied alpha blending here `_. .. versionaddedold:: 2.0.0 diff --git a/docs/reST/ref/sprite.rst b/docs/reST/ref/sprite.rst index a9d9d5e8ed..268727a1d0 100644 --- a/docs/reST/ref/sprite.rst +++ b/docs/reST/ref/sprite.rst @@ -64,24 +64,24 @@ Sprites are not thread safe. So lock them yourself if using threads. adding the Sprite to Groups. For example: .. code-block:: python - + class Block(pygame.sprite.Sprite): - - # Constructor. Pass in the color of the block, + + # Constructor. Pass in the color of the block, # and its x and y position def __init__(self, color, width, height): # Call the parent class (Sprite) constructor - pygame.sprite.Sprite.__init__(self) - + pygame.sprite.Sprite.__init__(self) + # Create an image of the block, and fill it with a color. # This could also be an image loaded from the disk. self.image = pygame.Surface([width, height]) self.image.fill(color) - + # Fetch the rectangle object that has the dimensions of the image # Update the position of this object by setting the values of rect.x and rect.y - self.rect = self.image.get_rect() - + self.rect = self.image.get_rect() + .. method:: update | :sl:`method to control sprite behavior` @@ -667,17 +667,17 @@ Sprites are not thread safe. So lock them yourself if using threads. collide_circle_ratio, collide_mask Example: - + .. code-block:: python # See if the Sprite block has collided with anything in the Group block_list # The True flag will remove the sprite in block_list - blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) - + blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) + # Check the list of colliding sprites, and add one to the score for each one for block in blocks_hit_list: score +=1 - + .. ## pygame.sprite.spritecollide ## .. function:: collide_rect diff --git a/docs/reST/ref/system.rst b/docs/reST/ref/system.rst index 1d522b49ee..eb1450f9e3 100644 --- a/docs/reST/ref/system.rst +++ b/docs/reST/ref/system.rst @@ -16,11 +16,11 @@ | :sg:`get_cpu_instruction_sets() -> instruction_sets` Returns a dict of the information of CPU instruction sets. The keys of - the dict are the names of instruction sets and the values determine + the dict are the names of instruction sets and the values determine whether the instruction set is available. - Some of functions like ``Surface.blit`` can be accelerated by SIMD - instruction sets like SSE2 or AVX2. By checking the availability of + Some of functions like ``Surface.blit`` can be accelerated by SIMD + instruction sets like SSE2 or AVX2. By checking the availability of instruction sets, you can check if these accelerations are available. Here is an example of the returned dict @@ -35,23 +35,23 @@ 'SSE41': True, 'SSE42': True, 'AVX': True, - 'AVX2': True, + 'AVX2': True, 'AVX512F': False, - 'NEON': False, + 'NEON': False, 'ARMSIMD': False, - 'LSX': False, + 'LSX': False, 'LASX': False } .. Note:: The value of ``ARMSIMD`` will be always False if SDL version < 2.0.12. - + The values of ``LSX`` and ``LASX`` will be always False if SDL version < 2.24.0. - + .. versionadded:: 2.3.1 - .. versionchanged:: 2.4.0 removed ``RDTSC`` key, + .. versionchanged:: 2.4.0 removed ``RDTSC`` key, as it has been removed in pre-release SDL3 .. function:: get_total_ram @@ -77,7 +77,7 @@ per app name. It takes two strings, ``org`` and ``app``, referring to the "organization" - and "application name." For example, the organization could be "Valve," + and "application name." For example, the organization could be "Valve," and the application name could be "Half Life 2." It then will figure out the preferred path, **creating the folders referenced by the path if necessary**, and return a string containing the absolute path. @@ -101,7 +101,7 @@ .. note:: The ``appdirs`` library has similar functionality for this use case, but has more "folder types" to choose from. - + .. versionadded:: 2.2.0 .. function:: get_pref_locales @@ -114,11 +114,11 @@ also be an empty list if pygame could not find this information. Each "locale" dict contains the language code which can be accessed by the - key ``"language"``. This language code is an ISO-639 language specifier + key ``"language"``. This language code is an ISO-639 language specifier (such as "en" for English, "de" for German, etc). A "locale" dict may also optionally contain a ``"country"`` field, whose - value is an ISO-3166 country code (such as "US" for the United States, - "CA" for Canada, etc). If this field is not set or undetermined, it is + value is an ISO-3166 country code (such as "US" for the United States, + "CA" for Canada, etc). If this field is not set or undetermined, it is ``None``. A "locale" dict which looks like ``{'language': 'en', 'country': 'US'}`` indicates the user prefers American English, while @@ -126,7 +126,7 @@ English, generically. This might be a bit of an expensive call because it has to query the OS. So - this function must not be called in a game loop, instead it's best to ask + this function must not be called in a game loop, instead it's best to ask for this once and save the results. However, this list can change when the user changes a system preference outside of your program. pygame will send a ``LOCALECHANGED`` event in this case, if possible, and you can call this @@ -141,11 +141,11 @@ **Experimental:** feature available for testing and feedback. We don't anticipate it changing, but it might if something important - is brought up. `Please leave get_power_state feedback with + is brought up. `Please leave get_power_state feedback with authors `_ Returns a ``PowerState`` object representing the power supply state. - + Returns ``None`` if the power state is unknown. The PowerState object has several attributes: @@ -159,7 +159,7 @@ battery_seconds: An integer, representing the seconds of battery life left. Could be None if the value is unknown. - + on_battery: True if the device is running on the battery (not plugged in). diff --git a/docs/reST/ref/transform.rst b/docs/reST/ref/transform.rst index 926a304e42..3ee5f05200 100644 --- a/docs/reST/ref/transform.rst +++ b/docs/reST/ref/transform.rst @@ -39,7 +39,7 @@ Instead, always begin with the original image and scale to the desired size.) | :sl:`resize to new resolution` | :sg:`scale(surface, size, dest_surface=None) -> Surface` - Resizes the Surface to a new size, given as (width, height). + Resizes the Surface to a new size, given as (width, height). This is a fast scale operation that does not sample the results. An optional destination surface can be passed which is faster than creating a new @@ -113,7 +113,7 @@ Instead, always begin with the original image and scale to the desired size.) This really only has an effect on simple images with solid colors. On photographic and antialiased images it will look like a regular unfiltered scale. - + An optional destination surface can be passed which is faster than creating a new Surface. This destination surface must have double the dimensions (width * 2, height * 2) and same depth and format as the source Surface. @@ -127,7 +127,7 @@ Instead, always begin with the original image and scale to the desired size.) Uses one of two different algorithms for scaling each dimension of the input surface as required. For shrinkage, the output pixels are area averages of - the colors they cover. The size is a 2 number sequence for (width, height). + the colors they cover. The size is a 2 number sequence for (width, height). This function only works for 24-bit or 32-bit surfaces. A ``ValueError`` will be thrown if the input surface bit depth is less than 24. @@ -138,7 +138,7 @@ Instead, always begin with the original image and scale to the desired size.) .. versionaddedold:: 1.8 .. versionchanged:: 2.4.0 now uses SSE2/NEON SIMD for acceleration on x86 - and ARM machines, a performance improvement over previous MMX/SSE only + and ARM machines, a performance improvement over previous MMX/SSE only supported on x86. .. ## pygame.transform.smoothscale ## @@ -269,9 +269,9 @@ Instead, always begin with the original image and scale to the desired size.) .. versionchanged:: 2.3.0 Passing the calling surface as destination surface raises a ``ValueError`` - + .. versionchanged:: 2.3.1 - Now the standard deviation of the Gaussian kernel is equal to the radius. + Now the standard deviation of the Gaussian kernel is equal to the radius. Blur results will be slightly different. .. versionchanged:: 2.5.0 @@ -295,7 +295,7 @@ Instead, always begin with the original image and scale to the desired size.) correctly. An optional destination surface can be passed which is faster than creating a new - Surface. This destination surface must have the same dimensions (width, height) and + Surface. This destination surface must have the same dimensions (width, height) and depth as the first passed source Surface. .. versionaddedold:: 1.8 @@ -342,7 +342,7 @@ Instead, always begin with the original image and scale to the desired size.) An optional destination surface can be passed which is faster than creating a new Surface. This destination surface must have the same dimensions (width, height) and depth as the source Surface. - + .. versionadded:: 2.1.4 .. versionchanged:: 2.4.0 Adjusted formula slightly to support performance optimisation. It may return very slightly diff --git a/docs/reST/ref/typing.rst b/docs/reST/ref/typing.rst index de79ecc76b..27d3bb7ecd 100644 --- a/docs/reST/ref/typing.rst +++ b/docs/reST/ref/typing.rst @@ -37,12 +37,12 @@ type aliases for proper typehint annotations. Being a generic, subscribing it will signal further precision such as ``SequenceLike[str]`` or ``SequenceLike[float]``. - + .. data:: Coordinate A sequence of two numbers (floats or ints), i.e: - * ``pygame.Vector2(a, b)`` + * ``pygame.Vector2(a, b)`` * ``[a, b]`` * ``(a, b)`` @@ -64,7 +64,7 @@ type aliases for proper typehint annotations. * ``0`` (mapped color) .. data:: RectLike - + An object representing a rect such as a sequence of numbers or coordinates or an object with a rect attribute or a method returning a rect. These types are supported by every function accepting a rect as argument. i.e.: diff --git a/docs/reST/ref/window.rst b/docs/reST/ref/window.rst index a8ecbbdaa7..bba608c6c0 100644 --- a/docs/reST/ref/window.rst +++ b/docs/reST/ref/window.rst @@ -291,8 +291,8 @@ Update pixel data from memory to be displayed in the window. This is the Window class equivalent of :func:`pygame.display.flip`. - With ``get_surface()`` this method allows software rendering (classic pygame rendering) flipping pixel data - from an associated surface in memory to be displayed in the window. Alternatively, when this window has an + With ``get_surface()`` this method allows software rendering (classic pygame rendering) flipping pixel data + from an associated surface in memory to be displayed in the window. Alternatively, when this window has an associated OpenGL context, this method will instead perform a GL buffer swap to the window. Here is a runnable example of using ``get_surface`` and ``flip``: @@ -406,7 +406,7 @@ | :sg:`flash(operation, /) -> None` :param int operation: The flash operation. - + Supported flash operations are: * ``pygame.FLASH_CANCEL``: Cancel the current flash state if present * ``pygame.FLASH_BRIEFLY``: Flash for a short amount of time to get attention @@ -420,7 +420,7 @@ advised to wrap it in a try block. .. code-block:: python - + import pygame window = pygame.Window() diff --git a/docs/reST/themes/classic/elements.html b/docs/reST/themes/classic/elements.html index cbe7e5af95..7b093a89fb 100644 --- a/docs/reST/themes/classic/elements.html +++ b/docs/reST/themes/classic/elements.html @@ -105,6 +105,3 @@
pygame-ce documentation

{{ _('Edit on GitHub') }} {%- endblock %} - - - diff --git a/docs/reST/tutorials/en/Red_or_Black/2.Print_text/Basic TEMPLATE and OUTPUT.rst b/docs/reST/tutorials/en/Red_or_Black/2.Print_text/Basic TEMPLATE and OUTPUT.rst index 7f6036725c..46ea700b9c 100644 --- a/docs/reST/tutorials/en/Red_or_Black/2.Print_text/Basic TEMPLATE and OUTPUT.rst +++ b/docs/reST/tutorials/en/Red_or_Black/2.Print_text/Basic TEMPLATE and OUTPUT.rst @@ -114,7 +114,7 @@ That was the explanation of the entire source code, which has 20 lines. It seems pygame.display.set_caption("Hello World Project") #7 myScreen = pygame.display.set_mode((640, 480)) #8 myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) #9 - myText = myTextFont.render("Hello World!", True, red, green) #10 + myText = myTextFont.render("Hello World!", True, red, green) #10 myTextArea = myText.get_rect() #11 myTextArea.center = (320, 240) #12 @@ -128,4 +128,3 @@ That was the explanation of the entire source code, which has 20 lines. It seems sys.exit() #19 pygame.display.update() #20 - diff --git a/docs/reST/tutorials/en/Red_or_Black/3.Move_text/Basic PROCESS.rst b/docs/reST/tutorials/en/Red_or_Black/3.Move_text/Basic PROCESS.rst index efb45cc3f2..b95dac1226 100644 --- a/docs/reST/tutorials/en/Red_or_Black/3.Move_text/Basic PROCESS.rst +++ b/docs/reST/tutorials/en/Red_or_Black/3.Move_text/Basic PROCESS.rst @@ -105,10 +105,10 @@ Okay, we learn that “Fixing time” is needed when screen is updated. Every sc red = (255,0,0) green = (0,255,0) pygame.init() - pygame.display.set_caption("Moving World Project") + pygame.display.set_caption("Moving World Project") myScreen = pygame.display.set_mode((640, 480)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) - myText = myTextFont.render("Moving World!", True, red, green) + myText = myTextFont.render("Moving World!", True, red, green) myTextArea = myText.get_rect() myTextArea.center = (320, 240) fpsClock = pygame.time.Clock() #1 @@ -139,7 +139,7 @@ Okay, we learn that “Fixing time” is needed when screen is updated. Every sc myTextArea.center = (320 + x, 240 + y) #10 - + myScreen.fill(white) myScreen.blit(myText, myTextArea) @@ -150,4 +150,3 @@ Okay, we learn that “Fixing time” is needed when screen is updated. Every sc pygame.display.update() fpsClock.tick(60) #11 - diff --git a/docs/reST/tutorials/en/Red_or_Black/4.Control_text/Basic INPUT.rst b/docs/reST/tutorials/en/Red_or_Black/4.Control_text/Basic INPUT.rst index 5afa30c37c..c6e32f7a68 100644 --- a/docs/reST/tutorials/en/Red_or_Black/4.Control_text/Basic INPUT.rst +++ b/docs/reST/tutorials/en/Red_or_Black/4.Control_text/Basic INPUT.rst @@ -89,7 +89,7 @@ Usually, we learn how to output something first (Think about Hello World!), lear (Controlling World! moves when player press one of four direction arrow of keyboard) -There are 2 big difference in comparison to before project. First big difference is line #5, which adds checking ``KEYDOWN`` **event** is triggered or not. Other lines are just changing previous algorithm to act differently. We know that same command can make big difference in entire program when it is executed before Event statement of after Event statement. Pay attention that process about changing location appear after Event statement. (**Update after set**. That is second big difference). Variable ``event.key`` means latest pressed key on keyboard. Look at the specific key name. K_UP, K_LEFT, K_DOWN, K_RIGHT. Very intuitive **K_ series**. (Given by pygame.locals which we added at the Header) Furthermore, there are other key named K_8, K_a, K_L, K_LCTRL, K_DELETE, or K_F4. We can understand meaning of these keys without extra explanation. Full key list can be found in +There are 2 big difference in comparison to before project. First big difference is line #5, which adds checking ``KEYDOWN`` **event** is triggered or not. Other lines are just changing previous algorithm to act differently. We know that same command can make big difference in entire program when it is executed before Event statement of after Event statement. Pay attention that process about changing location appear after Event statement. (**Update after set**. That is second big difference). Variable ``event.key`` means latest pressed key on keyboard. Look at the specific key name. K_UP, K_LEFT, K_DOWN, K_RIGHT. Very intuitive **K_ series**. (Given by pygame.locals which we added at the Header) Furthermore, there are other key named K_8, K_a, K_L, K_LCTRL, K_DELETE, or K_F4. We can understand meaning of these keys without extra explanation. Full key list can be found in `https://pyga.me/docs/ref/key.html#pygame.key.name`. Notice that KEYDOWN means “this key was not pressed before, but **now is pressed**” and meaning of **“hold” is not included** here. In the case of hold, new event-handling about checking ``KEYUP`` (it means “this key was pressed before, but now is not pressed”) is needed with some processing (which needs extra variable and algorithm). This will be mentioned at advanced part. @@ -107,10 +107,10 @@ Adding input was easy because it’s just adding if phase with certain event par red = (255,0,0) green = (0,255,0) pygame.init() - pygame.display.set_caption("Controlling World Project") + pygame.display.set_caption("Controlling World Project") myScreen = pygame.display.set_mode((640, 480)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) - myText = myTextFont.render("Controlling World!", True, red, green) + myText = myTextFont.render("Controlling World!", True, red, green) myTextArea = myText.get_rect() myTextArea.center = (320, 240) fpsClock = pygame.time.Clock() @@ -143,7 +143,7 @@ Adding input was easy because it’s just adding if phase with certain event par elif event.key == K_RIGHT: moveDown = 0 moveRight = 1 - + if(moveRight == 1): #6 x = x + 10 elif(moveRight == -1): #7 @@ -154,4 +154,3 @@ Adding input was easy because it’s just adding if phase with certain event par y = y - 10 pygame.display.update() - diff --git a/docs/reST/tutorials/en/Red_or_Black/5.HP_bar/Advanced OUTPUT with Advanced PROCESS.rst b/docs/reST/tutorials/en/Red_or_Black/5.HP_bar/Advanced OUTPUT with Advanced PROCESS.rst index fc97bb2ea4..9192a2b861 100644 --- a/docs/reST/tutorials/en/Red_or_Black/5.HP_bar/Advanced OUTPUT with Advanced PROCESS.rst +++ b/docs/reST/tutorials/en/Red_or_Black/5.HP_bar/Advanced OUTPUT with Advanced PROCESS.rst @@ -215,8 +215,8 @@ Furthermore, now it’s time to functionalize specifically. I push Always statem import pygame, sys from pygame.locals import* - - maxHP = 10 + + maxHP = 10 white = (255,255,255) gray = (127,127,127) black = (0,0,0) @@ -233,18 +233,18 @@ Furthermore, now it’s time to functionalize specifically. I push Always statem myTextArea = myText.get_rect() myTextArea.center = (width/2, height/2) #3 fpsClock = pygame.time.Clock() - + def main(): #4 HP = 5 - + while True: myText = myTextFont.render((str(HP) + "/" + str(maxHP)), True, red, gray) - + myScreen.fill(gray) - + myScreen.blit(myText, myTextArea) drawHP(HP) #5 - + for event in pygame.event.get(): if event.type == QUIT: pygame.quit() @@ -256,21 +256,21 @@ Furthermore, now it’s time to functionalize specifically. I push Always statem elif event.key == K_DOWN: if HP != 0: HP = HP - 1 - + pygame.display.update() fpsClock.tick(60) - + def drawHP(HP): #6 r = int((height - 40) / maxHP) - + pygame.draw.rect(myScreen, black, (20, 20, 20, 20 + ((maxHP - 0.5) * r))) - + for i in range(maxHP): if HP >= (maxHP - i): pygame.draw.rect(myScreen, red, (20, 20 + (i * r), 20, r)) pygame.draw.rect(myScreen, white, (20, 20 + (i * r), 20, r), 1) - + return - + if __name__ == '__main__': #7 main() diff --git a/docs/reST/tutorials/en/Red_or_Black/6.Buttons/Advanced INPUT with Advanced OUTPUT.rst b/docs/reST/tutorials/en/Red_or_Black/6.Buttons/Advanced INPUT with Advanced OUTPUT.rst index c3e2bd7b65..6be9b13967 100644 --- a/docs/reST/tutorials/en/Red_or_Black/6.Buttons/Advanced INPUT with Advanced OUTPUT.rst +++ b/docs/reST/tutorials/en/Red_or_Black/6.Buttons/Advanced INPUT with Advanced OUTPUT.rst @@ -185,8 +185,8 @@ In the case of button, input and output area for button must be **identical**. ( import pygame, sys from pygame.locals import* - - maxHP = 10 + + maxHP = 10 white = (255,255,255) gray = (127,127,127) black = (0,0,0) @@ -195,7 +195,7 @@ In the case of button, input and output area for button must be **identical**. ( blue = (0,0,255) pygame.init() pygame.display.set_caption("Array buttons Project") - width = 640 + width = 640 height = 480 myScreen = pygame.display.set_mode((width, height)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) @@ -203,19 +203,19 @@ In the case of button, input and output area for button must be **identical**. ( myTextArea = myText.get_rect() myTextArea.center = (width/2, height/2) fpsClock = pygame.time.Clock() - + def main(): HP = 5 - + while True: myText = myTextFont.render((str(HP) + "/" + str(maxHP)), True, red, gray) - + myScreen.fill(gray) - + myScreen.blit(myText, myTextArea) drawHP(HP) drawButtons() - + for event in pygame.event.get(): if event.type == QUIT: pygame.quit() @@ -234,28 +234,28 @@ In the case of button, input and output area for button must be **identical**. ( HP = HP + 1 elif pygame.Rect(325, 425, 45, 45).collidepoint(x, y): if HP != 0: - HP = HP - 1 - + HP = HP - 1 + pygame.display.update() fpsClock.tick(60) - + def drawHP(HP): r = int((height - 40) / maxHP) - + pygame.draw.rect(myScreen, black, (20, 20, 20, 20 + ((maxHP - 0.5) * r))) - + for i in range(maxHP): if HP >= (maxHP - i): pygame.draw.rect(myScreen, red, (20, 20 + (i * r), 20, r)) pygame.draw.rect(myScreen, white, (20, 20 + (i * r), 20, r), 1) - + return - + def drawButtons(): r = 45 r_margin = 10 colors = [red, black] - + num = 2 margin = int((width - ((r * num) + (r_margin * (num - 1)))) / 2) for i in range(0, num): @@ -263,6 +263,6 @@ In the case of button, input and output area for button must be **identical**. ( up = height - r - 10 pygame.draw.rect(myScreen, colors[i], (left, up, r, r)) pygame.draw.rect(myScreen, gray, (left + 2, up + 2, r - 4, r - 4), 2) - + if __name__ == '__main__': main() diff --git a/docs/reST/tutorials/en/Red_or_Black/7.Game_board/Advanced OUTPUT and plus alpha.rst b/docs/reST/tutorials/en/Red_or_Black/7.Game_board/Advanced OUTPUT and plus alpha.rst index bd2a1fca7b..f59617b9f3 100644 --- a/docs/reST/tutorials/en/Red_or_Black/7.Game_board/Advanced OUTPUT and plus alpha.rst +++ b/docs/reST/tutorials/en/Red_or_Black/7.Game_board/Advanced OUTPUT and plus alpha.rst @@ -116,8 +116,8 @@ Actually, there are a lot of idea for improving this game. How about changing bu import pygame, sys, random from pygame.locals import* - - maxHP = 10 + + maxHP = 10 white = (255,255,255) gray = (127,127,127) black = (0,0,0) @@ -126,7 +126,7 @@ Actually, there are a lot of idea for improving this game. How about changing bu blue = (0,0,255) pygame.init() pygame.display.set_caption("Red or Black Project") - width = 640 + width = 640 height = 480 myScreen = pygame.display.set_mode((width, height)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) @@ -134,26 +134,26 @@ Actually, there are a lot of idea for improving this game. How about changing bu myTextArea = myText.get_rect() myTextArea.center = (width/2, height/2) fpsClock = pygame.time.Clock() - + def main(): HP = 5 board, b_red, b_black = generateBoard(5,5) #1 - + while True: myText = myTextFont.render((str(HP) + "/" + str(maxHP)), True, red, gray) - + myScreen.fill(gray) - + myScreen.blit(myText, myTextArea) drawHP(HP) drawButtons() drawBoard(board) #2 - + for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() - + elif event.type == KEYDOWN: if event.key == K_UP: if HP != 10: @@ -163,7 +163,7 @@ Actually, there are a lot of idea for improving this game. How about changing bu HP = HP - 1 elif event.type == MOUSEBUTTONUP: x, y = event.pos - + if pygame.Rect(270, 425, 45, 45).collidepoint(x, y): #3 if b_red >= b_black: if HP != 10: @@ -173,7 +173,7 @@ Actually, there are a lot of idea for improving this game. How about changing bu if HP != 0: HP = HP - 1 board, b_red, b_black = generateBoard(5,5) - + elif pygame.Rect(325, 425, 45, 45).collidepoint(x, y): #4 if b_red <= b_black: if HP != 10: @@ -183,63 +183,63 @@ Actually, there are a lot of idea for improving this game. How about changing bu if HP != 0: HP = HP - 1 board, b_red, b_black = generateBoard(5,5) - + pygame.display.update() fpsClock.tick(60) - + def drawHP(HP): r = int((height - 40) / maxHP) - + pygame.draw.rect(myScreen, gray, (20, 20, 20, 20 + ((maxHP - 0.5) * r))) - + for i in range(maxHP): if HP >= (maxHP - i): pygame.draw.rect(myScreen, blue, (20, 20 + (i * r), 20, r)) pygame.draw.rect(myScreen, white, (20, 20 + (i * r), 20, r), 1) - + return - + def drawButtons(): r = 45 r_margin = 10 colors = [red, black] - + num = 2 margin = int((width - ((r * num) + (r_margin * (num - 1)))) / 2) - + for i in range(0, num): left = margin + (i * r) + (i * r_margin) up = height - r - 10 pygame.draw.rect(myScreen, colors[i], (left, up, r, r)) - pygame.draw.rect(myScreen, gray, (left + 2, up + 2, r - 4, r - 4), 2) - + pygame.draw.rect(myScreen, gray, (left + 2, up + 2, r - 4, r - 4), 2) + def generateBoard(width, height): #5 board = [] b_red = 0 b_black = 0 - + for x in range(width): column = [] for y in range(height): column.append(random.randint(0, 1)) board.append(column) - + for x in range(width): for y in range(height): if(board[x][y] == 1): b_red = b_red + 1 elif(board[x][y] == 0): b_black = b_black + 1 - + return board, b_red, b_black - + def drawBoard(board): #6 r = 50 b_width = 5 b_height = 5 l_margin = int((width - (b_width * r)) / 2) u_margin = int((height - (b_height * r)) / 2) - + for x in range(5): for y in range(5): left = x * r + l_margin @@ -249,10 +249,10 @@ Actually, there are a lot of idea for improving this game. How about changing bu elif board[x][y] == 0: color = black pygame.draw.rect(myScreen, color, (left, up, r, r)) - + left = l_margin up = u_margin pygame.draw.rect(myScreen, white, (left-1, up-1, r * 5 + 1, r * b_height + 1), 1) - + if __name__ == '__main__': main() diff --git a/docs/reST/tutorials/en/Red_or_Black/8.Epilog/Epilog.rst b/docs/reST/tutorials/en/Red_or_Black/8.Epilog/Epilog.rst index d365479384..b257ee4588 100644 --- a/docs/reST/tutorials/en/Red_or_Black/8.Epilog/Epilog.rst +++ b/docs/reST/tutorials/en/Red_or_Black/8.Epilog/Epilog.rst @@ -15,4 +15,3 @@ However, this is end of tutorial. This tutorial covers only a few of Pygame. But What is conclusion? **Output is greater than input**. We can implement much more program within our knowledge. Or, we can learn new knowledge easily by connecting it to old knowledge. That’s trait of programming. And so is game. “Radom” is the key concept for every game. (including simple game made on this tutorial!) number of cases is much greater when random variable is concerned. If random variable starts to affect another random variable and so on, output will be greater like Avalanche. That’s why game is interesting. Concept of “Random” is the only unique characteristic for game in comparison to novel, music or movie. Think about Tetris. How much effort Alexey Leonidovich Pajitnov spent? Do you think it is greater than sum of Tetris player’s playing time above the world, along 35 years? That’s ultimate example of both power of programming and game. So, game makers are Avalanche makers. Now it’s time to create any game! Learn! Utilize! Go through trial and errors! - diff --git a/docs/reST/tutorials/en/chimp-explanation.rst b/docs/reST/tutorials/en/chimp-explanation.rst index ef713b20c3..a18c83e0e2 100644 --- a/docs/reST/tutorials/en/chimp-explanation.rst +++ b/docs/reST/tutorials/en/chimp-explanation.rst @@ -72,7 +72,7 @@ It also checks for the availability of some of the optional pygame modules. :: First, we import the standard "os" python module. This allow us to do things like create platform independent file paths. -In the next line, we import the pygame package. +In the next line, we import the pygame package. Lastly, we prepare two paths for the rest of the code to use. ``main_dir`` uses the `os.path` module and the `__file__` variable provided @@ -321,7 +321,7 @@ Next we set up the display graphics mode. Note that the :mod:`pygame.display` module is used to control all the display settings. In this case we are asking for a 1280 by 480 window, with the ``SCALED`` display flag. This automatically scales up the window for displays much larger than the -window. +window. Last we set the window title and turn off the mouse cursor for our window. Very basic to do, and now we have a small black window ready to @@ -406,7 +406,7 @@ Prepare Game Object Here we create all the objects that the game is going to need. :: - + whiff_sound = load_sound("whiff.wav") punch_sound = load_sound("punch.wav") chimp = Chimp() @@ -500,7 +500,7 @@ Now that all the objects are in the right place, time to draw them. :: The first blit call will draw the background onto the entire screen. This erases everything we saw from the previous frame (slightly inefficient, but good enough for this game). Next we call the `draw()` method of the sprite -container. Lastly, we `flip()` the contentsof pygame's software double buffer +container. Lastly, we `flip()` the contentsof pygame's software double buffer to the screen. This makes everything we've drawn visible all at once. @@ -513,4 +513,4 @@ User has quit, time to clean up. :: Cleaning up the running game in *pygame* is extremely simple. Since all variables are automatically destructed, we don't really have to do -anything, but calling `pygame.quit()` explicitly cleans up pygame's internals. \ No newline at end of file +anything, but calling `pygame.quit()` explicitly cleans up pygame's internals. diff --git a/docs/reST/tutorials/en/import-init.rst b/docs/reST/tutorials/en/import-init.rst index ecccc661a0..3219702d15 100644 --- a/docs/reST/tutorials/en/import-init.rst +++ b/docs/reST/tutorials/en/import-init.rst @@ -5,7 +5,7 @@ ******************************************** Pygame Tutorials - Import and Initialize ******************************************** - + Import and Initialize ===================== diff --git a/docs/reST/tutorials/en/intro-to-camera.rst b/docs/reST/tutorials/en/intro-to-camera.rst index 771926990f..291c54d97b 100644 --- a/docs/reST/tutorials/en/intro-to-camera.rst +++ b/docs/reST/tutorials/en/intro-to-camera.rst @@ -28,7 +28,7 @@ for the full API. that use v4l2 on Linux. There is support for other platforms via OpenCV, but this guide will focus on the native module. Most of the code will be valid for other platforms, but certain things like controls will not work. - The module is also marked as **EXPERIMENTAL**, meaning the API could + The module is also marked as **EXPERIMENTAL**, meaning the API could change in subsequent versions. @@ -99,29 +99,29 @@ we will be supplying the camera with the same surface to use each time. :: self.size = (640,480) # create a display surface. standard pygame stuff self.display = pygame.display.set_mode(self.size, 0) - + # this is the same as what we saw before self.clist = pygame.camera.list_cameras() if not self.clist: raise ValueError("Sorry, no cameras detected.") self.cam = pygame.camera.Camera(self.clist[0], self.size) self.cam.start() - + # create a surface to capture to. for performance purposes # bit depth is the same as that of the display surface. self.snapshot = pygame.surface.Surface(self.size, 0, self.display) - + def get_and_flip(self): # if you don't want to tie the framerate to the camera, you can check # if the camera has an image ready. note that while this works # on most cameras, some will never return true. if self.cam.query_image(): self.snapshot = self.cam.get_image(self.snapshot) - + # blit it to the display surface. simple! self.display.blit(self.snapshot, (0,0)) pygame.display.flip() - + def main(self): going = True while going: @@ -131,7 +131,7 @@ we will be supplying the camera with the same surface to use each time. :: # close the camera safely self.cam.stop() going = False - + self.get_and_flip() diff --git a/docs/reST/tutorials/en/intro-to-sprites.rst b/docs/reST/tutorials/en/intro-to-sprites.rst index 53d6978293..9ae4e77351 100644 --- a/docs/reST/tutorials/en/intro-to-sprites.rst +++ b/docs/reST/tutorials/en/intro-to-sprites.rst @@ -374,4 +374,3 @@ both look similar, this is the most flexible way to "see" the difference.) You should go through the code for the sprite module. While the code is a bit "tuned", it's got enough comments to help you follow along. There's even a TODO section in the source if you feel like contributing. - diff --git a/docs/reST/tutorials/en/intro-to-surfarray.rst b/docs/reST/tutorials/en/intro-to-surfarray.rst index 120e844d6d..df6756440c 100644 --- a/docs/reST/tutorials/en/intro-to-surfarray.rst +++ b/docs/reST/tutorials/en/intro-to-surfarray.rst @@ -527,7 +527,7 @@ There is one very useful function though. .. function:: surfarray.blit_array(surface, array) :noindex: - + This will transfer any type of 2D or 3D surface array onto a Surface of the same dimensions. This surfarray blit will generally be faster than assigning an array to a diff --git a/docs/reST/tutorials/en/move-it.rst b/docs/reST/tutorials/en/move-it.rst index b489a6599d..f81b561702 100644 --- a/docs/reST/tutorials/en/move-it.rst +++ b/docs/reST/tutorials/en/move-it.rst @@ -383,8 +383,8 @@ user asks us to stop. :: What this code simply does is, first loop forever, then check if there are -any events from the user. We exit the program if the user presses the close -button on the window. After we've checked all the events we move and draw +any events from the user. We exit the program if the user presses the close +button on the window. After we've checked all the events we move and draw our game objects. (We'll also erase them before they move, too) @@ -471,7 +471,7 @@ our move function under our GameObject class. :: ... if down: ... self.pos.top += self.speed ... if up: - ... self.pos.top -= self.speed + ... self.pos.top -= self.speed ... if self.pos.right > WIDTH: ... self.pos.left = 0 ... if self.pos.top > HEIGHT-SPRITE_HEIGHT: @@ -483,7 +483,7 @@ our move function under our GameObject class. :: There's certainly a lot more going on here, so let's take it one step at a time. First, we've added some default values into the move function, declared as up, -down, left, and right. These booleans will allow us to specifically select a +down, left, and right. These booleans will allow us to specifically select a direction that the object is moving in. The first part, where we go through and check True for each variable, is where we will add to the position of the object, much like before. Right controls horizontal, and top controls vertical positions. @@ -505,7 +505,7 @@ We've already seen that pygame has event handling, and we know that KEYDOWN is an event in this loop. We could, under KEYDOWN, assert the key press matches an arrow key, where we would then call move. However, this movement will only occur once every time a key is pressed, and it therefore will be extremely choppy and -unpleasant. +unpleasant. For this, we can use pygame.key.get_pressed(), which returns a list of all keys, and whether or not they are currently pressed. Since we want these key presses @@ -571,7 +571,7 @@ sure we understand everything. :: A few things not mentioned earlier: we load in a second image and call it entity, and we use that for all objects that aren't the player, which uses the player -image defined earlier. +image defined earlier. And that's all there is to it! Now we have a fully functional player object that is controlled using the arrow keys! @@ -597,4 +597,4 @@ Lastly, you can feel free to come to the pygame mailing list or chatroom with any questions on this stuff. There's always folks on hand who can help you out with this sort of business. -Lastly, have fun, that's what games are for! \ No newline at end of file +Lastly, have fun, that's what games are for! diff --git a/docs/reST/tutorials/en/newbie-guide.rst b/docs/reST/tutorials/en/newbie-guide.rst index e1b4504abc..1265859bc7 100644 --- a/docs/reST/tutorials/en/newbie-guide.rst +++ b/docs/reST/tutorials/en/newbie-guide.rst @@ -495,4 +495,4 @@ the author of Twitch, an entirely average pygame arcade game.* .. _Game Programming Patterns: https://gameprogrammingpatterns.com/contents.html .. _Why Pygame is Slow: https://blubberquark.tumblr.com/post/630054903238262784/why-pygame-is-slow .. _cProfile: https://docs.python.org/3/library/profile.html -.. _SnakeViz: https://jiffyclub.github.io/snakeviz/ \ No newline at end of file +.. _SnakeViz: https://jiffyclub.github.io/snakeviz/ diff --git a/docs/reST/tutorials/en/tom-games4.rst b/docs/reST/tutorials/en/tom-games4.rst index 98048b8515..43818884bf 100644 --- a/docs/reST/tutorials/en/tom-games4.rst +++ b/docs/reST/tutorials/en/tom-games4.rst @@ -101,7 +101,7 @@ This is a really nice feature of Python - class inheritance. Now the ``Ball`` class has all of the functions that come with the ``Sprite`` class, and any object instances of the ``Ball`` class will be registered by Pygame as sprites. Whereas with text and the background, which don't move, it's OK to blit the object onto the background, Pygame handles sprite objects in a different manner, which you'll see when we -look at the whole program's code. +look at the whole program's code. Basically, you create both a ball object, and a sprite object for that ball, and you then call the ball's update function on the sprite object, thus updating the sprite. Sprites also give you sophisticated ways of determining if two objects have collided. @@ -137,7 +137,6 @@ Pygame doesn't support vectors itself, and we can only move the ball by moving i trigonometry, and can be done with the formulae shown in the diagram. If you've studied elementary trigonometry before, none of this should be news to you. But just in case you're forgetful, here are some -useful formulae to remember, that will help you visualise the angles (I find it easier to visualise angles in degrees than in radians!) +useful formulae to remember, that will help you visualise the angles (I find it easier to visualise angles in degrees than in radians!) .. image:: ../assets/tom_formulae.png - diff --git a/docs/reST/tutorials/en/tom-games5.rst b/docs/reST/tutorials/en/tom-games5.rst index 31cc531edd..d8353cf565 100644 --- a/docs/reST/tutorials/en/tom-games5.rst +++ b/docs/reST/tutorials/en/tom-games5.rst @@ -85,7 +85,7 @@ will be set back to "still", and the ``movepos`` attribute will be set back to [ 5.1.1. Diversion 3: Pygame events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - + So how do we know when the player is pushing keys down, and then releasing them? With the Pygame event queue system of course! It's a really easy system to use and understand, so this shouldn't take long :) You've already seen the event queue in action in the basic Pygame program, where it was used to check if the user was quitting the application. The code for moving the bat is about as simple diff --git a/docs/reST/tutorials/es/ChimpanceLineaporLinea.rst b/docs/reST/tutorials/es/ChimpanceLineaporLinea.rst index 2d0d70f38c..f4d65642b2 100644 --- a/docs/reST/tutorials/es/ChimpanceLineaporLinea.rst +++ b/docs/reST/tutorials/es/ChimpanceLineaporLinea.rst @@ -23,22 +23,22 @@ Introducción ------------ Entre los ejemplos de *pygame* hay un ejemplo simple llamado "chimp" (chimpancé). -Este ejemplo simula un mono golpeable que se mueve alrededor de la pantalla +Este ejemplo simula un mono golpeable que se mueve alrededor de la pantalla con promesas de riquezas y recomepensas. El ejemplo en sí es muy simple y acarrea -poco código de comprobación de error. Como modelo de programa, Chimp demuestra muchas +poco código de comprobación de error. Como modelo de programa, Chimp demuestra muchas de las bondades de pygame, como por ejemplo crear una ventana, cargar imágenes y sonidos, representar texto, y manejo de eventos básicos y del mouse. El programa y las imagenes se pueden encontrar dentro de la fuente estándar -de distribución de pygame. Se puede ejecutar al correr `python -m pygame.examples.chimp` +de distribución de pygame. Se puede ejecutar al correr `python -m pygame.examples.chimp` en la terminal. -Este tutorial atravesará el código bloque a bloque, explicando cómo -funciona el mismo. Además, se hará mención de cómo se puede +Este tutorial atravesará el código bloque a bloque, explicando cómo +funciona el mismo. Además, se hará mención de cómo se puede mejorar el código y qué errores de comprobación podrían ser de ayuda. Este tutorial es excelente para aquellas personas que están buscando -una primera aproximación a códigos de *pygame*. Una vez que *pygame* +una primera aproximación a códigos de *pygame*. Una vez que *pygame* esté completamente instalado, podrás encontrar y ejecutar la demostración del chimpancé para ti mismo en el directorio de ejemplos. @@ -58,7 +58,7 @@ Importación de Módulos ---------------------- Este es el código que importa todos los módulos necesarios del programa. -Este código también comprueba la disponibilidad de algunos de los módulos opcionales +Este código también comprueba la disponibilidad de algunos de los módulos opcionales de pygame. :: # Import Modules @@ -75,7 +75,7 @@ de pygame. :: Primero, se importa el módulo estándar de python "os" (sistema operativo). -Esto permite hacer cosas como crear rutas de archivos independientes de la +Esto permite hacer cosas como crear rutas de archivos independientes de la platforma. En la sigueinte línea, se importa el paquete de pygame. En nuestro caso, @@ -84,14 +84,14 @@ ser referenciadas desde el espacio de nombres ``pg``. Algunos de los módulos de pygame son opcionales, y si no fueran encontrados, la evaluación será ``False``. Es por eso que decidimos mostrar (print) un agradable -mensaje de advertencia si los módulos :mod:`font` o +mensaje de advertencia si los módulos :mod:`font` o :mod:`mixer ` no están disponibles. (Aunque estos solo podrían no estar disponibles en situaciones poco comunes). Finalmente, se preparan dos rutas que serán usadas para el resto del código. -Una de ellas es ``main_dir``, que usa el módulo `os.path` y la variable `__file__` -asignada por Python para localizar el archivo de juegos de python, y extraer la carpeta -desde esa ruta. Luego, ésta prepara la ruta ``data_dir`` para indicarle a las +Una de ellas es ``main_dir``, que usa el módulo `os.path` y la variable `__file__` +asignada por Python para localizar el archivo de juegos de python, y extraer la carpeta +desde esa ruta. Luego, ésta prepara la ruta ``data_dir`` para indicarle a las funciones de carga exactamente dónde buscar. @@ -118,7 +118,7 @@ En esta sección examinaremos cada función individualmente. :: Esta función toma el nombre de la imagen a cargar. Opcionalmente, también -toma un argumento que puede usar para definir la clave de color (colorkey) de +toma un argumento que puede usar para definir la clave de color (colorkey) de la imagen, y un argumento para determinar la escala de la imagen. La clave de color se usa en la gráfica para representar un color en la imagen que es transparente. @@ -133,20 +133,20 @@ El paso siguiente es cargar la imagen usando la función :func:`pygame.image.loa Luego de que la imagen se cargue, llamamos a la función `convert()`. Al hacer esto se crea una nueva copia del Surface y convierte su formato de color y la profundidad, de tal forma que coincida con el mostrado. -Esto significa que el dibujo (blitting) de la imagen a la pantalla sucederá +Esto significa que el dibujo (blitting) de la imagen a la pantalla sucederá lo más rápido posible. -Luego, usando la función :func:`pygame.transform.scale` se definirá el tamaño de +Luego, usando la función :func:`pygame.transform.scale` se definirá el tamaño de la imagen. Esta función toma una Surface y el tamaño al cual se debería adecuar. Para darle tamaño con números escalares, se puede tomar la medida y determinar las dimensiones *x* e *y* con número escalar. Finalmente, definimos la clave de color para la imagen. Si el usuario suministró un valor para el parametro de la clave de color, usamos ese valor como la clave -de color de la imagen. Usualmente, éste sería un valor de color RGB -(red-green-blue = rojo-verde-azul), como (255, 255, 255) para el color blanco. -También es posible pasar el valor -1 como la clave de color. En este caso, la -función buscará el color en el píxel de arriba a la izquierda de la imagen, +de color de la imagen. Usualmente, éste sería un valor de color RGB +(red-green-blue = rojo-verde-azul), como (255, 255, 255) para el color blanco. +También es posible pasar el valor -1 como la clave de color. En este caso, la +función buscará el color en el píxel de arriba a la izquierda de la imagen, y lo usará para la clave de color. :: def load_sound(name): @@ -163,14 +163,14 @@ y lo usará para la clave de color. :: return sound -La anterior, es la función para cargar un archivo de sonido. Lo primero que hace +La anterior, es la función para cargar un archivo de sonido. Lo primero que hace esta función es verificar si el módulo :mod:`pygame.mixer` se importó correctamente. En caso de no ser así, la función va a devolver una instancia de reproducción de un -sonido de error. Esto obrará como un objeto de Sonido normal para que el juego se +sonido de error. Esto obrará como un objeto de Sonido normal para que el juego se ejecute sin ningún error de comprobación extra. -Esta funcion es similar a la función de carga de imagen, pero maneja diferentes problemas. -Primero, creamos una ruta completa al sonido de la imagen y cargamos el archivo +Esta funcion es similar a la función de carga de imagen, pero maneja diferentes problemas. +Primero, creamos una ruta completa al sonido de la imagen y cargamos el archivo de sonido. Luego, simplemente devolvemos el objeto de Sonido cargado. @@ -179,7 +179,7 @@ Clases de Objetos para Juegos ----------------------------- En este caso creamos dos clases (classes) que representan los objetos en nuestro juego. -Casi toda la logica del juego se organiza en estas dos clases. A continuación +Casi toda la logica del juego se organiza en estas dos clases. A continuación las revisaremos de a una. :: class Fist(pg.sprite.Sprite): @@ -211,25 +211,25 @@ las revisaremos de a una. :: self.punching = False -En este caso, creamos una clase (class) que representa el puño del jugador. Esta se -deriva de la clase `Sprite` incluida en el módulo :mod:`pygame.sprite`. La +En este caso, creamos una clase (class) que representa el puño del jugador. Esta se +deriva de la clase `Sprite` incluida en el módulo :mod:`pygame.sprite`. La función `__init__` es llamada cuando se crean nuevas instancias de este clase. Esto le permite a la función `__init__` del Sprite preparar nuestro objeto para ser usado como una imagen (sprite). Este juego usa uno de los dibujos de sprite de la clase de Grupo. Estas clases pueden dibujar sprites que tienen un atributo "imagen" y uno "rect". Al cambiar -simplemente estos dos atributos, el compilador (renderer) dibujará la imagen actual +simplemente estos dos atributos, el compilador (renderer) dibujará la imagen actual en la posición actual. -Todos los sprites tienen un método `update()`. Esta función es tipicamente -llamada una vez por cuadro. Es en esta función donde se debería colocar el código -que mueva y actualice las variables para el sprite. El método de `update()` para el -movimiento del puño, mueve el puño al lugar donde se encuentre el puntero del mouse. -Asímismo, compensa sutilmente la posición del puño sobre el objeto, si el puño está +Todos los sprites tienen un método `update()`. Esta función es tipicamente +llamada una vez por cuadro. Es en esta función donde se debería colocar el código +que mueva y actualice las variables para el sprite. El método de `update()` para el +movimiento del puño, mueve el puño al lugar donde se encuentre el puntero del mouse. +Asímismo, compensa sutilmente la posición del puño sobre el objeto, si el puño está en condición de golpear. -Las siguientes dos funciones `punch()` y `unpunch()` cambian la condición de +Las siguientes dos funciones `punch()` y `unpunch()` cambian la condición de golpeado del puño. El método `punch()` también devuelve un valor verdadero si el puño está chocando con el sprite objetivo. :: @@ -282,20 +282,20 @@ el puño está chocando con el sprite objetivo. :: self.original = self.image -Si bien la clase (class) `Chimp` está haciendo un poco más de trabajo que el +Si bien la clase (class) `Chimp` está haciendo un poco más de trabajo que el puño, no resulta mucho más complejo. Esta clase moverá al chimpancé hacia adelante -y hacia atrás, por la pantalla. Cuando el mono es golpeado, él girará -con un efecto de emoción. Esta clase también es derivada de la base de clases -:class:`Sprite ` y es iniciada de igual manera que el puño. +y hacia atrás, por la pantalla. Cuando el mono es golpeado, él girará +con un efecto de emoción. Esta clase también es derivada de la base de clases +:class:`Sprite ` y es iniciada de igual manera que el puño. Mientras se inicia, la clase también establece el atributo "area" para que sea del tamaño de la pantalla de visualización. La función `update` para el chimpancé simplemente se fija en el estado actual -del mono. Esta puede ser "dizzy" (mareado), la cual sería verdadera si el mono +del mono. Esta puede ser "dizzy" (mareado), la cual sería verdadera si el mono está girando a causa del golpe. La función llama al método `_spin` o `_walk`. Estas funciones son prefijadas con un guión bajo, lo cual en el idioma estándar de python sugiere que estos métodos deberían ser solo usados por la clase `Chimp`. -Podríamos incluso hasta escribirlas con un doble guión bajo, lo cual indicaría a +Podríamos incluso hasta escribirlas con un doble guión bajo, lo cual indicaría a python que realmente intente hacerlas un método privado, pero no necesitamos tal protección. :) @@ -307,13 +307,13 @@ un efecto crudo que hace que el mono se vea como si estuviera cambiando de dirección. El método `_spin` es llamado cuando el mono está actualmente en estado "dizzy" -(mareado). El atributo 'dizzy' es usado para guardar el monto de rotación. +(mareado). El atributo 'dizzy' es usado para guardar el monto de rotación. Cuando el mono ha rotado por completo en su eje (360 grados) se resetea la imagen a la versión original no rotada. Antes de llamar a la función :func:`pygame.transform.rotate`, verás que el código hace una referencia local -a la función simplemente llamanda "rotate". No hay ncesidad de hacer eso en -este ejemplo, aquí fue realizada para mantener la siguiente línea un poco -más corta. Notese que al llamar a la función `rotate`, se está siempre rotando +a la función simplemente llamanda "rotate". No hay ncesidad de hacer eso en +este ejemplo, aquí fue realizada para mantener la siguiente línea un poco +más corta. Notese que al llamar a la función `rotate`, se está siempre rotando la imagen original del mono. Cuando rotamos, hay un pequeña pérdida de calidad. Rotar repetidamente la misma imagen genera que la calidad se deteriore cada vez más. Esto se debe a que las esquinas de la imagen van a haber sido rotadas de más, @@ -321,8 +321,8 @@ causando que la imagen se haga más grande. Nos aseguramos que la nueva imagen coincida con el centro de la vieja imagen, para que de esta forma se rote sin moverse. -El último método es `punched()` el cual indica al sprite que entre en un estado de -mareo. Esto causará que la imagen empice a girar. Además, también crea una copia de +El último método es `punched()` el cual indica al sprite que entre en un estado de +mareo. Esto causará que la imagen empice a girar. Además, también crea una copia de la actual imagen llamada "original". @@ -344,19 +344,19 @@ La primera línea para inicializar *pygame* realiza algo de trabajo por nosotros Verifica a través del módulo importado *pygame* e intenta inicializar cada uno de ellos. Es posible volver y verificar que los módulos que fallaron al iniciar, pero no vamos a molestarnos acá con eso. También es posible tomar mucho más control -e inicializar cada módulo en especifico, uno a uno. Ese tipo de control no es +e inicializar cada módulo en especifico, uno a uno. Ese tipo de control no es necesario generalmente, pero está disponible en caso de ser deseado. -Luego, se configura el modo de visualización de gráficos. Notse que el módulo +Luego, se configura el modo de visualización de gráficos. Notse que el módulo :mod:`pygame.display` es usado para controlar todas las configuraciones de visualización. En este caso nosotros estamos buscando una ventana 1280x480, con ``SCALED``, que es la señal de visualización (display flag) -Esto aumenta proporcionalmente la ventana de visualización (display) más grande que la +Esto aumenta proporcionalmente la ventana de visualización (display) más grande que la ventana. (window) Por último, establecemos el título de la ventana y apagamos el cursor del mouse para nuestra ventana. Es una acción básica y ahora tenemos una pequeña ventana negra -que está lista para nuestras instrucciones (bidding) u ofertas. Generalmente, el cursor +que está lista para nuestras instrucciones (bidding) u ofertas. Generalmente, el cursor se mantiene visible por default, asi que no hay mucha necesidad de realmente establecer este estado a menos que querramos esconderlo. @@ -373,21 +373,21 @@ El primer paso es crear el Surface. :: background.fill((170, 238, 187)) Esto crea el nuevo surface, que en nuestro caso, es del mismo tamaño que -la ventana de visualización. Notese el llamado extra a `convert()` luego +la ventana de visualización. Notese el llamado extra a `convert()` luego de crear la Surface. La función `convert()` sin argumentos es para asegurarnos que nuestro fondo sea del mismo formato que la ventana de visualización, lo cual nos va a brindar resultados más rápidos. -Lo que nosotros hicimos también, fue rellenar el fondo con un color verduzco. -La función `fill()` suele tomar como argumento tres instancias de colores RGB, -pero soporta muchos formatos de entrada. Para ver todos los formatos de color +Lo que nosotros hicimos también, fue rellenar el fondo con un color verduzco. +La función `fill()` suele tomar como argumento tres instancias de colores RGB, +pero soporta muchos formatos de entrada. Para ver todos los formatos de color veasé :mod:`pygame.Color`. Centrar Texto en el Fondo ------------------------- -Ahora que tenemos el surface del fondo, vamos a representar el texto en él. +Ahora que tenemos el surface del fondo, vamos a representar el texto en él. Nosotros solo haremos esto si vemos que el módulo :mod:`pygame.font` se importó correctamente. De no ser así, hay que saltear esta sección. :: @@ -402,7 +402,7 @@ crear la fuente del objeto y renderizarlo (representarlo) en una nueva Surface. Luego, buscamos el centro de esa nueva surface y lo pegamos (blit) al fondo. La fuente es creada con el constructor `Font()` del módulo `font`. Generalmente, -uno va a poner el nombre de la fuente TrueType en esta función, pero también se +uno va a poner el nombre de la fuente TrueType en esta función, pero también se puede poner `None`, como hicimos en este caso, y entonces se usará la fuente por predeterminada. El constructor `Font` también necesita la información del tamaño de la fuente que se quiere crear. @@ -412,8 +412,8 @@ Luego vamos a represetar (renderizar) la fuente en la nueva surface. La función En este caso, también le estamos pidiendo al render que cree un texto suavizado (para un lindo efecto de suavidad en la apariencia) y que use un color gris oscuro. -Lo siguiente que necesitamos es encontrar la posición la posición central, para -colocar el texto en el centro de la pantalla. Creamos un objeto "Rect" de las +Lo siguiente que necesitamos es encontrar la posición la posición central, para +colocar el texto en el centro de la pantalla. Creamos un objeto "Rect" de las dimensiones del texto, lo cual nos permite asignarlo fácilmente al centro de la pantalla. @@ -434,7 +434,7 @@ El blit se explica por sí mismo, pero ¿qué está haciendo esa rutina flip? En pygame, los cambios en la surface de visualización (display) no se hacen visibles inmediatamente. Normalmente, la pantalla debe ser actualizacada para que el usuario pueda ver los cambios realizados. En este caso la función `flip()` es perfecta para eso -porque se encarga de toda el área de la pantalla. +porque se encarga de toda el área de la pantalla. Preparar Objetos del Juego @@ -443,7 +443,7 @@ Preparar Objetos del Juego En este caso crearemos todos los objetos que el juego va a necesitar. :: - + whiff_sound = load_sound("whiff.wav") punch_sound = load_sound("punch.wav") chimp = Chimp() @@ -452,12 +452,12 @@ En este caso crearemos todos los objetos que el juego va a necesitar. clock = pg.time.Clock() Primero cargamos dos efectos de sonido usando la función `load_sound`, que se -encuentra definida en código arriba. Luego, creamos una instancia para cada -uno de los sprites de la clase. Por último, creamos el sprite +encuentra definida en código arriba. Luego, creamos una instancia para cada +uno de los sprites de la clase. Por último, creamos el sprite :class:`Group ` que va a contener todos nuestros sprites. Nosotros creamos el grupo llamado "allsprites" al pasar una lista con todos los sprites que deberían -pertenecer al grupo. Exise la posibilidad, si más adelante quisieramos, de agregar +pertenecer al grupo. Exise la posibilidad, si más adelante quisieramos, de agregar o sacar sprites de este grupo, pero para este juego no sería necesario. El objeto `clock` que creamos será usado para ayudar a controlar la frequencia de @@ -476,7 +476,7 @@ No hay mucho por acá, solo un loop infinito. :: Todos los juegos se ejecutan sobre una especie de loop. El orden usual de las cosas es verificar el estado de la computadora y la entrada de usuario, mover y actualizar -el estado de todos los objetos, y luego dibujarlos en la pantalla. Verás que este +el estado de todos los objetos, y luego dibujarlos en la pantalla. Verás que este ejemplo no es diferente. También haremos un llamado a nuestro objeto `clock`, que asegurará que nuestro juego @@ -501,14 +501,14 @@ Este es un caso extremandamente simple para trabajar la cola de eventos. :: elif event.type == pg.MOUSEBUTTONUP: fist.unpunch() -Primero obtenemos todos los Eventos (events) disponibles en pygame y los recorremos en loop. -Las primeras dos pruebas es para ver si el usuario dejó nuestro juego, o si +Primero obtenemos todos los Eventos (events) disponibles en pygame y los recorremos en loop. +Las primeras dos pruebas es para ver si el usuario dejó nuestro juego, o si presionó la tecla de escape. En estos casos, configuramos ``going`` en ``False``, permitiendonos salir del loop infinito. -A continuación, verificamos si se presionó o si se soltó el botón del mouse. En el +A continuación, verificamos si se presionó o si se soltó el botón del mouse. En el caso de que el botón se haya presionado, preguntamos al primer objeto si chocó con -el mono. Se reproduce el sonido apropiado, y si el mono fue golpeado, le decimos +el mono. Se reproduce el sonido apropiado, y si el mono fue golpeado, le decimos que empiece a girar (al hacer un llamado a su método `punched()` ) @@ -522,7 +522,7 @@ Actualizar los Sprites Los grupos de Sprite tienen un método `update()`, que simplemente llama al método de actualización para todos los sprites que contiene. Cada uno de los objetos se va a mover, dependiendo de cuál sea el estado en el que estén. Acá -es donde el mono se va a mover de un lado a otro, o va a girar un poco más +es donde el mono se va a mover de un lado a otro, o va a girar un poco más lejos si fue recientemente golpeado. @@ -530,17 +530,17 @@ lejos si fue recientemente golpeado. Dibujar la Escena Completa -------------------------- -Ahora que todos los objetos están en el lugar indicado, es el momento para +Ahora que todos los objetos están en el lugar indicado, es el momento para dibujarlos. :: screen.blit(background, (0, 0)) allsprites.draw(screen) pygame.display.flip() -La primera llamada de blit dibujará el fondo en toda la pantalla. Esto borra -todo lo que vimos en el cuadro anterior (ligeramente ineficiente, pero -suficientemnte bueno para este juego). A continuación, llamamos al método -`draw()` del contenedor de sprites. Ya que este contenedor de sprites es +La primera llamada de blit dibujará el fondo en toda la pantalla. Esto borra +todo lo que vimos en el cuadro anterior (ligeramente ineficiente, pero +suficientemnte bueno para este juego). A continuación, llamamos al método +`draw()` del contenedor de sprites. Ya que este contenedor de sprites es en realidad una instancia del grupo de sprites "DrawPlain", sabe como dibujar nuestros sprites. Por último, usamos el método `flip()` para voltear los contenidos del software de pygame. Se realiza el flip a través del cargado de la imagen en segundo @@ -555,6 +555,6 @@ El usuario ha salido del juego, hora de limpiar (clean up) :: pg.quit() Hacer la limpieza, el cleanup, de la ejecución del juego en *pygame* es extremandamente -simple. Ya que todas las variables son automáticamente destruidas, nosotros no +simple. Ya que todas las variables son automáticamente destruidas, nosotros no tenemos que hacer realmnete nada, únicamente llamar a `pg.quit()` que explicitamente hace la limpieza de las partes internas del pygame. diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/1.\355\224\204\353\241\244\353\241\234\352\267\270/\354\206\214\352\260\234.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/1.\355\224\204\353\241\244\353\241\234\352\267\270/\354\206\214\352\260\234.rst" index f0495254a4..b82626d373 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/1.\355\224\204\353\241\244\353\241\234\352\267\270/\354\206\214\352\260\234.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/1.\355\224\204\353\241\244\353\241\234\352\267\270/\354\206\214\352\260\234.rst" @@ -123,5 +123,3 @@ Contact: rumia0601@gmail.com (파이게임 게임의 예시- 배틀십) 요약하자면, 파이게임은 저급 수준(콘솔 환경은 예시 중 하나)의 게임 제작 프로그램과 고급 수준(게임 엔진은 예시 중 하나)의 게임 제작 프로그램의 장점을 모두 가진다는 것이다. 파이게임은 이 둘 사이의 좋은 연결점이 된다. 이것이 파이게임을 쓸 이유이다. 더 복잡한 게임 엔진을 최대한 활용해 게임을 만드는 1인 개발자가 목표가 아닌 이상 (빨리 그 게임 엔진을 배우는 것이 낫다!), 콘솔 환경용 게임이 아닌 더 발전된 환경에서 게임을 한번쯤은 코딩해 보고 싶다면 (물론, 푹 빠지면 계속 코딩하게 될 것이다!), 한번쯤은 파이게임을 시도해 볼만 하다. - - diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/2.\355\205\215\354\212\244\355\212\270 \354\266\234\353\240\245/\352\270\260\354\264\210 \355\205\234\355\224\214\353\246\277\352\263\274 \354\266\234\353\240\245.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/2.\355\205\215\354\212\244\355\212\270 \354\266\234\353\240\245/\352\270\260\354\264\210 \355\205\234\355\224\214\353\246\277\352\263\274 \354\266\234\353\240\245.rst" index f00dea835e..47173e2361 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/2.\355\205\215\354\212\244\355\212\270 \354\266\234\353\240\245/\352\270\260\354\264\210 \355\205\234\355\224\214\353\246\277\352\263\274 \354\266\234\353\240\245.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/2.\355\205\215\354\212\244\355\212\270 \354\266\234\353\240\245/\352\270\260\354\264\210 \355\205\234\355\224\214\353\246\277\352\263\274 \354\266\234\353\240\245.rst" @@ -89,7 +89,7 @@ Contact: rumia0601@gmail.com 우선, 무언가를 출력하기 위해선 소스코드가 어떻게 작성되어야 하는지 그 형식을 살펴보자. 소스코드는 4개의 부분으로 나눠질 수 있다. Header(#1-#2), Initial문(#3-#12), Always문(#13-#20), Event문(#16-#19)가 그것이다. Header에선, 모듈들을 import하는 작업이 실행된다. 여기에 import pygame, sys는 항상 필요하다. 이 프로젝트가 파이게임 프로젝트이며, 사용자가 프로그램을 종료하고 싶을 때 종료되어야 하기 때문에(실제로 #19에서 sys.exit()가 실행된다) 추가적인 설명이 필요 없는 당연한 문구이다. from pygame.locals import*는 #17에서의 QUIT같은 유용한 상수들을 선언 없이 사용하기 위해 거의 반필수적으로 필요하다. - + Initial문(무한 반복문 이전의 문장들)에선, 전역 변수가 한번만 초기화되거나 몇몇 함수가 한번만 호출된다. 주로 색상과 같은 전역 변수들이 가독성을 높이기 위해 초기화된다. 파이게임은 여러가지 색상을 사용하는 화려한 GUI임을 까먹어선 안된다. (게임이므로) 하나의 색상은 R값, G값, B값 3개의 구성 요소를 가진다. 그래서 색상 변수는 red = (255, 0, 0)와 같이 선언되어야 한다. pygame.init()과 같은 함수는 나중에 사용할 함수를 위해선 가장 앞서서 호출되어야 한다. (이 외의 함수들은 나중에 언급하겠다.) Always문(무한 반복문)에선, 전역 변수가 계속 업데이트되거나 몇몇 함수가 계속 호출된다. (물론, 조건문이 있는 경우 조건이 맞을 때만) pygame.display.update() 라는 함수는 일반적으로 다른 변수/함수의 처리가 끝난 이후에 호출되는데, 이 함수는 처리의 결과물들을 스크린(= 모니터)에 출력하는 함수이기 때문이다. 이 함수가 Always문 마지막에 실행되지 않으면, 출력되는 화면과 게임 내부 데이터가 서로 일치하지 않는 문제가 생길 수 있다. (이 외의 함수들은 나중에 언급하겠다.) @@ -117,7 +117,7 @@ Event문(모든 이벤트를 체크하는 반복문)에선, 특정 이벤트가 pygame.display.set_caption("Hello World Project") #7 myScreen = pygame.display.set_mode((640, 480)) #8 myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) #9 - myText = myTextFont.render("Hello World!", True, red, green) #10 + myText = myTextFont.render("Hello World!", True, red, green) #10 myTextArea = myText.get_rect() #11 myTextArea.center = (320, 240) #12 @@ -131,4 +131,3 @@ Event문(모든 이벤트를 체크하는 반복문)에선, 특정 이벤트가 sys.exit() #19 pygame.display.update() #20 - diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/3.\355\205\215\354\212\244\355\212\270 \354\235\264\353\217\231/\352\270\260\354\264\210 \354\262\230\353\246\254.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/3.\355\205\215\354\212\244\355\212\270 \354\235\264\353\217\231/\352\270\260\354\264\210 \354\262\230\353\246\254.rst" index ef2d2d8cff..398ed8149f 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/3.\355\205\215\354\212\244\355\212\270 \354\235\264\353\217\231/\352\270\260\354\264\210 \354\262\230\353\246\254.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/3.\355\205\215\354\212\244\355\212\270 \354\235\264\353\217\231/\352\270\260\354\264\210 \354\262\230\353\246\254.rst" @@ -104,10 +104,10 @@ Contact: rumia0601@gmail.com red = (255,0,0) green = (0,255,0) pygame.init() - pygame.display.set_caption("Moving World Project") + pygame.display.set_caption("Moving World Project") myScreen = pygame.display.set_mode((640, 480)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) - myText = myTextFont.render("Moving World!", True, red, green) + myText = myTextFont.render("Moving World!", True, red, green) myTextArea = myText.get_rect() myTextArea.center = (320, 240) fpsClock = pygame.time.Clock() #1 @@ -138,7 +138,7 @@ Contact: rumia0601@gmail.com myTextArea.center = (320 + x, 240 + y) #10 - + myScreen.fill(white) myScreen.blit(myText, myTextArea) @@ -149,4 +149,3 @@ Contact: rumia0601@gmail.com pygame.display.update() fpsClock.tick(60) #11 - diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/4.\355\205\215\354\212\244\355\212\270 \354\241\260\354\242\205/\352\270\260\354\264\210 \354\236\205\353\240\245.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/4.\355\205\215\354\212\244\355\212\270 \354\241\260\354\242\205/\352\270\260\354\264\210 \354\236\205\353\240\245.rst" index 464e57b0c4..93e581ea70 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/4.\355\205\215\354\212\244\355\212\270 \354\241\260\354\242\205/\352\270\260\354\264\210 \354\236\205\353\240\245.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/4.\355\205\215\354\212\244\355\212\270 \354\241\260\354\242\205/\352\270\260\354\264\210 \354\236\205\353\240\245.rst" @@ -102,10 +102,10 @@ KEYDOWN은 “이 키는 이전에는 눌리지 않았지만, 지금은 눌렸 red = (255,0,0) green = (0,255,0) pygame.init() - pygame.display.set_caption("Controlling World Project") + pygame.display.set_caption("Controlling World Project") myScreen = pygame.display.set_mode((640, 480)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) - myText = myTextFont.render("Controlling World!", True, red, green) + myText = myTextFont.render("Controlling World!", True, red, green) myTextArea = myText.get_rect() myTextArea.center = (320, 240) fpsClock = pygame.time.Clock() @@ -138,7 +138,7 @@ KEYDOWN은 “이 키는 이전에는 눌리지 않았지만, 지금은 눌렸 elif event.key == K_RIGHT: moveDown = 0 moveRight = 1 - + if(moveRight == 1): #6 x = x + 10 elif(moveRight == -1): #7 @@ -149,4 +149,3 @@ KEYDOWN은 “이 키는 이전에는 눌리지 않았지만, 지금은 눌렸 y = y - 10 pygame.display.update() - diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/5.HP\353\260\224/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\262\230\353\246\254.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/5.HP\353\260\224/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\262\230\353\246\254.rst" index 375bbbf199..4111aca87f 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/5.HP\353\260\224/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\262\230\353\246\254.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/5.HP\353\260\224/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\262\230\353\246\254.rst" @@ -214,8 +214,8 @@ Contact: rumia0601@gmail.com import pygame, sys from pygame.locals import* - - maxHP = 10 + + maxHP = 10 white = (255,255,255) gray = (127,127,127) black = (0,0,0) @@ -232,18 +232,18 @@ Contact: rumia0601@gmail.com myTextArea = myText.get_rect() myTextArea.center = (width/2, height/2) #3 fpsClock = pygame.time.Clock() - + def main(): #4 HP = 5 - + while True: myText = myTextFont.render((str(HP) + "/" + str(maxHP)), True, red, gray) - + myScreen.fill(gray) - + myScreen.blit(myText, myTextArea) drawHP(HP) #5 - + for event in pygame.event.get(): if event.type == QUIT: pygame.quit() @@ -255,21 +255,21 @@ Contact: rumia0601@gmail.com elif event.key == K_DOWN: if HP != 0: HP = HP - 1 - + pygame.display.update() fpsClock.tick(60) - + def drawHP(HP): #6 r = int((height - 40) / maxHP) - + pygame.draw.rect(myScreen, black, (20, 20, 20, 20 + ((maxHP - 0.5) * r))) - + for i in range(maxHP): if HP >= (maxHP - i): pygame.draw.rect(myScreen, red, (20, 20 + (i * r), 20, r)) pygame.draw.rect(myScreen, white, (20, 20 + (i * r), 20, r), 1) - + return - + if __name__ == '__main__': #7 main() diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/6.\353\262\204\355\212\274\353\223\244/\354\213\254\355\231\224 \354\236\205\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\266\234\353\240\245.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/6.\353\262\204\355\212\274\353\223\244/\354\213\254\355\231\224 \354\236\205\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\266\234\353\240\245.rst" index a524c66cdf..907dc206af 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/6.\353\262\204\355\212\274\353\223\244/\354\213\254\355\231\224 \354\236\205\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\266\234\353\240\245.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/6.\353\262\204\355\212\274\353\223\244/\354\213\254\355\231\224 \354\236\205\353\240\245 \352\267\270\353\246\254\352\263\240 \354\213\254\355\231\224 \354\266\234\353\240\245.rst" @@ -185,8 +185,8 @@ KEYDOWN이 사용되었지만, 아직도 이 게임이 완전한 GUI가 아닌 import pygame, sys from pygame.locals import* - - maxHP = 10 + + maxHP = 10 white = (255,255,255) gray = (127,127,127) black = (0,0,0) @@ -195,7 +195,7 @@ KEYDOWN이 사용되었지만, 아직도 이 게임이 완전한 GUI가 아닌 blue = (0,0,255) pygame.init() pygame.display.set_caption("Array buttons Project") - width = 640 + width = 640 height = 480 myScreen = pygame.display.set_mode((width, height)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) @@ -203,19 +203,19 @@ KEYDOWN이 사용되었지만, 아직도 이 게임이 완전한 GUI가 아닌 myTextArea = myText.get_rect() myTextArea.center = (width/2, height/2) fpsClock = pygame.time.Clock() - + def main(): HP = 5 - + while True: myText = myTextFont.render((str(HP) + "/" + str(maxHP)), True, red, gray) - + myScreen.fill(gray) - + myScreen.blit(myText, myTextArea) drawHP(HP) drawButtons() - + for event in pygame.event.get(): if event.type == QUIT: pygame.quit() @@ -234,28 +234,28 @@ KEYDOWN이 사용되었지만, 아직도 이 게임이 완전한 GUI가 아닌 HP = HP + 1 elif pygame.Rect(325, 425, 45, 45).collidepoint(x, y): if HP != 0: - HP = HP - 1 - + HP = HP - 1 + pygame.display.update() fpsClock.tick(60) - + def drawHP(HP): r = int((height - 40) / maxHP) - + pygame.draw.rect(myScreen, black, (20, 20, 20, 20 + ((maxHP - 0.5) * r))) - + for i in range(maxHP): if HP >= (maxHP - i): pygame.draw.rect(myScreen, red, (20, 20 + (i * r), 20, r)) pygame.draw.rect(myScreen, white, (20, 20 + (i * r), 20, r), 1) - + return - + def drawButtons(): r = 45 r_margin = 10 colors = [red, black] - + num = 2 margin = int((width - ((r * num) + (r_margin * (num - 1)))) / 2) for i in range(0, num): @@ -263,6 +263,6 @@ KEYDOWN이 사용되었지만, 아직도 이 게임이 완전한 GUI가 아닌 up = height - r - 10 pygame.draw.rect(myScreen, colors[i], (left, up, r, r)) pygame.draw.rect(myScreen, gray, (left + 2, up + 2, r - 4, r - 4), 2) - + if __name__ == '__main__': main() diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/7.\352\262\214\354\236\204\355\214\220/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\241\260\352\270\210 \353\215\224.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/7.\352\262\214\354\236\204\355\214\220/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\241\260\352\270\210 \353\215\224.rst" index 594d1ee977..a7ecf1050d 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/7.\352\262\214\354\236\204\355\214\220/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\241\260\352\270\210 \353\215\224.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/7.\352\262\214\354\236\204\355\214\220/\354\213\254\355\231\224 \354\266\234\353\240\245 \352\267\270\353\246\254\352\263\240 \354\241\260\352\270\210 \353\215\224.rst" @@ -116,8 +116,8 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 import pygame, sys, random from pygame.locals import* - - maxHP = 10 + + maxHP = 10 white = (255,255,255) gray = (127,127,127) black = (0,0,0) @@ -126,7 +126,7 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 blue = (0,0,255) pygame.init() pygame.display.set_caption("Red or Black Project") - width = 640 + width = 640 height = 480 myScreen = pygame.display.set_mode((width, height)) myTextFont = pygame.font.Font("HoonWhitecatR.ttf", 32) @@ -134,26 +134,26 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 myTextArea = myText.get_rect() myTextArea.center = (width/2, height/2) fpsClock = pygame.time.Clock() - + def main(): HP = 5 board, b_red, b_black = generateBoard(5,5) #1 - + while True: myText = myTextFont.render((str(HP) + "/" + str(maxHP)), True, red, gray) - + myScreen.fill(gray) - + myScreen.blit(myText, myTextArea) drawHP(HP) drawButtons() drawBoard(board) #2 - + for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() - + elif event.type == KEYDOWN: if event.key == K_UP: if HP != 10: @@ -163,7 +163,7 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 HP = HP - 1 elif event.type == MOUSEBUTTONUP: x, y = event.pos - + if pygame.Rect(270, 425, 45, 45).collidepoint(x, y): #3 if b_red >= b_black: if HP != 10: @@ -173,7 +173,7 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 if HP != 0: HP = HP - 1 board, b_red, b_black = generateBoard(5,5) - + elif pygame.Rect(325, 425, 45, 45).collidepoint(x, y): #4 if b_red <= b_black: if HP != 10: @@ -183,63 +183,63 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 if HP != 0: HP = HP - 1 board, b_red, b_black = generateBoard(5,5) - + pygame.display.update() fpsClock.tick(60) - + def drawHP(HP): r = int((height - 40) / maxHP) - + pygame.draw.rect(myScreen, gray, (20, 20, 20, 20 + ((maxHP - 0.5) * r))) - + for i in range(maxHP): if HP >= (maxHP - i): pygame.draw.rect(myScreen, blue, (20, 20 + (i * r), 20, r)) pygame.draw.rect(myScreen, white, (20, 20 + (i * r), 20, r), 1) - + return - + def drawButtons(): r = 45 r_margin = 10 colors = [red, black] - + num = 2 margin = int((width - ((r * num) + (r_margin * (num - 1)))) / 2) - + for i in range(0, num): left = margin + (i * r) + (i * r_margin) up = height - r - 10 pygame.draw.rect(myScreen, colors[i], (left, up, r, r)) - pygame.draw.rect(myScreen, gray, (left + 2, up + 2, r - 4, r - 4), 2) - + pygame.draw.rect(myScreen, gray, (left + 2, up + 2, r - 4, r - 4), 2) + def generateBoard(width, height): #5 board = [] b_red = 0 b_black = 0 - + for x in range(width): column = [] for y in range(height): column.append(random.randint(0, 1)) board.append(column) - + for x in range(width): for y in range(height): if(board[x][y] == 1): b_red = b_red + 1 elif(board[x][y] == 0): b_black = b_black + 1 - + return board, b_red, b_black - + def drawBoard(board): #6 r = 50 b_width = 5 b_height = 5 l_margin = int((width - (b_width * r)) / 2) u_margin = int((height - (b_height * r)) / 2) - + for x in range(5): for y in range(5): left = x * r + l_margin @@ -249,10 +249,10 @@ generateboard 함수는 무작위로 만들어진 2차원 배열과 빨간 블 elif board[x][y] == 0: color = black pygame.draw.rect(myScreen, color, (left, up, r, r)) - + left = l_margin up = u_margin pygame.draw.rect(myScreen, white, (left-1, up-1, r * 5 + 1, r * b_height + 1), 1) - + if __name__ == '__main__': main() diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/8.\354\227\220\355\225\204\353\241\234\352\267\270/\354\227\220\355\225\204\353\241\234\352\267\270.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/8.\354\227\220\355\225\204\353\241\234\352\267\270/\354\227\220\355\225\204\353\241\234\352\267\270.rst" index 1e56d39fff..20517bb99b 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/8.\354\227\220\355\225\204\353\241\234\352\267\270/\354\227\220\355\225\204\353\241\234\352\267\270.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/8.\354\227\220\355\225\204\353\241\234\352\267\270/\354\227\220\355\225\204\353\241\234\352\267\270.rst" @@ -15,4 +15,3 @@ Contact: rumia0601@gmail.com 결론이 무엇인가? 출력이 입력보다 크다는 것이다. 우리는 우리의 지식만으로 지식보다 더 폭넓은 프로그램을 구현할 수 있다. 또는 우리는 새로운 지식을 기존의 지식에 연결시키면서 습득할 수도 있다. 그것이 프로그래밍의 특성이다. 게임도 마찬가지이다. “난수”라는 개념은 모든 게임(이미 구현한 게임도 포함!)에서 대단히 중요한 개념이다. 난수까지 고려되었을 때 경우의 수는 매우 커지게 된다. 만약 하나의 난수가 다른 난수까지 영향을 미치게 된다면, “눈사태”와 같은 효과가 나게 된다. 그것이 게임이 흥미로운 이유이다. “난수”라는 개념은 소설, 음악, 영화 등은 가질 수 없는 게임만의 특성이다. 테트리스를 생각해 보아라. 알렉세이 파지트노프가 테트리스를 위해 얼만큼의 시간을 투자했을까? 이 시간이 35년 넘게 전세계 사람들이 플레이 한 시간보다 클까? 이것이 바로 프로그래밍과 게임이 갖는 두 특성이 완벽히 발휘된 예시이다. 그러므로, 게임을 만드는 것은 눈사태를 일으키는 것과 같다. 이제 아무 게임이나 만들 시간이다! 배우고, 활용하고, 시행 착오를 겪어 보자! - diff --git "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/\352\260\234\354\232\224.rst" "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/\352\260\234\354\232\224.rst" index e1c2b76460..6dfe791961 100644 --- "a/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/\352\260\234\354\232\224.rst" +++ "b/docs/reST/tutorials/ko/\353\271\250\352\260\204\353\270\224\353\241\235 \352\262\200\354\235\200\353\270\224\353\241\235/\352\260\234\354\232\224.rst" @@ -28,4 +28,4 @@ 게임판 :doc:`8 부 <8.에필로그/에필로그>` - 에필로그 \ No newline at end of file + 에필로그 diff --git a/meson_options.txt b/meson_options.txt index 3152e69736..8d409fba9c 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -17,7 +17,7 @@ option('font', type: 'feature', value: 'enabled') option('freetype', type: 'feature', value: 'enabled') # Controls whether pygame.midi is built. -# Enabled by default, disable explicitly if you don't want to compile with +# Enabled by default, disable explicitly if you don't want to compile with # portmidi/porttime. option('midi', type: 'feature', value: 'enabled') diff --git a/pyproject.toml b/pyproject.toml index 97554d5744..76c546710b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -107,7 +107,7 @@ quote-style = "preserve" [tool.uv.pip] only-binary = ["numpy"] -# 1. skip all 32-bit manylinux (i686) +# 1. skip all 32-bit manylinux (i686) # 2. skip all pypy+arm combinations [[tool.cibuildwheel.overrides]] select = "{*-manylinux_i686,pp*-*{arm64,aarch64}}" diff --git a/src_c/SDL_gfx/SDL_gfxPrimitives.h b/src_c/SDL_gfx/SDL_gfxPrimitives.h index 5f532524e3..ec5dc17c3b 100644 --- a/src_c/SDL_gfx/SDL_gfxPrimitives.h +++ b/src_c/SDL_gfx/SDL_gfxPrimitives.h @@ -133,9 +133,9 @@ lineRGBA(SDL_Surface *dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 r, Sint16 x2, Sint16 y2, Uint8 r, Uint8 g, Uint8 b, Uint8 a); /* Thick Line */ - SDL_GFXPRIMITIVES_SCOPE int thickLineColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, + SDL_GFXPRIMITIVES_SCOPE int thickLineColor(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 width, Uint32 color); - SDL_GFXPRIMITIVES_SCOPE int thickLineRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, + SDL_GFXPRIMITIVES_SCOPE int thickLineRGBA(SDL_Surface * dst, Sint16 x1, Sint16 y1, Sint16 x2, Sint16 y2, Uint8 width, Uint8 r, Uint8 g, Uint8 b, Uint8 a); #endif /********** CURRENTLY NOT USED BY pygame.gfxdraw **********/ diff --git a/src_c/cython/pygame/_sdl2/audio.pyx b/src_c/cython/pygame/_sdl2/audio.pyx index 83d15566ef..c3667d5e32 100644 --- a/src_c/cython/pygame/_sdl2/audio.pyx +++ b/src_c/cython/pygame/_sdl2/audio.pyx @@ -57,7 +57,7 @@ def get_audio_device_names(iscapture = False): cdef int count = SDL_GetNumAudioDevices(iscapture) if count == -1: raise error('Audio system not initialised') - + names = [] for i in range(count): name = SDL_GetAudioDeviceName(i, iscapture) @@ -84,8 +84,8 @@ cdef void recording_cb(void* userdata, Uint8* stream, int len) nogil: raise -# disable auto_pickle since it causes stubcheck error -@cython.auto_pickle(False) +# disable auto_pickle since it causes stubcheck error +@cython.auto_pickle(False) cdef class AudioDevice: def __cinit__(self): self._deviceid = 0 diff --git a/src_c/cython/pygame/_sdl2/controller_old.pyx b/src_c/cython/pygame/_sdl2/controller_old.pyx index 6df1dc4407..cb7d5ad307 100644 --- a/src_c/cython/pygame/_sdl2/controller_old.pyx +++ b/src_c/cython/pygame/_sdl2/controller_old.pyx @@ -10,7 +10,7 @@ cdef extern from "../pygame.h" nogil: cdef extern from "SDL.h" nogil: void SDL_free(void *mem) - int SDL_VERSION_ATLEAST(int major, int minor, int patch) + int SDL_VERSION_ATLEAST(int major, int minor, int patch) import_pygame_joystick() @@ -100,8 +100,8 @@ def name_forindex(index): return None -# disable auto_pickle since it causes stubcheck error -@cython.auto_pickle(False) +# disable auto_pickle since it causes stubcheck error +@cython.auto_pickle(False) cdef class Controller: _controllers = [] @@ -250,7 +250,7 @@ cdef class Controller: """ _gamecontroller_init_check() self._CLOSEDCHECK() - + duration = max(duration, 0) low = min(max(low_frequency, 0.0), 1.0) high = min(max(high_frequency, 0.0), 1.0) diff --git a/src_c/cython/pygame/_sdl2/video.pxd b/src_c/cython/pygame/_sdl2/video.pxd index bedfb8b967..8d3d868286 100644 --- a/src_c/cython/pygame/_sdl2/video.pxd +++ b/src_c/cython/pygame/_sdl2/video.pxd @@ -90,7 +90,7 @@ cdef extern from "SDL.h" nogil: SDL_FPoint position SDL_Color color SDL_FPoint tex_coord - + ctypedef enum SDL_ScaleMode "_pgsdlScaleMode": SDL_ScaleModeNearest, SDL_ScaleModeLinear, @@ -151,8 +151,8 @@ cdef extern from "SDL.h" nogil: # https://wiki.libsdl.org/SDL_RenderCopyExF # https://wiki.libsdl.org/SDL_RenderPresent int SDL_GetRenderDrawColor(SDL_Renderer* renderer, - Uint8* r, - Uint8* g, + Uint8* r, + Uint8* g, Uint8* b, Uint8* a) int SDL_SetRenderDrawColor(SDL_Renderer* renderer, @@ -227,7 +227,7 @@ cdef extern from "SDL.h" nogil: SDL_BlendFactor srcAlphaFactor, SDL_BlendFactor dstAlphaFactor, SDL_BlendOperation alphaOperation) - + ctypedef enum SDL_BlendOperation: SDL_BLENDOPERATION_ADD = 0x00000001, SDL_BLENDOPERATION_SUBTRACT = 0x00000002, @@ -370,7 +370,7 @@ cdef extern from "SDL.h" nogil: # https://wiki.libsdl.org/SDL_RenderGetIntegerScale int SDL_RenderSetScale(SDL_Renderer* renderer, float scaleX, - float scaleY) + float scaleY) void SDL_RenderGetScale(SDL_Renderer* renderer, float* scaleX, float* scaleY) @@ -382,7 +382,7 @@ cdef extern from "SDL.h" nogil: int* h) int SDL_RenderGetIntegerScale(SDL_Renderer* renderer) - int SDL_VERSION_ATLEAST(int major, int minor, int patch) + int SDL_VERSION_ATLEAST(int major, int minor, int patch) # https://wiki.libsdl.org/SDL_GetWindowPixelFormat # https://wiki.libsdl.org/SDL_IntersectRect @@ -414,7 +414,7 @@ cdef extern from "pygame.h" nogil: ctypedef class pygame.color.Color [object pgColorObject]: cdef Uint8 data[4] cdef Uint8 len - + ctypedef enum pgColorHandleFlags: PG_COLOR_HANDLE_SIMPLE PG_COLOR_HANDLE_STR @@ -425,7 +425,7 @@ cdef extern from "pygame.h" nogil: ctypedef class pygame.rect.Rect [object pgRectObject]: cdef SDL_Rect r cdef object weakreflist - + ctypedef class pygame.window.Window [object pgWindowObject]: cdef SDL_Window *_win cdef SDL_bool _is_borrowed diff --git a/src_c/cython/pygame/_sdl2/video.pyx b/src_c/cython/pygame/_sdl2/video.pyx index 0dd2308b84..af8ea28e1e 100644 --- a/src_c/cython/pygame/_sdl2/video.pyx +++ b/src_c/cython/pygame/_sdl2/video.pyx @@ -167,7 +167,7 @@ cdef Uint32 format_from_depth(int depth): Rmask, Gmask, Bmask, Amask) -# disable auto_pickle since it causes stubcheck error +# disable auto_pickle since it causes stubcheck error @cython.auto_pickle(False) cdef class Texture: @@ -320,7 +320,7 @@ cdef class Texture: """Get or set the blend mode for texture drawing operations Gets or sets the blend mode for the texture's drawing operations. - Valid blend modes are any of the ``BLENDMODE_*`` constants or a custom one. + Valid blend modes are any of the ``BLENDMODE_*`` constants or a custom one. """ # https://wiki.libsdl.org/SDL_GetTextureBlendMode cdef SDL_BlendMode blendMode @@ -342,13 +342,13 @@ cdef class Texture: """Get or set the additional color value multiplied into texture drawing operations """ cdef Uint8[4] rgba - + # https://wiki.libsdl.org/SDL_GetTextureColorMod cdef int res = SDL_GetTextureColorMod(self._tex, &(rgba[0]), &(rgba[1]), &(rgba[2])) - rgba[3] = 255 + rgba[3] = 255 if res < 0: raise error() @@ -570,7 +570,7 @@ cdef class Texture: if rectptr == NULL and area is not None: raise TypeError('area must be a rectangle or None') - + cdef int dst_width, dst_height if rectptr == NULL: dst_width = self.width @@ -578,7 +578,7 @@ cdef class Texture: else: dst_width = rect.w dst_height = rect.h - + if dst_height > surf.h or dst_width > surf.w: # if the surface is smaller than the destination rect, # clip the rect to prevent segfault @@ -619,8 +619,8 @@ cdef class Texture: if res < 0: raise error() -# disable auto_pickle since it causes stubcheck error -@cython.auto_pickle(False) +# disable auto_pickle since it causes stubcheck error +@cython.auto_pickle(False) cdef class Image: def __cinit__(self): @@ -745,8 +745,8 @@ cdef class Image: self.flip_x, self.flip_y) -# disable auto_pickle since it causes stubcheck error -@cython.auto_pickle(False) +# disable auto_pickle since it causes stubcheck error +@cython.auto_pickle(False) cdef class Renderer: @classmethod @@ -786,7 +786,7 @@ cdef class Renderer: the refresh rate. :param bool target_texture: Whether the renderer should support setting :class:`Texture` objects as target textures, to - enable drawing onto them. + enable drawing onto them. :class:`Renderer` objects provide a cross-platform API for rendering 2D @@ -800,7 +800,7 @@ cdef class Renderer: If configured correctly and supported by an underlying rendering driver, Renderer objects can have a :class:`Texture` object temporarily set as a target texture (the Texture object must have been created with target texture usage support), - which allows those textures to be drawn onto. + which allows those textures to be drawn onto. To present drawn content onto the window, :meth:`Renderer.present` should be called. :meth:`Renderer.clear` should be called to clear any drawn content @@ -920,7 +920,7 @@ cdef class Renderer: :param area: A :class:`pygame.Rect` or tuple representing the drawing area on the target, or ``None`` to use the - entire area of the current rendering target. + entire area of the current rendering target. """ # https://wiki.libsdl.org/SDL_RenderSetViewport if area is None: @@ -1078,7 +1078,7 @@ cdef class Renderer: cdef SDL_FRect *frectptr cdef int res - + frectptr = pgFRect_FromObject(rect, &_frect) if frectptr == NULL: raise TypeError('expected a rectangle') @@ -1105,7 +1105,7 @@ cdef class Renderer: # https://wiki.libsdl.org/SDL_RenderGeometry if not SDL_VERSION_ATLEAST(2, 0, 18): raise error("fill_triangle requires SDL 2.0.18 or newer") - + cdef Uint8[4] rgba cdef int res = SDL_GetRenderDrawColor(self._renderer, @@ -1146,7 +1146,7 @@ cdef class Renderer: # https://wiki.libsdl.org/SDL_RenderGeometry if not SDL_VERSION_ATLEAST(2, 0, 18): raise error("fill_quad requires SDL 2.0.18 or newer") - + cdef Uint8[4] rgba cdef int res = SDL_GetRenderDrawColor(self._renderer, diff --git a/src_c/system.c b/src_c/system.c index 7ba35a04d4..7d715821ad 100644 --- a/src_c/system.c +++ b/src_c/system.c @@ -207,9 +207,9 @@ pg_system_get_power_state(PyObject *self, PyObject *_null) "battery_seconds", sec_py, "on_battery", PyBool_FromLong(on_battery), "no_battery", PyBool_FromLong(no_battery), - "charging", PyBool_FromLong(charging), + "charging", PyBool_FromLong(charging), "charged", PyBool_FromLong(charged), - "plugged_in", PyBool_FromLong(!on_battery), + "plugged_in", PyBool_FromLong(!on_battery), "has_battery", PyBool_FromLong(on_battery || !no_battery) ); // clang-format on diff --git a/src_py/__briefcase/pygame_ce.py b/src_py/__briefcase/pygame_ce.py index ddd26ddb4a..9a58410587 100644 --- a/src_py/__briefcase/pygame_ce.py +++ b/src_py/__briefcase/pygame_ce.py @@ -24,7 +24,7 @@ def main(): # app's windows to its menu item. # # For association to work, any windows of the app must have WMCLASS property - # set to match the value set in app's desktop file. For pygame_ce, this is + # set to match the value set in app's desktop file. For pygame_ce, this is # set using the SDL_VIDEO_X11_WMCLASS environment variable. # Find the name of the module that was used to start the app diff --git a/test/README.rst b/test/README.rst index d1936616e0..b18872e5e7 100644 --- a/test/README.rst +++ b/test/README.rst @@ -2,7 +2,7 @@ Pygame Unit Tests ***************** The test runner for pygame was developed for these purposes: - + * Per process isolation of test modules * Ability to tag tests for exclusion (interactive tests etc) * Record timings of tests @@ -139,15 +139,14 @@ some convenience functions :: trunk_relative_path(pth) Will return a normalized relative path, relative to the test_module - + eg trunk_relative_path('examples\\data\\alien.jpg') will work on linux - + This is so the test module can be run from anywhere with working paths - eg ../test/color_test.py - + eg ../test/color_test.py + fixture_path(pth) Likewise but paths are relative to trunk\test\fixtures example_path(pth) Likewise but paths are relative to trunk\examples -