Actor

Contents

Actor#

Actors can communicate through messages when this is easier to read than passing object references around.

Combine send_message(...) with @register_message("...") for simple, beginner-friendly event flows between actor classes.

For beginner classes, you can enable world.learning_mode = True. In this mode, common input mistakes are handled more gently where possible (for example list positions are accepted in many Actor position methods).

Useful beginner aliases on Actor include:

  • go_to(...) for move_to(...)

  • move_forward(...) for move(...)

  • face(...) for set_direction(...)

  • turn(...) for turn_right(...)

  • touching(...) and touching_all(...) for detect helpers

API Reference#

class miniworlds.actors.actor.Actor(position=(0, 0), *args, **kwargs)[source]#

Interactive object placed in a world.

Actors can move, change costumes, detect collisions, send messages, and react to keyboard, mouse, and lifecycle events.

Examples

Create a basic actor:

    from miniworlds import Actor, World

    world = World(100, 60)
    Actor((10, 10), world=world)
    world.run()

Create an actor with a costume:

    from miniworlds import Actor, World

    world = World(100, 60)
    player = Actor((10, 10), world=world)
    player.add_costume("images/player.png")
    world.run()
actor_count: int = 0#
add_costume(source=None)[source]#

Add a costume to the actor.

Return type:

Costume

Parameters:

source – Image path, color tuple, list of image sources, existing Costume, or None for an empty costume.

Returns:

The new costume.

Examples

player = Actor((20, 20))
player.add_costume("images/player.png")
player.add_costume((255, 255, 0))

idle = player.add_costume("images/idle.png")
run = player.add_costume("images/run.png")
player.switch_costume(run)
add_costumes(sources)[source]#

Add several costumes.

Return type:

Costume

Parameters:

sources – List of image paths, color tuples, or costume sources.

Returns:

The last added costume.

Examples

actor.add_costumes(["images/idle.png", "images/run.png"])
animate(speed=10)[source]#

Animate the current costume.

Parameters:

speed – Frames between animation steps.

Examples

actor.animate(speed=5)
animate_costume(costume, speed=10)[source]#

Animate a specific costume.

Parameters:
  • costume – Costume to animate.

  • speed – Frames between animation steps.

Examples

actor.animate_costume(run_costume, speed=5)
animate_loop(speed=10)[source]#

Animate the current costume in a loop.

Parameters:

speed – Frames between animation steps.

Examples

player.costume.add_images(["images/walk1.png", "images/walk2.png"])
player.animate_loop(speed=8)
before_remove()[source]#

Hook called immediately before the actor is removed from the world.

property border#

Border width of the actor.

A value of 0 means no border.

Notes

You can also configure borders via costume.border or world.default_border.

property border_color#

Border color as RGBA tuple.

Notes

  • Set Actor.border to a value greater than 0 for a visible border.

  • Alias: Actor.stroke_color.

bounce_from_actor(other)[source]#

Reflect movement direction after colliding with another actor.

Parameters:

other – Actor to bounce from.

Examples

other = ball.detect()
if other:
    ball.bounce_from_actor(other)
bounce_from_border(borders)[source]#

Bounce the actor away from world borders.

Return type:

Actor

Parameters:

borders – Border names such as “left” or “top”.

Returns:

The actor itself.

Examples

@ball.register
def act(self):
    self.move()
    borders = self.detect_borders()
    if borders:
        self.bounce_from_border(borders)
property center: Tuple[float, float]#

Center position in world coordinates.

Examples

actor.center = (100, 80)
Type:

tuple[float, float]

property center_x: float#

X-coordinate of the actor center.

Type:

float

property center_y: float#

Y-coordinate of the actor center.

Type:

float

class_image: str = ''#
property class_name: str#

Class name of this actor instance.

property collision_type: str#

Collision strategy used by this actor.

Values:

default: Use the world default. tile: Match actors on the same tile. rect: Check bounding rectangles. static-rect: Check cached bounding rectangles. circle: Check bounding circles. mask: Check overlapping image masks.

Examples

actor.collision_type = "rect"

if actor.detect(wall):
    actor.undo_move()
Type:

str

property color#

Fill color of the actor as RGBA tuple.

Setting this value also enables filling on the costume.

