Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions doc/builtins.rst
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,20 @@ of transparency:
through a ghost.


On screen or not
''''''''''''''''

There is a simple function to check whether an Actor is visible on the screen:

.. method:: Actor.is_onscreen()

Returns ``True`` if the Actor is currently inside the screen bounds and
``False`` if not.

This can be useful if you have many game objects flying around the screen that
should disappear as soon as they are out of sight.


The Keyboard
------------

Expand Down
5 changes: 5 additions & 0 deletions src/pgzero/actor.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,5 +361,10 @@ def distance_to(self, target):
dy = ty - myy
return sqrt(dx * dx + dy * dy)

def is_onscreen(self):
"""Returns whether the Actor is within the screen bounds or not."""
return not (self.right < 0 or self.left > game.screen.get_width() or
self.bottom < 0 or self.top > game.screen.get_height())

def unload_image(self):
loaders.images.unload(self._image_name)
23 changes: 23 additions & 0 deletions test/test_actor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import unittest
from unittest.mock import patch

import pygame

Expand Down Expand Up @@ -146,3 +147,25 @@ def test_dir_correct(self):
a = Actor("alien")
for attribute in dir(a):
a.__getattr__(attribute)

# Since the tests don't create the proper screen, it must be mocked for
# these test functions.
@patch("pgzero.actor.game.screen.get_height")
@patch("pgzero.actor.game.screen.get_width")
@patch("pgzero.actor.game.screen")
def test_onscreen(self, mock_screen, mock_get_width, mock_get_height):
"""We can check if the Actor is in the screen bounds."""
mock_get_width.return_value = 200
mock_get_height.return_value = 100
a = Actor("alien", (10, 10))
self.assertTrue(a.is_onscreen())

@patch("pgzero.actor.game.screen.get_height")
@patch("pgzero.actor.game.screen.get_width")
@patch("pgzero.actor.game.screen")
def test_not_onscreen(self, mock_screen, mock_get_width, mock_get_height):
"""We can check if the Actor is not within the screen bounds."""
a = Actor("alien", (10, 1000))
mock_get_width.return_value = 200
mock_get_height.return_value = 100
self.assertFalse(a.is_onscreen())