From 54e02936d7ce194117493b206f407013c322e538 Mon Sep 17 00:00:00 2001 From: Einar Forselv Date: Thu, 27 Jun 2024 14:58:20 +0200 Subject: [PATCH] Missing type hints --- arcade/application.py | 161 +++++++++++++++++------------- arcade/context.py | 2 +- arcade/draw_commands.py | 64 ++++++------ arcade/easing.py | 12 ++- arcade/gl/vertex_array.py | 32 +++--- arcade/math.py | 20 ++-- arcade/perf_info.py | 4 +- arcade/physics_engines.py | 16 ++- arcade/shape_list.py | 58 +++++------ arcade/sprite/mixins.py | 15 +-- arcade/sprite/sprite.py | 22 ++-- arcade/sprite_list/sprite_list.py | 4 +- arcade/utils.py | 13 ++- 13 files changed, 225 insertions(+), 198 deletions(-) diff --git a/arcade/application.py b/arcade/application.py index 528a490fea..4f1ee0e163 100644 --- a/arcade/application.py +++ b/arcade/application.py @@ -15,6 +15,7 @@ import pyglet.gl as gl import pyglet.window.mouse from pyglet.display.base import ScreenMode +from pyglet.window import MouseCursor import arcade from arcade import get_display_size @@ -121,7 +122,7 @@ def __init__( enable_polling: bool = True, gl_api: str = "gl", draw_rate: float = 1 / 60, - ): + ) -> None: # In certain environments we can't have antialiasing/MSAA enabled. # Detect replit environment if os.environ.get("REPL_ID"): @@ -267,7 +268,7 @@ def clear( color: Optional[RGBOrA255] = None, color_normalized: Optional[RGBANormalized] = None, viewport: Optional[Tuple[int, int, int, int]] = None, - ): + ) -> None: """Clears the window with the configured background color set through :py:attr:`arcade.Window.background_color`. @@ -317,7 +318,7 @@ def background_color(self) -> Color: return self._background_color @background_color.setter - def background_color(self, value: RGBOrA255): + def background_color(self, value: RGBOrA255) -> None: self._background_color = Color.from_iterable(value) @property @@ -334,7 +335,7 @@ def run(self) -> None: """ arcade.run() - def close(self): + def close(self) -> None: """Close the Window.""" super().close() # Make sure we don't reference the window any more @@ -348,7 +349,7 @@ def set_fullscreen( mode: Optional[ScreenMode] = None, width: Optional[float] = None, height: Optional[float] = None, - ): + ) -> None: """ Set if we are full screen or not. @@ -375,23 +376,22 @@ def center_window(self) -> None: # Center the window self.set_location((screen_width - window_width) // 2, (screen_height - window_height) // 2) - def on_update(self, delta_time: float): + def on_update(self, delta_time: float) -> Optional[bool]: """ Move everything. Perform collision checks. Do all the game logic here. :param delta_time: Time interval since the last time the function was called. - """ pass - def _dispatch_updates(self, delta_time: float): + def _dispatch_updates(self, delta_time: float) -> None: """ Internal function that is scheduled with Pyglet's clock, this function gets run by the clock, and dispatches the on_update events. """ self.dispatch_event("on_update", delta_time) - def set_update_rate(self, rate: float): + def set_update_rate(self, rate: float) -> None: """ Set how often the on_update function should be dispatched. For example, self.set_update_rate(1 / 60) will set the update rate to 60 times per second. @@ -402,7 +402,7 @@ def set_update_rate(self, rate: float): pyglet.clock.unschedule(self._dispatch_updates) pyglet.clock.schedule_interval(self._dispatch_updates, rate) - def set_draw_rate(self, rate: float): + def set_draw_rate(self, rate: float) -> None: """ Set how often the on_draw function should be run. For example, set.set_draw_rate(1 / 60) will set the draw rate to 60 frames per second. @@ -411,7 +411,7 @@ def set_draw_rate(self, rate: float): pyglet.clock.unschedule(pyglet.app.event_loop._redraw_windows) pyglet.clock.schedule_interval(pyglet.app.event_loop._redraw_windows, self._draw_rate) - def on_mouse_motion(self, x: int, y: int, dx: int, dy: int): + def on_mouse_motion(self, x: int, y: int, dx: int, dy: int) -> Optional[bool]: """ Called repeatedly while the mouse is moving over the window. @@ -424,7 +424,7 @@ def on_mouse_motion(self, x: int, y: int, dx: int, dy: int): """ pass - def on_mouse_press(self, x: int, y: int, button: int, modifiers: int): + def on_mouse_press(self, x: int, y: int, button: int, modifiers: int) -> Optional[bool]: """ Called once whenever a mouse button gets pressed down. @@ -448,7 +448,9 @@ def on_mouse_press(self, x: int, y: int, button: int, modifiers: int): """ pass - def on_mouse_drag(self, x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int): + def on_mouse_drag( + self, x: int, y: int, dx: int, dy: int, buttons: int, modifiers: int + ) -> Optional[bool]: """ Called repeatedly while the mouse moves with a button down. @@ -462,9 +464,9 @@ def on_mouse_drag(self, x: int, y: int, dx: int, dy: int, buttons: int, modifier :param modifiers: Bitwise 'and' of all modifiers (shift, ctrl, num lock) active during this event. See :ref:`keyboard_modifiers`. """ - self.on_mouse_motion(x, y, dx, dy) + return self.on_mouse_motion(x, y, dx, dy) - def on_mouse_release(self, x: int, y: int, button: int, modifiers: int): + def on_mouse_release(self, x: int, y: int, button: int, modifiers: int) -> Optional[bool]: """ Called once whenever a mouse button gets released. @@ -480,9 +482,9 @@ def on_mouse_release(self, x: int, y: int, button: int, modifiers: int): :param modifiers: Bitwise 'and' of all modifiers (shift, ctrl, num lock) active during this event. See :ref:`keyboard_modifiers`. """ - pass + return False - def on_mouse_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int): + def on_mouse_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> Optional[bool]: """ Called repeatedly while a mouse scroll wheel moves. @@ -511,9 +513,9 @@ def on_mouse_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int): :param scroll_y: number of steps scrolled vertically since the last call of this function """ - pass + return False - def set_mouse_visible(self, visible: bool = True): + def set_mouse_visible(self, visible: bool = True) -> None: """ Set whether to show the system's cursor while over the window @@ -545,10 +547,10 @@ def set_mouse_visible(self, visible: bool = True): """ super().set_mouse_visible(visible) - def on_action(self, action_name: str, state): + def on_action(self, action_name: str, state) -> None: pass - def on_key_press(self, symbol: int, modifiers: int): + def on_key_press(self, symbol: int, modifiers: int) -> Optional[bool]: """ Called once when a key gets pushed down. @@ -568,7 +570,9 @@ def on_key_press(self, symbol: int, modifiers: int): except AttributeError: pass - def on_key_release(self, symbol: int, modifiers: int): + return False + + def on_key_release(self, symbol: int, modifiers: int) -> Optional[bool]: """ Called once when a key gets released. @@ -592,13 +596,15 @@ def on_key_release(self, symbol: int, modifiers: int): except AttributeError: pass - def on_draw(self): + return False + + def on_draw(self) -> Optional[bool]: """ Override this function to add your custom drawing code. """ - pass + return False - def on_resize(self, width: int, height: int): + def on_resize(self, width: int, height: int) -> Optional[bool]: """ Override this function to add custom code to be called any time the window is resized. The main responsibility of this method is updating @@ -621,7 +627,9 @@ def on_resize(self, width: int, height: int): # Retain projection scrolling if applied self.viewport = (0, 0, width, height) - def set_min_size(self, width: int, height: int): + return False + + def set_min_size(self, width: int, height: int) -> None: """Wrap the Pyglet window call to set minimum size :param width: width in pixels. @@ -633,7 +641,7 @@ def set_min_size(self, width: int, height: int): else: raise ValueError("Cannot set min size on non-resizable window") - def set_max_size(self, width: int, height: int): + def set_max_size(self, width: int, height: int) -> None: """Wrap the Pyglet window call to set maximum size :param width: width in pixels. @@ -647,7 +655,7 @@ def set_max_size(self, width: int, height: int): else: raise ValueError("Cannot set max size on non-resizable window") - def set_size(self, width: int, height: int): + def set_size(self, width: int, height: int) -> None: """ Ignore the resizable flag and set the size @@ -683,7 +691,7 @@ def set_visible(self, visible: bool = True): """ super().set_visible(visible) - def use(self): + def use(self) -> None: """Bind the window's framebuffer for rendering commands""" self.ctx.screen.use() @@ -724,7 +732,7 @@ def viewport(self, new_viewport: tuple[int, int, int, int]): else: self._ctx.screen.viewport = new_viewport - def test(self, frames: int = 10): + def test(self, frames: int = 10) -> None: """ Used by unit test cases. Runs the event loop a few times and stops. @@ -744,7 +752,7 @@ def test(self, frames: int = 10): time.sleep(sleep_time) self._dispatch_updates(1 / 60) - def show_view(self, new_view: "View"): + def show_view(self, new_view: "View") -> None: """ Select the view to show in the next frame. This is not a blocking call showing the view. @@ -817,7 +825,7 @@ def show_view(self, new_view: "View"): # will still call the Window's event handlers. (See pyglet's EventDispatcher.dispatch_event() implementation # for details) - def hide_view(self): + def hide_view(self) -> None: """ Hide the currently active view (if any) returning us back to ``on_draw`` and ``on_update`` functions in the window. @@ -835,13 +843,13 @@ def hide_view(self): self.remove_handlers(self._current_view) self._current_view = None - def _create(self): + def _create(self) -> None: super()._create() - def _recreate(self, changes): + def _recreate(self, changes) -> None: super()._recreate(changes) - def flip(self): + def flip(self) -> None: """ Window framebuffers normally have a back and front buffer. This method makes the back buffer visible and hides the front buffer. @@ -864,43 +872,43 @@ def flip(self): super().flip() - def switch_to(self): + def switch_to(self) -> None: """Switch the this window.""" super().switch_to() - def set_caption(self, caption): + def set_caption(self, caption) -> None: """Set the caption for the window.""" super().set_caption(caption) - def set_minimum_size(self, width: int, height: int): + def set_minimum_size(self, width: int, height: int) -> None: """Set smallest window size.""" super().set_minimum_size(width, height) - def set_maximum_size(self, width, height): + def set_maximum_size(self, width, height) -> None: """Set largest window size.""" super().set_maximum_size(width, height) - def set_location(self, x, y): + def set_location(self, x, y) -> None: """Set location of the window.""" super().set_location(x, y) - def activate(self): + def activate(self) -> None: """Activate this window.""" super().activate() - def minimize(self): + def minimize(self) -> None: """Minimize the window.""" super().minimize() - def maximize(self): + def maximize(self) -> None: """Maximize the window.""" super().maximize() - def set_vsync(self, vsync: bool): + def set_vsync(self, vsync: bool) -> None: """Set if we sync our draws to the monitors vertical sync rate.""" super().set_vsync(vsync) - def set_mouse_platform_visible(self, platform_visible=None): + def set_mouse_platform_visible(self, platform_visible=None) -> None: """ .. warning:: You are probably looking for :meth:`~.Window.set_mouse_visible`! @@ -915,23 +923,23 @@ def set_mouse_platform_visible(self, platform_visible=None): """ super().set_mouse_platform_visible(platform_visible) - def set_exclusive_mouse(self, exclusive=True): + def set_exclusive_mouse(self, exclusive=True) -> None: """Capture the mouse.""" super().set_exclusive_mouse(exclusive) - def set_exclusive_keyboard(self, exclusive=True): + def set_exclusive_keyboard(self, exclusive=True) -> None: """Capture all keyboard input.""" super().set_exclusive_keyboard(exclusive) - def get_system_mouse_cursor(self, name): + def get_system_mouse_cursor(self, name) -> MouseCursor: """Get the system mouse cursor""" return super().get_system_mouse_cursor(name) - def dispatch_events(self): + def dispatch_events(self) -> None: """Dispatch events""" super().dispatch_events() - def on_mouse_enter(self, x: int, y: int): + def on_mouse_enter(self, x: int, y: int) -> Optional[bool]: """ Called once whenever the mouse enters the window area on screen. @@ -943,7 +951,7 @@ def on_mouse_enter(self, x: int, y: int): """ pass - def on_mouse_leave(self, x: int, y: int): + def on_mouse_leave(self, x: int, y: int) -> Optional[bool]: """ Called once whenever the mouse leaves the window area on screen. @@ -1005,8 +1013,7 @@ class View: Support different views/screens in a window. """ - def __init__(self, window: Optional[Window] = None): - + def __init__(self, window: Optional[Window] = None) -> None: self.window = arcade.get_window() if window is None else window self.key: Optional[int] = None self._section_manager: Optional[SectionManager] = None @@ -1027,7 +1034,10 @@ def has_sections(self) -> bool: return self.section_manager.has_sections def add_section( - self, section, at_index: Optional[int] = None, at_draw_order: Optional[int] = None + self, + section: arcade.Section, + at_index: Optional[int] = None, + at_draw_order: Optional[int] = None, ) -> None: """ Adds a section to the view Section Manager. @@ -1043,7 +1053,7 @@ def clear( color: Optional[RGBOrA255] = None, color_normalized: Optional[RGBANormalized] = None, viewport: Optional[Tuple[int, int, int, int]] = None, - ): + ) -> None: """Clears the window with the configured background color set through :py:attr:`arcade.Window.background_color`. @@ -1061,19 +1071,19 @@ def clear( """ self.window.clear(color=color, color_normalized=color_normalized, viewport=viewport) - def on_update(self, delta_time: float): + def on_update(self, delta_time: float) -> Optional[bool]: """To be overridden""" pass - def on_draw(self): + def on_draw(self) -> Optional[bool]: """Called when this view should draw""" pass - def on_show(self): + def on_show(self) -> None: """Deprecated. Use :py:meth:`~arcade.View.on_show_view` instead.""" pass - def on_show_view(self): + def on_show_view(self) -> None: """ Called once when the view is shown. @@ -1081,11 +1091,11 @@ def on_show_view(self): """ pass - def on_hide_view(self): + def on_hide_view(self) -> None: """Called once when this view is hidden.""" pass - def on_mouse_motion(self, x: int, y: int, dx: int, dy: int): + def on_mouse_motion(self, x: int, y: int, dx: int, dy: int) -> Optional[bool]: """ Override this function to add mouse functionality. @@ -1096,7 +1106,7 @@ def on_mouse_motion(self, x: int, y: int, dx: int, dy: int): """ pass - def on_mouse_press(self, x: int, y: int, button: int, modifiers: int): + def on_mouse_press(self, x: int, y: int, button: int, modifiers: int) -> Optional[bool]: """ Override this function to add mouse button functionality. @@ -1110,7 +1120,9 @@ def on_mouse_press(self, x: int, y: int, button: int, modifiers: int): """ pass - def on_mouse_drag(self, x: int, y: int, dx: int, dy: int, _buttons: int, _modifiers: int): + def on_mouse_drag( + self, x: int, y: int, dx: int, dy: int, _buttons: int, _modifiers: int + ) -> Optional[bool]: """ Override this function to add mouse button functionality. @@ -1123,8 +1135,9 @@ def on_mouse_drag(self, x: int, y: int, dx: int, dy: int, _buttons: int, _modifi active during this event. See :ref:`keyboard_modifiers`. """ self.on_mouse_motion(x, y, dx, dy) + return False - def on_mouse_release(self, x: int, y: int, button: int, modifiers: int): + def on_mouse_release(self, x: int, y: int, button: int, modifiers: int) -> Optional[bool]: """ Override this function to add mouse button functionality. @@ -1138,18 +1151,18 @@ def on_mouse_release(self, x: int, y: int, button: int, modifiers: int): """ pass - def on_mouse_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int): + def on_mouse_scroll(self, x: int, y: int, scroll_x: int, scroll_y: int) -> Optional[bool]: """ User moves the scroll wheel. :param x: x position of mouse :param y: y position of mouse - :param scroll_x: ammout of x pixels scrolled since last call - :param scroll_y: ammout of y pixels scrolled since last call + :param scroll_x: amount of x pixels scrolled since last call + :param scroll_y: amount of y pixels scrolled since last call """ pass - def on_key_press(self, symbol: int, modifiers: int): + def on_key_press(self, symbol: int, modifiers: int) -> Optional[bool]: """ Override this function to add key press functionality. @@ -1162,7 +1175,9 @@ def on_key_press(self, symbol: int, modifiers: int): except AttributeError: pass - def on_key_release(self, _symbol: int, _modifiers: int): + return False + + def on_key_release(self, _symbol: int, _modifiers: int) -> Optional[bool]: """ Override this function to add key release functionality. @@ -1175,7 +1190,9 @@ def on_key_release(self, _symbol: int, _modifiers: int): except AttributeError: pass - def on_resize(self, width: int, height: int): + return False + + def on_resize(self, width: int, height: int) -> Optional[bool]: """ Called when the window is resized while this view is active. :py:meth:`~arcade.Window.on_resize` is also called separately. @@ -1184,7 +1201,7 @@ def on_resize(self, width: int, height: int): """ pass - def on_mouse_enter(self, x: int, y: int): + def on_mouse_enter(self, x: int, y: int) -> Optional[bool]: """ Called when the mouse was moved into the window. This event will not be triggered if the mouse is currently being @@ -1195,7 +1212,7 @@ def on_mouse_enter(self, x: int, y: int): """ pass - def on_mouse_leave(self, x: int, y: int): + def on_mouse_leave(self, x: int, y: int) -> Optional[bool]: """ Called when the mouse was moved outside of the window. This event will not be triggered if the mouse is currently being diff --git a/arcade/context.py b/arcade/context.py index bb44cd84eb..32d0e1c639 100644 --- a/arcade/context.py +++ b/arcade/context.py @@ -51,7 +51,7 @@ class ArcadeContext(Context): def __init__( self, window: pyglet.window.Window, gc_mode: str = "context_gc", gl_api: str = "gl" - ): + ) -> None: super().__init__(window, gc_mode=gc_mode, gl_api=gl_api) diff --git a/arcade/draw_commands.py b/arcade/draw_commands.py index b3941b49ac..d4e63a1421 100644 --- a/arcade/draw_commands.py +++ b/arcade/draw_commands.py @@ -113,7 +113,7 @@ def draw_arc_filled( end_angle: float, tilt_angle: float = 0, num_segments: int = 128, -): +) -> None: """ Draw a filled in arc. Useful for drawing pie-wedges, or Pac-Man. @@ -164,7 +164,7 @@ def draw_arc_outline( border_width: float = 1, tilt_angle: float = 0, num_segments: int = 128, -): +) -> None: """ Draw the outside edge of an arc. Useful for drawing curved lines. @@ -228,7 +228,7 @@ def draw_parabola_filled( height: float, color: RGBA255, tilt_angle: float = 0, -): +) -> None: """ Draws a filled in parabola. @@ -256,7 +256,7 @@ def draw_parabola_outline( color: RGBA255, border_width: float = 1, tilt_angle: float = 0, -): +) -> None: """ Draws the outline of a parabola. @@ -300,7 +300,7 @@ def draw_circle_filled( color: RGBA255, tilt_angle: float = 0, num_segments: int = -1, -): +) -> None: """ Draw a filled-in circle. @@ -334,7 +334,7 @@ def draw_circle_outline( border_width: float = 1, tilt_angle: float = 0, num_segments: int = -1, -): +) -> None: """ Draw the outline of a circle. @@ -377,7 +377,7 @@ def draw_ellipse_filled( color: RGBA255, tilt_angle: float = 0, num_segments: int = -1, -): +) -> None: """ Draw a filled in ellipse. @@ -425,7 +425,7 @@ def draw_ellipse_outline( border_width: float = 1, tilt_angle: float = 0, num_segments: int = -1, -): +) -> None: """ Draw the outline of an ellipse. @@ -469,7 +469,9 @@ def draw_ellipse_outline( # --- BEGIN LINE FUNCTIONS # # # -def _generic_draw_line_strip(point_list: PointList, color: RGBA255, mode: int = gl.GL_LINE_STRIP): +def _generic_draw_line_strip( + point_list: PointList, color: RGBA255, mode: int = gl.GL_LINE_STRIP +) -> None: """ Draw a line strip. A line strip is a set of continuously connected line segments. @@ -512,7 +514,7 @@ def _generic_draw_line_strip(point_list: PointList, color: RGBA255, mode: int = geometry.render(program, mode=mode) -def draw_line_strip(point_list: PointList, color: RGBA255, line_width: float = 1): +def draw_line_strip(point_list: PointList, color: RGBA255, line_width: float = 1) -> None: """ Draw a multi-point line. @@ -545,7 +547,7 @@ def draw_line( end_y: float, color: RGBA255, line_width: float = 1, -): +) -> None: """ Draw a line. @@ -576,7 +578,7 @@ def draw_line( geometry.render(program, mode=gl.GL_LINES, vertices=2) -def draw_lines(point_list: PointList, color: RGBA255, line_width: float = 1): +def draw_lines(point_list: PointList, color: RGBA255, line_width: float = 1) -> None: """ Draw a set of lines. @@ -619,7 +621,7 @@ def draw_lines(point_list: PointList, color: RGBA255, line_width: float = 1): # --- BEGIN POINT FUNCTIONS # # # -def draw_point(x: float, y: float, color: RGBA255, size: float): +def draw_point(x: float, y: float, color: RGBA255, size: float) -> None: """ Draw a point. @@ -632,7 +634,7 @@ def draw_point(x: float, y: float, color: RGBA255, size: float): draw_rect_filled(XYWH(x, y, size, size), color) -def draw_points(point_list: PointList, color: RGBA255, size: float = 1): +def draw_points(point_list: PointList, color: RGBA255, size: float = 1) -> None: """ Draw a set of points. @@ -675,7 +677,7 @@ def draw_points(point_list: PointList, color: RGBA255, size: float = 1): # --- BEGIN POLYGON FUNCTIONS # # # -def draw_polygon_filled(point_list: Point2List, color: RGBA255): +def draw_polygon_filled(point_list: Point2List, color: RGBA255) -> None: """ Draw a polygon that is filled in. @@ -688,7 +690,7 @@ def draw_polygon_filled(point_list: Point2List, color: RGBA255): _generic_draw_line_strip(flattened_list, color, gl.GL_TRIANGLES) -def draw_polygon_outline(point_list: Point2List, color: RGBA255, line_width: float = 1): +def draw_polygon_outline(point_list: Point2List, color: RGBA255, line_width: float = 1) -> None: """ Draw a polygon outline. Also known as a "line loop." @@ -728,7 +730,7 @@ def draw_polygon_outline(point_list: Point2List, color: RGBA255, line_width: flo def draw_triangle_filled( x1: float, y1: float, x2: float, y2: float, x3: float, y3: float, color: RGBA255 -): +) -> None: """ Draw a filled in triangle. @@ -758,7 +760,7 @@ def draw_triangle_outline( y3: float, color: RGBA255, border_width: float = 1, -): +) -> None: """ Draw a the outline of a triangle. @@ -793,7 +795,7 @@ def draw_lrbt_rectangle_outline( top: float, color: RGBA255, border_width: float = 1, -): +) -> None: """ Draw a rectangle by specifying left, right, bottom and top edges. @@ -822,7 +824,7 @@ def draw_lbwh_rectangle_outline( height: float, color: RGBA255, border_width: float = 1, -): +) -> None: """ Draw a rectangle extending from bottom left to top right @@ -840,7 +842,7 @@ def draw_lbwh_rectangle_outline( def draw_lrbt_rectangle_filled( left: float, right: float, bottom: float, top: float, color: RGBA255 -): +) -> None: """ Draw a rectangle by specifying left, right, bottom and top edges. @@ -866,7 +868,7 @@ def draw_lrbt_rectangle_filled( def draw_lbwh_rectangle_filled( left: float, bottom: float, width: float, height: float, color: RGBA255 -): +) -> None: """ Draw a filled rectangle extending from bottom left to top right @@ -888,7 +890,7 @@ def draw_scaled_texture_rectangle( scale: float = 1.0, angle: float = 0, alpha: int = 255, -): +) -> None: """ Draw a textured rectangle on-screen. @@ -926,7 +928,7 @@ def draw_texture_rectangle( texture: Texture, angle: float = 0, alpha: int = 255, -): +) -> None: """ Draw a textured rectangle on-screen. @@ -949,7 +951,7 @@ def draw_lbwh_rectangle_textured( texture: Texture, angle: float = 0, alpha: int = 255, -): +) -> None: """ Draw a texture extending from bottom left to top right. @@ -970,7 +972,9 @@ def draw_lbwh_rectangle_textured( # Reference implementations: drawing of new Rect -def draw_rect_outline(rect: Rect, color: RGBA255, border_width: float = 1, tilt_angle: float = 0): +def draw_rect_outline( + rect: Rect, color: RGBA255, border_width: float = 1, tilt_angle: float = 0 +) -> None: """ Draw a rectangle outline. @@ -1007,7 +1011,7 @@ def draw_rect_outline(rect: Rect, color: RGBA255, border_width: float = 1, tilt_ _generic_draw_line_strip(point_list, color, gl.GL_TRIANGLE_STRIP) -def draw_rect_filled(rect: Rect, color: RGBA255, tilt_angle: float = 0): +def draw_rect_filled(rect: Rect, color: RGBA255, tilt_angle: float = 0) -> None: """ Draw a filled-in rectangle. @@ -1038,12 +1042,14 @@ def draw_rect_filled(rect: Rect, color: RGBA255, tilt_angle: float = 0): def draw_rect_outline_kwargs( color: RGBA255 = WHITE, border_width: int = 1, tilt_angle: float = 0, **kwargs: AsFloat -): +) -> None: rect = Rect.from_kwargs(**kwargs) draw_rect_outline(rect, color, border_width, tilt_angle) -def draw_rect_filled_kwargs(color: RGBA255 = WHITE, tilt_angle: float = 0, **kwargs: AsFloat): +def draw_rect_filled_kwargs( + color: RGBA255 = WHITE, tilt_angle: float = 0, **kwargs: AsFloat +) -> None: rect = Rect.from_kwargs(**kwargs) draw_rect_filled(rect, color, tilt_angle) diff --git a/arcade/easing.py b/arcade/easing.py index 54c0488090..2ea77cdeaa 100644 --- a/arcade/easing.py +++ b/arcade/easing.py @@ -23,7 +23,7 @@ class EasingData: end_value: float ease_function: Callable - def reset(self): + def reset(self) -> None: self.cur_period = self.start_period @@ -211,7 +211,9 @@ def ease_angle_update(easing_data: EasingData, delta_time: float) -> Tuple: return done, angle -def ease_value(start_value: float, end_value: float, *, time=None, rate=None, ease_function=linear): +def ease_value( + start_value: float, end_value: float, *, time=None, rate=None, ease_function=linear +) -> EasingData: """ Get an easing value """ @@ -233,7 +235,9 @@ def ease_value(start_value: float, end_value: float, *, time=None, rate=None, ea return easing_data -def ease_position(start_position, end_position, *, time=None, rate=None, ease_function=linear): +def ease_position( + start_position, end_position, *, time=None, rate=None, ease_function=linear +) -> Tuple[EasingData, EasingData]: """ Get an easing position """ @@ -252,7 +256,7 @@ def ease_position(start_position, end_position, *, time=None, rate=None, ease_fu return easing_data_x, easing_data_y -def ease_update(easing_data: EasingData, delta_time: float) -> Tuple: +def ease_update(easing_data: EasingData, delta_time: float) -> Tuple[bool, float]: """ Update easing between two values/ """ diff --git a/arcade/gl/vertex_array.py b/arcade/gl/vertex_array.py index 8149c4645b..4a8381b00b 100644 --- a/arcade/gl/vertex_array.py +++ b/arcade/gl/vertex_array.py @@ -10,7 +10,7 @@ from .types import BufferDescription, GLenumLike, GLuintLike, gl_name from .program import Program -if TYPE_CHECKING: # handle import cycle caused by type hinting +if TYPE_CHECKING: from arcade.gl import Context # Index buffer types based on index element size @@ -52,7 +52,7 @@ def __init__( content: Sequence[BufferDescription], index_buffer: Optional[Buffer] = None, index_element_size: int = 4, - ): + ) -> None: self._ctx = ctx self._program = program self._content = content @@ -70,10 +70,10 @@ def __init__( self.ctx.stats.incr("vertex_array") - def __repr__(self): + def __repr__(self) -> str: return f"" - def __del__(self): + def __del__(self) -> None: # Intercept garbage collection if we are using Context.gc() if self._ctx.gc_mode == "context_gc" and self.glo.value > 0: self._ctx.objects.append(self) @@ -114,7 +114,7 @@ def num_vertices(self) -> int: """ return self._num_vertices - def delete(self): + def delete(self) -> None: """ Destroy the underlying OpenGL resource. Don't use this unless you know exactly what you are doing. @@ -123,7 +123,7 @@ def delete(self): self.glo.value = 0 @staticmethod - def delete_glo(ctx: "Context", glo: gl.GLuint): + def delete_glo(ctx: "Context", glo: gl.GLuint) -> None: """ Delete this object. This is automatically called when this object is garbage collected. @@ -140,7 +140,7 @@ def delete_glo(ctx: "Context", glo: gl.GLuint): def _build( self, program: Program, content: Sequence[BufferDescription], index_buffer: Optional[Buffer] - ): + ) -> None: """Build a vertex array compatible with the program passed in""" gl.glGenVertexArrays(1, byref(self.glo)) gl.glBindVertexArray(self.glo) @@ -247,7 +247,9 @@ def _build( if buff_descr.instanced: gl.glVertexAttribDivisor(prog_attr.location, 1) - def render(self, mode: GLenumLike, first: int = 0, vertices: int = 0, instances: int = 1): + def render( + self, mode: GLenumLike, first: int = 0, vertices: int = 0, instances: int = 1 + ) -> None: """Render the VertexArray to the currently active framebuffer. :param mode: Primitive type to render. TRIANGLES, LINES etc. @@ -269,7 +271,7 @@ def render(self, mode: GLenumLike, first: int = 0, vertices: int = 0, instances: else: gl.glDrawArraysInstanced(mode, first, vertices, instances) - def render_indirect(self, buffer: Buffer, mode: GLuintLike, count, first, stride): + def render_indirect(self, buffer: Buffer, mode: GLuintLike, count, first, stride) -> None: """ Render the VertexArray to the framebuffer using indirect rendering. @@ -318,7 +320,7 @@ def transform_interleaved( vertices: int = 0, instances: int = 1, buffer_offset=0, - ): + ) -> None: """Run a transform feedback. :param buffer: The buffer to write the output @@ -371,7 +373,7 @@ def transform_separate( vertices: int = 0, instances: int = 1, buffer_offset=0, - ): + ) -> None: """ Run a transform feedback writing to separate buffers. @@ -453,7 +455,7 @@ def __init__( index_buffer: Optional[Buffer] = None, mode: Optional[int] = None, index_element_size: int = 4, - ): + ) -> None: self._ctx = ctx self._content = list(content or []) self._index_buffer = index_buffer @@ -620,7 +622,7 @@ def render_indirect( count: int = -1, first: int = 0, stride: int = 0, - ): + ) -> None: """ Render the VertexArray to the framebuffer using indirect rendering. @@ -682,7 +684,7 @@ def transform( :param program: The Program to render with :param Union[Buffer, Sequence[Buffer]] buffer: The buffer(s) we transform into. This depends on the programs ``varyings_capture_mode``. We can transform - into one buffer interlaved or transform each attribute into separate buffers. + into one buffer interleaved or transform each attribute into separate buffers. :param first: Offset start vertex :param vertices: Number of vertices to render :param instances: Number of instances to render @@ -752,6 +754,6 @@ def _generate_vao(self, program: Program) -> VertexArray: return vao @staticmethod - def _release(ctx): + def _release(ctx) -> None: """Mainly here to count destroyed instances""" ctx.stats.decr("geometry") diff --git a/arcade/math.py b/arcade/math.py index c682c71b45..e2a02766c1 100644 --- a/arcade/math.py +++ b/arcade/math.py @@ -230,43 +230,43 @@ class _Vec2: __slots__ = ["x", "y"] - def __init__(self, x: float, y: float): + def __init__(self, x: float, y: float) -> None: # see if first argument is an iterable with two items self.x: float = x self.y: float = y @staticmethod - def from_polar(angle, radius): + def from_polar(angle, radius) -> _Vec2: rads = math.radians(angle) return _Vec2(radius * math.cos(rads), radius * math.sin(rads)) - def __add__(self, other): + def __add__(self, other) -> _Vec2: return _Vec2(self.x + other.x, self.y + other.y) - def __sub__(self, other): + def __sub__(self, other) -> _Vec2: return _Vec2(self.x - other.x, self.y - other.y) - def __mul__(self, other): + def __mul__(self, other) -> _Vec2: return _Vec2(self.x * other.x, self.y * other.y) - def __truediv__(self, other): + def __truediv__(self, other) -> _Vec2: return _Vec2(self.x / other.x, self.y / other.y) def __iter__(self): yield self.x yield self.y - def length(self): + def length(self) -> float: """return the length (magnitude) of the vector""" return math.sqrt(self.x**2 + self.y**2) - def dot(self, other): + def dot(self, other) -> float: return self.x * other.x + self.y * other.y - def __repr__(self): + def __repr__(self) -> str: return f"Vec2({self.x},{self.y})" - def rotated(self, angle: float): + def rotated(self, angle: float) -> _Vec2: """ Returns the new vector resulting when this vector is rotated by the given angle in degrees diff --git a/arcade/perf_info.py b/arcade/perf_info.py index 1c9bf9176d..083fe0a1e4 100644 --- a/arcade/perf_info.py +++ b/arcade/perf_info.py @@ -27,7 +27,7 @@ ] -def _dispatch_event(self, *args): +def _dispatch_event(self, *args) -> None: """ This function will be monkey-patched over Pyglet's dispatch event function. """ @@ -62,7 +62,7 @@ def _dispatch_event(self, *args): data.popleft() -def print_timings(): +def print_timings() -> None: """ Print event handler statistics to stdout as a table. diff --git a/arcade/physics_engines.py b/arcade/physics_engines.py index 2eb9382881..b36651cd46 100644 --- a/arcade/physics_engines.py +++ b/arcade/physics_engines.py @@ -22,11 +22,9 @@ from arcade.utils import copy_dunders_unimplemented -def _circular_check(player: Sprite, walls: List[SpriteList]): +def _circular_check(player: Sprite, walls: List[SpriteList]) -> None: """ This is a horrible kludge to 'guess' our way out of a collision - Returns: - """ original_x = player.center_x original_y = player.center_y @@ -245,7 +243,7 @@ def __init__( self, player_sprite: Sprite, walls: Optional[Union[SpriteList, Iterable[SpriteList]]] = None, - ): + ) -> None: self.player_sprite: Sprite = player_sprite self._walls: List[SpriteList] @@ -309,7 +307,7 @@ def __init__( gravity_constant: float = 0.5, ladders: Optional[Union[SpriteList, Iterable[SpriteList]]] = None, walls: Optional[Union[SpriteList, Iterable[SpriteList]]] = None, - ): + ) -> None: self._ladders: Optional[List[SpriteList]] self._platforms: List[SpriteList] self._walls: List[SpriteList] @@ -384,7 +382,7 @@ def walls(self, walls: Optional[Union[SpriteList, Iterable[SpriteList]]] = None) def walls(self): self._walls = [] - def is_on_ladder(self): + def is_on_ladder(self) -> bool: """Return 'true' if the player is in contact with a sprite in the ladder list.""" # Check for touching a ladder if self.ladders: @@ -422,7 +420,7 @@ def can_jump(self, y_distance: float = 5) -> bool: else: return False - def enable_multi_jump(self, allowed_jumps: int): + def enable_multi_jump(self, allowed_jumps: int) -> None: """ Enables multi-jump. allowed_jumps should include the initial jump. @@ -436,7 +434,7 @@ def enable_multi_jump(self, allowed_jumps: int): self.allowed_jumps = allowed_jumps self.allow_multi_jump = True - def disable_multi_jump(self): + def disable_multi_jump(self) -> None: """ Disables multi-jump. @@ -452,7 +450,7 @@ def jump(self, velocity: int): self.player_sprite.change_y = velocity self.increment_jump_counter() - def increment_jump_counter(self): + def increment_jump_counter(self) -> None: """ Updates the jump counter for multi-jump tracking """ diff --git a/arcade/shape_list.py b/arcade/shape_list.py index 2f46d9b298..d79a5517d2 100644 --- a/arcade/shape_list.py +++ b/arcade/shape_list.py @@ -14,6 +14,7 @@ import math from typing import ( Dict, + Set, List, Tuple, Iterable, @@ -30,7 +31,7 @@ from arcade.utils import copy_dunders_unimplemented from arcade import get_window, get_points_for_thick_line -from arcade.gl import BufferDescription +from arcade.gl import Buffer, Geometry, BufferDescription from arcade.gl import Program from arcade import ArcadeContext from arcade.math import rotate_point @@ -84,7 +85,7 @@ def __init__( # vbo: Buffer, mode: int = gl.GL_TRIANGLES, program: Optional[Program] = None, - ): + ) -> None: self.ctx = get_window().ctx self.program = program or self.ctx.line_generic_with_colors_program self.mode = mode @@ -99,10 +100,10 @@ def __init__( self.data = array("f", [c for a in zip(self.points, self.colors) for b in a for c in b]) self.vertices = len(points) - self.geometry = None - self.buffer = None + self.geometry: Optional[Geometry] = None + self.buffer: Optional[Buffer] = None - def _init_geometry(self): + def _init_geometry(self) -> None: # NOTE: When drawing a single shape we're not using an index buffer self.buffer = self.program.ctx.buffer(data=self.data) self.geometry = self.ctx.geometry( @@ -115,7 +116,7 @@ def _init_geometry(self): ] ) - def draw(self): + def draw(self) -> None: """ Draw this shape. Drawing this way isn't as fast as drawing multiple shapes batched together in a ShapeElementList. @@ -123,9 +124,8 @@ def draw(self): if self.geometry is None: self._init_geometry() - self.geometry.render( - self.program, mode=self.mode - ) # pyright: ignore [reportOptionalMemberAccess] + if self.geometry is not None: + self.geometry.render(self.program, mode=self.mode) def create_line( @@ -810,21 +810,21 @@ class ShapeElementList(Generic[TShape]): Adding new shapes is fast, but removing them is slow. """ - def __init__(self): + def __init__(self) -> None: # The context this shape list belongs to self.ctx = get_window().ctx # List of sprites in the sprite list - self.shape_list = [] - self.change_x = 0 - self.change_y = 0 - self._center_x = 0 - self._center_y = 0 - self._angle = 0 + self.shape_list: List[TShape] = [] + self.change_x = 0.0 + self.change_y = 0.0 + self._center_x = 0.0 + self._center_y = 0.0 + self._angle = 0.0 self.program = self.ctx.shape_element_list_program self.batches: Dict[int, _Batch] = OrderedDict() - self.dirties = set() + self.dirties: Set[_Batch] = set() - def append(self, item: TShape): + def append(self, item: TShape) -> None: """ Add a new shape to the list. """ @@ -843,7 +843,7 @@ def append(self, item: TShape): # Mark the group as dirty self.dirties.add(batch) - def remove(self, item: TShape): + def remove(self, item: TShape) -> None: """ Remove a specific shape from the list. """ @@ -894,7 +894,7 @@ def clear(self, position: bool = True, angle: bool = True) -> None: if angle: self.angle = 0 - def move(self, change_x: float, change_y: float): + def move(self, change_x: float, change_y: float) -> None: """ Change the center_x/y of the shape list relative to the current position. @@ -914,7 +914,7 @@ def position(self) -> Tuple[float, float]: return self._center_x, self._center_y @position.setter - def position(self, value: Tuple[float, float]): + def position(self, value: Tuple[float, float]) -> None: self._center_x, self._center_y = value @property @@ -923,7 +923,7 @@ def center_x(self) -> float: return self._center_x @center_x.setter - def center_x(self, value: float): + def center_x(self, value: float) -> None: self._center_x = value @property @@ -932,7 +932,7 @@ def center_y(self) -> float: return self._center_y @center_y.setter - def center_y(self, value: float): + def center_y(self, value: float) -> None: self._center_y = value @property @@ -941,7 +941,7 @@ def angle(self) -> float: return self._angle @angle.setter - def angle(self, value: float): + def angle(self, value: float) -> None: self._angle = value def __len__(self) -> int: @@ -975,7 +975,7 @@ def __init__( ctx: ArcadeContext, program: Program, mode: int, - ): + ) -> None: self.ctx = ctx self.program = program self.mode = mode @@ -1000,22 +1000,22 @@ def __init__( self.elements = 0 # Total elements in the batch self.FLAGS = 0 # Flags to indicate changes - def draw(self): + def draw(self) -> None: """Draw the batch.""" if self.elements == 0: return self.geometry.render(self.program, vertices=self.elements, mode=self.mode) - def append(self, item: TShape): + def append(self, item: TShape) -> None: self.new_items.append(item) self.FLAGS |= self.ADD - def remove(self, item: TShape): + def remove(self, item: TShape) -> None: self.items.remove(item) self.FLAGS |= self.REMOVE - def update(self): + def update(self) -> None: """Update the internals of the batch.""" if self.FLAGS == 0: return diff --git a/arcade/sprite/mixins.py b/arcade/sprite/mixins.py index ef26de207c..bfd05e9eb8 100644 --- a/arcade/sprite/mixins.py +++ b/arcade/sprite/mixins.py @@ -1,4 +1,5 @@ from __future__ import annotations +from typing import Optional, Tuple class PyMunk: @@ -13,19 +14,19 @@ class PyMunk: ) def __init__(self): - self.damping = None - self.gravity = None - self.max_velocity = None - self.max_horizontal_velocity = None - self.max_vertical_velocity = None + self.damping: Optional[float] = None + self.gravity: Optional[Tuple[float, float]] = None + self.max_velocity: Optional[float] = None + self.max_horizontal_velocity: Optional[float] = None + self.max_vertical_velocity: Optional[float] = None class PymunkMixin: - def __init__(self): + def __init__(self) -> None: self.pymunk = PyMunk() self.force = [0.0, 0.0] - def pymunk_moved(self, physics_engine, dx, dy, d_angle): + def pymunk_moved(self, physics_engine, dx: float, dy: float, d_angle: float) -> None: """Called by the pymunk physics engine if this sprite moves.""" pass diff --git a/arcade/sprite/sprite.py b/arcade/sprite/sprite.py index c214f2b6e1..6abb2ee30a 100644 --- a/arcade/sprite/sprite.py +++ b/arcade/sprite/sprite.py @@ -71,7 +71,7 @@ def __init__( center_y: float = 0.0, angle: float = 0.0, **kwargs: Any, - ): + ) -> None: if isinstance(path_or_texture, Texture): _texture = path_or_texture _textures = [_texture] @@ -133,7 +133,7 @@ def angle(self) -> float: return self._angle @angle.setter - def angle(self, new_value: float): + def angle(self, new_value: float) -> None: if new_value == self._angle: return @@ -155,7 +155,7 @@ def radians(self) -> float: return self._angle / 180.0 * math.pi @radians.setter - def radians(self, new_value: float): + def radians(self, new_value: float) -> None: self.angle = new_value * 180.0 / math.pi @property @@ -176,7 +176,7 @@ def velocity(self) -> Point2: return self._velocity @velocity.setter - def velocity(self, new_value: Point2): + def velocity(self, new_value: Point2) -> None: self._velocity = new_value @property @@ -185,7 +185,7 @@ def change_x(self) -> float: return self.velocity[0] @change_x.setter - def change_x(self, new_value: float): + def change_x(self, new_value: float) -> None: self._velocity = new_value, self._velocity[1] @property @@ -194,7 +194,7 @@ def change_y(self) -> float: return self.velocity[1] @change_y.setter - def change_y(self, new_value: float): + def change_y(self, new_value: float) -> None: self._velocity = self._velocity[0], new_value @property @@ -205,7 +205,7 @@ def hit_box(self) -> HitBox: return self._hit_box @hit_box.setter - def hit_box(self, hit_box: Union[HitBox, RotatableHitBox]): + def hit_box(self, hit_box: Union[HitBox, RotatableHitBox]) -> None: if type(hit_box) is HitBox: self._hit_box = hit_box.create_rotatable(self.angle) else: @@ -219,7 +219,7 @@ def texture(self) -> Texture: return self._texture @texture.setter - def texture(self, texture: Texture): + def texture(self, texture: Texture) -> None: if texture == self._texture: return @@ -256,7 +256,7 @@ def properties(self) -> Dict[str, Any]: return self._properties @properties.setter - def properties(self, value: Dict[str, Any]): + def properties(self, value: Dict[str, Any]) -> None: self._properties = value # --- Movement methods ----- @@ -373,7 +373,7 @@ def update_spatial_hash(self) -> None: if sprite_list.spatial_hash is not None: sprite_list.spatial_hash.move(self) - def append_texture(self, texture: Texture): + def append_texture(self, texture: Texture) -> None: """ Appends a new texture to the list of textures that can be applied to this sprite. @@ -419,7 +419,7 @@ def register_physics_engine(self, physics_engine: Any) -> None: """ self.physics_engines.append(physics_engine) - def sync_hit_box_to_texture(self): + def sync_hit_box_to_texture(self) -> None: """ Update the sprite's hit box to match the current texture's hit box. """ diff --git a/arcade/sprite_list/sprite_list.py b/arcade/sprite_list/sprite_list.py index d320a88e86..90f2ac3ae0 100644 --- a/arcade/sprite_list/sprite_list.py +++ b/arcade/sprite_list/sprite_list.py @@ -106,7 +106,7 @@ def __init__( capacity: int = 100, lazy: bool = False, visible: bool = True, - ): + ) -> None: self.program: Optional[Program] = None self._atlas: Optional[TextureAtlas] = atlas self._initialized = False @@ -479,7 +479,7 @@ def buffer_textures(self) -> Buffer: a texture ID. This ID references a texture in the texture atlas assigned to this spritelist. The ID is used to look up texture coordinates in a 32bit floating point texture the - texter atlas provides. This system makes sure we can resize + texture atlas provides. This system makes sure we can resize and rebuild a texture atlas without having to rebuild every single spritelist. diff --git a/arcade/utils.py b/arcade/utils.py index 244dba4acf..ecb3dd2ff6 100644 --- a/arcade/utils.py +++ b/arcade/utils.py @@ -46,7 +46,7 @@ class OutsideRangeError(ValueError): :param lower: the lower bound, inclusive, of the range :param upper: the upper bound, inclusive, of the range """ - def __init__(self, var_name: str, value: _CT, lower: _CT, upper: _CT): + def __init__(self, var_name: str, value: _CT, lower: _CT, upper: _CT) -> None: super().__init__(f"{var_name} must be between {lower} and {upper}, inclusive, not {value}") self.var_name = var_name self.value = value @@ -66,7 +66,7 @@ class IntOutsideRangeError(OutsideRangeError): :param lower: the lower bound, inclusive, of the range :param upper: the upper bound, inclusive, of the range """ - def __init__(self, var_name: str, value: int, lower: int, upper: int): + def __init__(self, var_name: str, value: int, lower: int, upper: int) -> None: super().__init__(var_name, value, lower, upper) @@ -79,7 +79,7 @@ class FloatOutsideRangeError(OutsideRangeError): :param lower: the lower bound, inclusive, of the range :param upper: the upper bound, inclusive, of the range """ - def __init__(self, var_name: str, value: float, lower: float, upper: float): + def __init__(self, var_name: str, value: float, lower: float, upper: float) -> None: super().__init__(var_name, value, lower, upper) @@ -90,7 +90,7 @@ class ByteRangeError(IntOutsideRangeError): :param var_name: the name of the variable or argument :param value: the value to fall outside the expected range """ - def __init__(self, var_name: str, value: int): + def __init__(self, var_name: str, value: int) -> None: super().__init__(var_name, value, 0, 255) @@ -108,7 +108,7 @@ class NormalizedRangeError(FloatOutsideRangeError): :param var_name: the name of the variable or argument :param value: the value to fall outside the expected range """ - def __init__(self, var_name: str, value: float): + def __init__(self, var_name: str, value: float) -> None: super().__init__(var_name, value, 0.0, 1.0) @@ -210,8 +210,7 @@ def is_raspberry_pi() -> bool: def get_raspberry_pi_info() -> Tuple[bool, str, str]: """ - Determine if the host is a raspberry pi - with additional info. + Determine if the host is a raspberry pi with additional info. :returns: 3 component tuple. bool (is host a raspi)