Notes

  • Alias: Actor.color

  • Filling an image costume replaces the visible image content.

property costume: Costume#

Current active costume.

Examples

actor.costume.is_rotatable = False
Type:

Costume

property costume_count: int#

Number of costumes attached to the actor.

Examples

actor.add_costume((255, 0, 0))
print(actor.costume_count)
Type:

int

property costumes: CostumesManager#

Manager containing all actor costumes.

Examples

for costume in actor.costumes:
    costume.border = 1
Type:

CostumesManager

classmethod create_on_world(world)[source]#

Create an actor on a specific world.

Parameters:

world – World to place the actor on.

Returns:

The created actor.

Examples

actor = Actor.create_on_world(world)
detect(*args, **kwargs)[source]#

Return the first detected actor.

Return type:

Optional[Actor]

Parameters:
  • args – Positional arguments forwarded to detect_all().

  • kwargs – Keyword arguments forwarded to detect_all().

Returns:

First matching actor, or None.

Examples

wall = player.detect(Wall)
if wall:
    player.undo_move()

coin = player.detect(Coin)
if coin:
    player.score += 1
    coin.remove()
detect_actor_at(direction=None, distance=0, actors=None)[source]#

Return the first actor at an offset from this actor.

Return type:

Actor

Parameters:
  • direction – Direction to check.

  • distance – Distance from the actor center.

  • actors – Optional actor filter.

Returns:

First matching actor, or None.

Examples

wall = player.detect_actor_at("right", 20, Wall)
if wall:
    player.undo_move()
detect_actor_in_front(actors=None, distance=1)[source]#

Return the first actor directly in front.

Return type:

Actor

Parameters:
  • actors – Optional actor filter.

  • distance – Distance in front of the actor.

Returns:

First matching actor, or None.

Examples

wall = player.detect_actor_in_front(Wall)
if wall:
    player.turn_left()
detect_actors_at(direction=None, distance=0, actors=None)[source]#

Return all actors at an offset from this actor.

Return type:

list

Parameters:
  • direction – Direction to check; omit it to use the actor position.

  • distance – Distance from the actor center.

  • actors – Optional actor filter.

Returns:

List of matching actors.

Examples

@player.register
def on_key_pressed_right(self):
    if not self.detect_actors_at("right", 20, Wall):
        self.move_in_direction("right", 5)
detect_actors_in_front(actors=None, distance=1)[source]#

Return all actors directly in front of this actor.

Return type:

list

Parameters:
  • actors – Optional actor filter.

  • distance – Distance in front of the actor.

Returns:

Matching actors.

Examples

enemies = player.detect_actors_in_front(Enemy)
for enemy in enemies:
    player.move_away(enemy, 3)
detect_all(actors=None, direction=0, distance=0)[source]#

Return all actors detected at an offset from this actor.

Return type:

List[Actor]

Parameters:
  • actors – Optional actor filter; use None for all actors.

  • direction – Direction to check.

  • distance – Distance from the actor center.

Returns:

All matching actors found by the sensor.

Examples

coins = player.detect_all(Coin)
for coin in coins:
    coin.remove()

walls_ahead = player.detect_all(Wall, direction="right", distance=10)
detect_borders(distance=0)[source]#

Return borders detected near the actor.

Return type:

List

Parameters:

distance – Distance in front of the actor to check.

Returns:

List of border names such as “left”, “right”, “top”, or “bottom”.

Examples

@ball.register
def act(self):
    self.move()
    borders = self.detect_borders()
    if borders:
        self.bounce_from_border(borders)
detect_bottom_border()[source]#

Return whether the actor touches the bottom border.

Return type:

bool

Returns:

True if the bottom border is detected.

detect_color(color=None)[source]#

Return whether the actor detects a background color.

Return type:

bool

Parameters:

color – Optional RGB/RGBA color tuple. If omitted, any color is detected.

Returns:

True if the color is detected at the actor center.

Examples

@player.register
def act(self):
    if self.detect_color((0, 0, 0)):
        self.remove()
detect_color_at(direction=None, distance=0)[source]#

Return background colors at an offset from the actor.

Return type:

Union[Tuple, List]

Parameters:
  • direction – Direction to check; omit it to use the actor position.

  • distance – Distance from the actor center.

