Sprite ======== .. automodule:: sprite .. autoclass:: sprite.Sprite Attributes ---------- .. autoinstanceattribute:: sprite.Sprite.x :annotation: .. autoinstanceattribute:: sprite.Sprite.y :annotation: .. autoinstanceattribute:: sprite.Sprite.image_name :annotation: Read-only Attributes -------------------- .. autoinstanceattribute:: sprite.Sprite.width :annotation: .. autoinstanceattribute:: sprite.Sprite.height :annotation: Methods ------- .. automethod:: sprite.Sprite.uncollide .. automethod:: sprite.Sprite.collides Examples -------- Here is an example of animating using the sprite module:: import graphics import sprite import random NUMBER_OF_BALLS = 700 WINDOW_WIDTH = 640 WINDOW_HEIGHT = 480 BALL_IMAGE = "ball.gif" BALL_WIDTH, BALL_HEIGHT = graphics.image_size(BALL_IMAGE) BALL_RADIUS = BALL_WIDTH / 2 MAX_Y = WINDOW_HEIGHT - BALL_RADIUS MAX_X = WINDOW_WIDTH - BALL_RADIUS MIN_Y = BALL_RADIUS MIN_X = BALL_RADIUS MIN_DELTA_X = -10 MAX_DELTA_X = 10 MIN_DELTA_Y = -10 MAX_DELTA_Y = 10 # Returns a sprite at a random location def init_sprite(): ball_x = random.randint(MIN_X, MAX_X) ball_y = random.randint(MIN_Y, MAX_Y) ball_delta_x = random.randint(MIN_DELTA_X, MAX_DELTA_X) ball_delta_y = random.randint(MIN_DELTA_Y, MAX_DELTA_Y) ball_sprite = sprite.Sprite(ball_x, ball_y, BALL_IMAGE) ball_sprite.velocity_x = ball_delta_x ball_sprite.velocity_y = ball_delta_y return ball_sprite # Update the location of the sprite so that bounces around the screen def update_sprite(ball_sprite): ball_sprite.x += ball_sprite.velocity_x ball_sprite.y += ball_sprite.velocity_y if ball_sprite.x > WINDOW_WIDTH - BALL_RADIUS: ball_sprite.velocity_x *= -1 if ball_sprite.x < BALL_RADIUS: ball_sprite.velocity_x *= -1 if ball_sprite.y > WINDOW_HEIGHT - BALL_RADIUS: ball_sprite.velocity_y *= -1 if ball_sprite.y < BALL_RADIUS: ball_sprite.velocity_y *= -1 # Animate many sprites bouncing around the screen def main_loop(): balls = [init_sprite() for _ in range(NUMBER_OF_BALLS)] graphics.window_size(WINDOW_WIDTH, WINDOW_HEIGHT) graphics.window_title("Bouncing Balls") graphics.window_background_color("white") graphics.frame_rate(30) while graphics.window_open(): graphics.clear() for i in range(len(balls)): update_sprite(balls[i]) graphics.draw_sprite(balls[i]) graphics.draw_text("Bouncing", WINDOW_WIDTH // 2, WINDOW_HEIGHT // 2, "blue", 42)