Make creating games with 2D sprites more easy and clean.
Class that represents a moveable 2D image.
Parameters: |
|
---|
The x-coordinate, in pixels, of the center of this sprite.
The y-coordinate, in pixels, of the center of this sprite.
The name of the image to draw, when drawing this sprite.
The width of this Sprite, when drawn.
The height of this Sprite, when drawn.
Moves this Sprite so that it does not overlap with another Sprite.
Parameters: | other_sprite (Sprite) – Another Sprite object. |
---|
Moves this sprite the minimum amount so that it is not overlapping with other_sprite. If there is no overlap, it does nothing.
Returns whether this Sprite is colliding with another Sprite.
Parameters: | other_sprite (Sprite) – Another Sprite object. |
---|---|
Returns: | (bool) – Returns True if this sprite is overlapping with other_sprite and False otherwise. |
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)