Returns:

Color or colors found by the sensor.

Examples

color = actor.detect_color_at("right", 5)
detect_left_border()[source]#

Return whether the actor touches the left border.

Return type:

bool

Returns:

True if the left border is detected.

detect_pixel(position)[source]#

Return whether the actor overlaps a screen pixel.

Return type:

bool

Parameters:

position – Pixel position as (x, y).

Returns:

True if the actor overlaps the pixel.

Examples

@actor.register
def on_mouse_left(self, position):
    if self.detect_pixel(position):
        self.hide()
detect_point(position)[source]#

Return whether the actor overlaps a world point.

Return type:

bool

Parameters:

position – World position as (x, y).

Returns:

True if the actor overlaps the point.

Examples

if actor.detect_point((100, 80)):
    actor.hide()
detect_rect(rect)[source]#

Return whether the actor overlaps a rectangle.

Parameters:

rect – Rectangle as (x, y, width, height) or pygame.Rect.

Returns:

True if the actor overlaps the rectangle.

detect_right_border()[source]#

Return whether the actor touches the right border.

Return type:

bool

Returns:

True if the right border is detected.

detect_top_border()[source]#

Return whether the actor touches the top border.

Return type:

bool

Returns:

True if the top border is detected.

detecting_bottom_border()[source]#

Return whether the actor touches the bottom border.

Return type:

bool

Returns:

True if the bottom border is detected.

detecting_left_border()[source]#

Return whether the actor touches the left border.

Return type:

bool

Returns:

True if the left border is detected.

detecting_right_border()[source]#

Return whether the actor touches the right border.

Return type:

bool

Returns:

True if the right border is detected.

detecting_top_border()[source]#

Return whether the actor touches the top border.

Return type:

bool

Returns:

True if the top border is detected.

property direction: int#

Actor direction in Miniworlds/Scratch convention.

Common values are 0 or “up”, 90 or “right”, -90 or “left”, and 180 or “down”.

Examples

@player.register
def on_key_down(self, key):
    if "left" in key:
        self.direction = "left"
    elif "right" in key:
        self.direction = "right"
    self.move()

actor.direction = 45
actor.move()
Type:

int

property direction_at_unit_circle: int#

Direction in unit-circle convention.

In this convention, 0 points right and 90 points up.

Examples

actor.direction_at_unit_circle = 0
Type:

int

face(direction)[source]#

Student-friendly alias for set_direction(direction).

fill(value)[source]#

Set fill color for borders and lines

property fill_color#

Fill color of the actor as RGBA tuple.

Setting this value also enables filling on the costume.

Notes

  • Alias: Actor.color

  • Filling an image costume replaces the visible image content.

flip_x()[source]#

Flip the costume horizontally and turn the actor around.

Return type:

int

Returns:

The new actor direction.

Examples

if actor.detect_borders():
    actor.flip_x()
classmethod from_center(center_position, *args, **kwargs)[source]#

Create an actor positioned by its center.

Parameters:

center_position – Center position as (x, y).

Returns:

The created actor.

Examples

actor = Actor.from_center((100, 80))
classmethod from_topleft(topleft_position, *args, **kwargs)[source]#

Create an actor positioned by its top-left corner.

Parameters:

topleft_position – Top-left position as (x, y).

Returns:

The created actor.

Examples

actor = Actor.from_topleft((20, 40))
get_distance_to(obj)[source]#

Gets the distance to another actor or a position

Return type:

float

Parameters:

obj – Actor or Position

Returns:

The distance between actor (measured from actor.center) to actor or position.

Return type:

float

get_local_rect()[source]#

Return actor rect in camera-local coordinates.

Return type:

Rect

go_to(position)[source]#

Student-friendly alias for move_to(position).

has_costume()[source]#

Return True when the actor currently has a costume.

Return type:

bool

property height#

Actor height in pixels.

Examples

actor.height = 60
Type:

float

hide()[source]#

Hides a actor (the actor will be invisible)

property is_blockable#

Whether this actor is stopped by blocking actors.

Examples

player.is_blockable = True
wall.is_blocking = True
Type:

bool

property is_blocking#

Whether this actor blocks blockable actors.

Examples

wall.is_blocking = True
Type:

bool

property is_filled#

Is actor filled with color?

property is_flipped: bool#

Whether the current costume is mirrored horizontally.

Examples

actor.is_flipped = True
Type:

bool

is_inside_world()[source]#

Return whether the actor is completely inside the world.

Returns:

True if the entire actor rectangle is inside the world.

property is_rotatable: bool#

Whether the costume rotates with the actor direction.

The actor direction still changes when this is False; only the rendered costume stays unrotated.

Examples

actor.is_rotatable = False
actor.direction = "right"
Type:

bool

property last_direction: int#

Direction value from the previous frame.

property last_position: Tuple[float, float]#

Actor center from the previous frame.

Examples

if actor.center != actor.last_position:
    print("actor moved")
Type:

tuple[float, float]

property local_center: Tuple[float, float]#

Actor center in camera-local coordinates.

Type:

tuple[float, float]

move(distance=0, direction=None)[source]#

Move the actor.

Parameters:
  • distance – Number of steps to move.

  • direction – Optional direction. If omitted, the current actor direction is used.

Returns:

The moved actor.

Examples

actor.direction = "right"
actor.move(5)
move_away(target, distance=1)[source]#

Move away from a target actor or position.

Parameters:
  • target – Target actor or position.

  • distance – Step size.

Returns:

The moved actor.

Examples

@player.register
def act(self):
    if self.detect(enemy):
        self.move_away(enemy, 3)
move_back(distance)[source]#

Move the actor backward.

Parameters:

distance – Number of steps to move backward.

Returns:

The actor itself.

Examples

actor.move()
if actor.detect(Wall):
    actor.move_back(5)
move_forward(distance=0)[source]#

Student-friendly alias for move(distance).

move_in_direction(direction, distance=1)[source]#

Move in a direction.

direction may be a number, a direction string, or a target position.

Parameters:
  • direction – Direction angle, direction name, or target position.

  • distance – Number of steps to move.

Returns:

The moved actor.

Examples

@player.register
def on_key_pressed(self, key):
    if "right" in key:
        self.move_in_direction("right", 5)
    if "up" in key:
        self.move_in_direction("up", 5)

player.move_in_direction((100, 80), 2)
move_to(position)[source]#

Move the actor to a world position.

Parameters:

position – Target position as (x, y).

Returns:

The moved actor.

Examples

@player.register
def on_clicked_left(self, position):
    self.move_to(position)
move_towards(target, distance=1)[source]#

Move toward a target actor or position.

Parameters:
  • target – Target actor or position.

  • distance – Step size.

Returns:

The moved actor.

Examples

enemy.move_towards(player, 2)
enemy.move_towards((100, 80), 2)
move_vector(vector)[source]#

Move the actor by a vector.

Parameters:

vector – Vector-like movement delta.

Returns:

The moved actor.

Examples

actor.move_vector(Vector(2, 0))
new_costume()[source]#

Create and attach a new empty costume to this actor.

next_costume()[source]#

Switch to the next costume.

Returns:

The new active costume.

Examples

actor.next_costume()
on_clicked_left(position)[source]#

Called when the actor is clicked with the left mouse button.

Parameters:

position – Current mouse position as (x, y).

Examples

@actor.register
def on_clicked_left(self, position):
    self.hide()
on_clicked_right(position)[source]#

Called when the actor is clicked with the right mouse button.

Parameters:

position – Current mouse position as (x, y).

Examples

@actor.register
def on_clicked_right(self, position):
    self.remove()
on_detecting_actor(actor)[source]#

Called when this actor detects another actor.

Parameters:

actor – Detected actor.

Examples

@player.register
def on_detecting_actor(self, actor):
    if isinstance(actor, Coin):
        actor.remove()
on_detecting_borders(borders)[source]#

Called when the actor detects one or more world borders.

Parameters:

borders – Border names, for example [“left”, “top”].

Examples

@player.register
def on_detecting_borders(self, borders):
    self.bounce_from_border(borders)
on_detecting_not_on_world()[source]#

Alias for on_not_detecting_world.

Both names are accepted so older teaching material and newer examples can use the wording that reads best in context.

Examples

@actor.register
def on_detecting_not_on_world(self):
    self.remove()
on_detecting_world()[source]#

Called when the actor is inside the world.

Examples

@player.register
def on_detecting_world(self):
    self.move()
on_key_down(key)[source]#

Called once when a key is pressed.

Register on_key_down_<letter> (for example on_key_down_a) if you want to react to a specific letter only.

For arrow keys use on_key_down_left, on_key_down_right, on_key_down_up, or on_key_down_down.

Parameters:

key – List of key name variants, for example [“A”, “a”] or [“left”].

Examples

@player.register
def on_key_down(self, key):
    if "left" in key:
        self.direction = "left"
    elif "right" in key:
        self.direction = "right"
    self.move()

@player.register
def on_key_down_space(self):
    self.send_message("jump")
on_key_pressed(key)[source]#

Called repeatedly every frame while a key is held down.

This is the right choice for smooth, continuous movement. Like on_key_down, this event supports per-letter handlers such as on_key_pressed_w or on_key_pressed_left.

Parameters:

key – List of key name variants currently held, for example [“W”, “w”] or [“up”].

Examples

@player.register
def on_key_pressed(self, key):
    if "left" in key:
        self.x -= 3
    elif "right" in key:
        self.x += 3
on_key_up(key)[source]#

Called once when a previously pressed key is released.

Parameters:

key – List of key name variants, same format as in on_key_down().

Examples

@player.register
def on_key_up(self, key):
    if "space" in key:
        self.stop_animation()
on_mouse_leave(position)[source]#

Called when the mouse cursor leaves the actor area.

Parameters:

position – The mouse position when it left the actor.

Examples

@actor.register
def on_mouse_leave(self, position):
    self.costume.transparency = 0
on_mouse_left(position)[source]#

Called when the left mouse button is clicked.

The event is triggered for the click itself, independent of whether the click happened on the actor. Use detect_pixel(position) if you only want clicks on the actor body.

Parameters:

position – Current mouse position as (x, y).

on_mouse_left_down(position)[source]#

Called when the left mouse button is pressed down.

Parameters:

position – Current mouse position as (x, y).

on_mouse_left_released(position)[source]#

Called when the left mouse button is released.

Parameters:

position – Current mouse position as (x, y).

Examples

@actor.register
def on_mouse_left_released(self, position):
    self.center = position
on_mouse_motion(position)[source]#

Called when the mouse moves.

The event is triggered for movement events in general. Use detect_pixel(position) if you only want motion over the actor body.

Parameters:

position – Current mouse position as (x, y).

on_mouse_over(position)[source]#

Called when the mouse cursor enters or moves over the actor area.

Parameters:

position – Current mouse position as (x, y).

Examples

@actor.register
def on_mouse_over(self, position):
    self.costume.transparency = 100
on_mouse_right(position)[source]#

Called when the right mouse button is clicked.

Use detect_pixel(position) if you only want clicks on the actor body.

Parameters:

position – Current mouse position as (x, y).

on_mouse_right_down(position)[source]#

Called when the right mouse button is pressed down.

Parameters:

position – Current mouse position as (x, y).

on_mouse_right_released(position)[source]#

Called when the right mouse button is released.

Parameters:

position – Current mouse position as (x, y).

on_not_detecting_world()[source]#

Called when the actor is not touching the world (i.e. outside world bounds).

Useful to remove actors that fly off-screen.

Examples

@rocket.register
def on_not_detecting_world(self):
    self.remove()
on_shape_change()[source]#

Hook called when actor shape-related properties change.

property orientation: float#

Costume orientation offset in degrees.

Examples

actor.orientation = -90
Type:

float

property origin#

Current origin mode used for size and position operations.

point_towards_actor(other)[source]#

Point the actor toward another actor.

Return type:

int

Parameters:

other – Target actor.

Returns:

The new direction.

Examples

enemy.point_towards_actor(player)
point_towards_position(destination)[source]#

Point the actor toward a position.

Return type:

Union[int, float]

Parameters:

destination – Target position as (x, y).

Returns:

The new direction.

Examples

def act(self):
    mouse = self.world.mouse.get_position()
    if mouse:
        self.point_towards_position(mouse)
    self.move()
property position: Tuple[float, float]#

The position of the actor as Position(x, y)

register_sensor(*args, **kwargs)[source]#

This method is used for the @register_sensor decorator.

remove(kill=True)[source]#

Remove this actor from its world.

Return type:

defaultdict

Parameters:

kill – Whether to remove the underlying pygame sprite too.

Returns:

Removed actor data from the world connector.

Examples

coin = actor.detect(Coin)
if coin:
    coin.remove()
remove_costume(source=None)[source]#

Remove a costume.

Parameters:

source – Costume index or costume object. If omitted, the current costume is removed.

Examples

actor.remove_costume()
actor.remove_costume(0)
reset_costumes()[source]#

Remove all costumes and reset appearance state.

scale_height(value)[source]#

Scale actor height by a factor.

Parameters:

value – Scale factor.

Examples

actor.scale_height(0.5)
scale_width(value)[source]#

Scale actor width by a factor.

Parameters:

value – Scale factor.

Examples

actor.scale_width(1.5)
send_message(message)[source]#

Send a message through the world event system.

Parameters:

message – Message name.

Examples

player.send_message("hit")

@enemy.register
def on_message(self, message):
    if message == "hit":
        self.remove()
set_background_color(color)[source]#

Set a background color behind the actor costume image.

set_costume(costume)[source]#

Set the current costume from an index, source, or appearance object.

set_direction(direction)[source]#

Point the actor in a direction.

Return type:

float

Parameters:

direction – Direction as an angle or string such as “up”, “right”, “down”, or “left”.

Returns:

The new direction.

Examples

actor.set_direction("left")
actor.set_direction(45)
set_position(value)[source]#

Set actor position in world coordinates.

set_size(value)[source]#

Set actor size.

Parameters:

value – Size as (width, height) or a scalar size.

Examples

actor.set_size((40, 30))
set_world(new_world)[source]#

Move the actor to another world and return the actor.

Return type:

Actor

show()[source]#

Displays a actor ( an invisible actor will be visible)

property size: tuple#

Actor size as (width, height).

Examples

actor.size = (40, 30)
Type:

tuple[float, float]

property static#

Should actor react to events? You can turn this option off for additional performance boost.

stop_animation()[source]#

Stop the current costume animation.

Examples

actor.animate_loop()
actor.stop_animation()
property stroke_color#

Border color as RGBA tuple.

Notes

  • Set Actor.border to a value greater than 0 for a visible border.

  • Alias: Actor.stroke_color.

switch_costume(source)[source]#

Switch to another costume.

Return type:

Costume

Parameters:

source – Costume index or costume object.

Returns:

The new active costume.

Examples

actor.add_costume("images/idle.png")
actor.add_costume("images/run.png")
actor.switch_costume(1)
switch_origin(value)[source]#

Switch the actor origin while preserving its screen position.

Parameters:

value“center” or “topleft”.

Examples

actor.switch_origin("center")
property topleft: Tuple[float, float]#

Top-left position in world coordinates.

Examples

actor.topleft = (10, 20)
Type:

tuple[float, float]

property topleft_x: float#

X-coordinate of the actor’s top-left corner.

Type:

float

property topleft_y: float#

Y-coordinate of the actor’s top-left corner.

Type:

float

touching(*args, **kwargs)[source]#

Student-friendly alias for detect(…).

touching_all(*args, **kwargs)[source]#

Student-friendly alias for detect_all(…).

turn(degrees=90)[source]#

Student-friendly alias for turn_right(degrees).

turn_left(degrees=90)[source]#

Turn the actor left.

Return type:

int

Parameters:

degrees – Degrees to turn.

Returns:

The new direction.

Examples

actor.turn_left()
actor.turn_left(45)
turn_right(degrees=90)[source]#

Turn the actor right.

Parameters:

degrees – Degrees to turn.

Returns:

The new direction.

Examples

actor.turn_right()
actor.turn_right(45)
undo_move()[source]#

Undo the last move.

Returns:

The moved actor.

Examples

def on_detecting_wall(self, wall):
    self.undo_move()
property width#

Actor width in pixels.

Examples

actor.width = 80
Type:

float

property world#

World this actor belongs to.

property x: float#

Actor x-position.

Type:

float

property y: float#

Actor y-position.

Type:

float