World#

Die Basisklasse für all deine Welten

World#

class miniworlds.worlds.world.World(x=400, y=400)[Quellcode]#

Eine Welt ist ein Spielfeld, auf dem sich Akteure bewegen können.

Eine Welt hat einen Hintergrund und bietet grundlegende Funktionen für die Positionierung von Akteuren und für die Kollisionsdetektion von Akteuren, die über die Sensoren der Akteure abgefragt werden können.

Sie können Ihre eigene Welt erschaffen, indem Sie eine Klasse erstellen, die von World erbt, oder Sie können direkt ein Weltobjekt vom Typ World oder einer seiner Kindklassen (TiledWorld, PhysicsWorld, …) erstellen.

Welt

Eine Welt für pixelgenaue Spiele.

  • Die Position eines Actors in einer Welt ist das Pixel oben links des Actors.

  • Neue Akteure werden erstellt, wobei die obere linke Ecke des Akteursrechtecks an der Position liegt.

  • Zwei Actor kollidieren, wenn sich ihre Sprites überlappen.

Asteroiden

Andere Welten:

  • TiledWorld: For worlds using Tiles, like rogue-like rpgs, see TiledWorld)

  • PhysicsWorld: For worlds using the PhysicsEngine, see PhysicsWorld)

Beispiele

Erstellen eines TiledWorld-Objekts:

from miniworlds import *

my_world = TiledWorld()
my_world.columns = 30
my_world.rows = 20
my_world.tile_size = 20

Erstellen einer TiledWorld-Unterklasse.

import miniworlds

class MyWorld(miniworlds.TiledWorld):

    def on_setup(self):
        self.columns = 30
        self.rows = 20
        self.tile_size = 20

Erstellen eines Weltobjekts:

from miniworlds import *

my_world = World()
my_world.columns = 300
my_world.rows = 200

Erstellen einer Weltunterklasse

import miniworlds

class MyWorld(miniworlds.World):

    def on_setup(self):
        self.columns = 300
        self.rows = 200

Siehe auch

Parameter:
  • view_x – Spalten der neuen Welt (Standard: 40)

  • view_y – Zeilen der neuen Welt (Standard:40)

  • tile_size – Größe der Kacheln (1 für normale Welten, kann für Tiled-Welten abweichen)

Öffentliche Datenattribute:

subclasses

tick_rate

Tick rate defines how often the method act() will be called.

fps

Bilder pro Sekunde auf dem Bildschirm angezeigt.

world_size_x

Gets the horizontal size of the world in pixels.

world_size_y

Gets the vertical size of the world in pixels.

columns

Gets the number of horizontal pixels (columns) visible in the world.

rows

Gets the number of vertical pixels (rows) visible in the world.

size

Gets the world size as a tuple (width, height), in pixels.

background

Returns the currently active background.

has_background

Returns True if the world has at least one background appearance.

actors

event_manager

clock

frame

is_running

actors_fixed_size

app

backgrounds

layout

data

mouse

draw

music

sound

Inherited from WorldBase

window

:py:obj:Größe <miniworlds.worlds.world_base.WorldBase.size>\

topleft

width

height

class_name

registered_events

Returns the set of all event names that are currently registered.

Öffentliche Methoden:

__init__([x, y])

contains_position(pos)

Prüft, ob die Position in der Welt ist.

contains_rect(rect)

Returns True if the entire rectangle is fully inside the world.

contains_rect_any(rect)

Returns True if any part of the rectangle is inside the world.

set_columns(value)

Internal method to set columns and sync world width.

set_rows(value)

Internal method to set rows and sync world height.

get_background()

Returns the current active background from the backgrounds manager.

switch_background(background)

Switches the current background to a specified one.

remove_background([background])

Removes a background from the world.

set_background(source)

Sets a new background and replaces the current active background.

add_background(source)

Adds a new background to the world and sets it as the active one.

start()

Starts or resumes the world.

stop([frames])

Stops the world immediately or after a delay in frames.

run([fullscreen, fit_desktop, replit, ...])

Starts the main application loop of the Miniworlds engine.

is_in_world(position)

Checks whether a given world position lies within the world's boundaries.

:py:obj:send_message <miniworlds.worlds.world.World.send_message>\ (Nachricht[, data])

Sends a broadcast message to the world and all actors.

quit([exit_code])

Immediately quits the application and closes the game window.

reset()

Setzt die Welt zurück Erstellt eine neue Welt mit der Init-Funktion - erstellt alle Akteure und Akteure in der Welt neu.

get_from_pixel(position)

Converts a screen pixel position into a valid world position if inside bounds.

to_pixel(position)

Converts a world position to a screen pixel position.

on_setup()

Hook method to define initial setup logic when the world is created.

detect_actors(position)

Gets all actors which are found at a specific position (in global world coordinates)

get_actors_from_pixel(pixel)

Returns a list of all actors located at the given screen pixel position.

distance_to(pos1, pos2)

Calculates the Euclidean distance between two positions.

direction_to(pos1, pos2)

Calculates the angle from pos1 to pos2 in degrees.

Inherited from WorldBase

__init__()

:py:obj:remove <miniworlds.worlds.world_base.WorldBase.remove>\ (Akteur)

In Unterklassen implementiert

on_change()

in Unterklassen implementiert

on_new_actor(actor)

on_remove_actor(actor)

get_world_connector(actor)

screenshot([filename])

Saves a screenshot of the current window surface to a file.

get_events()

Prints a list of all events that can be registered in this world.

register(method)

Registers a method as a world event handler.

Private Datenattribute:

_abc_impl

_fps

_step

_key_pressed

_animated

_timed_objects

_dynamic_actors

_registered_methods

_mainloop

_collision_manager

Inherited from WorldBase

_abc_impl

Inherited from ABC

_abc_impl

Private Methoden:

_validate_parameters(x, y)

_clear()

Clears the world's state: event queue, all backgrounds, and all actors.

Inherited from WorldBase

_get_mainloopmanager_class()

_get_camera_manager_class()

_get_world_connector_class()

benötigt von get_world_connector in der Elternklasse

_create_event_manager()

_unregister(method)

Unregisters a previously registered world method.

_start_listening()

Enables input listening for the world.

_stop_listening()

Disables input listening for the world.


add_background(source)[Quellcode]#

Adds a new background to the world and sets it as the active one.

The source can be either a file path (image) or a solid color in RGB(A) format.

Rückgabetyp:

Background

Parameter:

source – Either a path to an image file (e.g. „images/bg.png“) or an RGB/RGBA color tuple (e.g. (0, 0, 255)).

Rückgabe:

The newly created Background object.

Verursacht:

FileNotFoundError – If the image file does not exist.

Example

>>> world.add_background((255, 0, 0))               # red background
>>> world.add_background("images/background.png")  # image background
property background: Background#

Returns the currently active background.

This property delegates to get_background().

Rückgabe:

The currently active Background object.

Example

>>> current = world.background
>>> print(current)
property columns: int#

Gets the number of horizontal pixels (columns) visible in the world.

Rückgabe:

The width of the camera view in pixels.

contains_position(pos)[Quellcode]#

Prüft, ob die Position in der Welt ist.

Rückgabe:

Wahr, wenn die Position in der Welt ist.

contains_rect(rect)[Quellcode]#

Returns True if the entire rectangle is fully inside the world.

Useful when ensuring that an object is completely within bounds.

contains_rect_any(rect)[Quellcode]#

Returns True if any part of the rectangle is inside the world.

Useful when ensuring that an object is completely within bounds.

detect_actors(position)[Quellcode]#

Gets all actors which are found at a specific position (in global world coordinates)

Rückgabetyp:

List[Actor]

Parameter:

position – Position, wo Actor gesucht werden sollten.

Rückgabe:

Eine Liste von Actorn

Beispiele

Alle Akteure an der Mausposition abrufen:

position = world.get_mouse_position()
actors = world.get_actors_by_pixel(position)
direction_to(pos1, pos2)[Quellcode]#

Calculates the angle from pos1 to pos2 in degrees.

Rückgabetyp:

float

Parameter:
  • pos1 – Starting position (x, y)

  • pos2 – Target position (x, y)

Rückgabe:

Angle in degrees between the two points.

Example

>>> world.direction_to((0, 0), (0, 1))
90.0
static distance_to(pos1, pos2)[Quellcode]#

Calculates the Euclidean distance between two positions.

Rückgabetyp:

float

Parameter:
  • pos1 – First position (x, y)

  • pos2 – Second position (x, y)

Rückgabe:

The distance as a float.

Example

>>> World.distance_to((0, 0), (3, 4))
5.0
property fps: int#

Bilder pro Sekunde auf dem Bildschirm angezeigt.

Dies steuert, wie oft der Bildschirm neu gezeichnet wird. Die Spiel-Logik kann jedoch unabhängig davon häufiger oder seltener aufgerufen werden mit world.speed.

Beispiele

world.speed = 10
world.fps = 24
def act(self):
    nonlocal i
    i = i + 1
    if world.frame == 120:
        test_instance.assertEqual(i, 13)
        test_instance.assertEqual(world.frame, 120)
get_actors_from_pixel(pixel)[Quellcode]#

Returns a list of all actors located at the given screen pixel position.

This checks whether each actor’s screen-rect overlaps with the given pixel.

Rückgabetyp:

List[Actor]

Parameter:

pixel – A tuple (x, y) representing the screen pixel.

Rückgabe:

A list of Actor instances under the given pixel.

Example

>>> actors = world.get_actors_from_pixel((120, 80))
>>> for actor in actors:
...     print(actor.name)
get_background()[Quellcode]#

Returns the current active background from the backgrounds manager.

Rückgabetyp:

Background

Rückgabe:

The current Background object.

Example

>>> bg = world.get_background()
get_from_pixel(position)[Quellcode]#

Converts a screen pixel position into a valid world position if inside bounds.

In PixelWorlds, this returns the position directly. In TiledWorlds, this might return a tile coordinate instead (override if needed).

Rückgabetyp:

Optional[Tuple[float, float]]

Parameter:

position – A screen pixel coordinate (x, y)

Rückgabe:

The same position if it lies inside the world, else None.

Example

>>> world.get_from_pixel((100, 50))
(100, 50)
property has_background: bool#

Returns True if the world has at least one background appearance.

Example

>>> if world.has_background:
...     print("Background is set")
is_in_world(position)[Quellcode]#

Checks whether a given world position lies within the world’s boundaries.

Rückgabetyp:

bool

Parameter:

position – A tuple (x, y) representing a position in world coordinates.

Rückgabe:

True if the position is inside the world bounds, False otherwise.

Example

>>> world.size = (800, 600)
>>> world.is_in_world((100, 100))
True
>>> world.is_in_world((900, 100))
False
on_setup()[Quellcode]#

Hook method to define initial setup logic when the world is created.

Override this in subclasses or register via @world.register.

Rückgabetyp:

None

Example

>>> def on_setup():
...     actor = Actor()
quit(exit_code=0)[Quellcode]#

Immediately quits the application and closes the game window.

Rückgabetyp:

None

Parameter:

exit_code – Exit code returned by the application. Defaults to 0.

Example

>>> world.quit()
remove_background(background=None)[Quellcode]#

Removes a background from the world.

If no argument is provided, the last added background will be removed. You can also remove a specific background by passing its index or Appearance object.

Rückgabetyp:

None

Parameter:

background – Either an integer index (e.g. 0) or an Appearance object. If None, the most recently added background is removed.

Example

>>> world.remove_background()              # removes last background
>>> world.remove_background(0)            # removes background at index 0
>>> world.remove_background(my_background)  # removes specific Appearance object
reset()[Quellcode]#

Setzt die Welt zurück Erstellt eine neue Welt mit der Init-Funktion - erstellt alle Akteure und Akteure in der Welt neu.

Beispiele

Startet das Spiel Flappy Bird nach einer Kollision mit einem Rohr neu:

def on_sensing_collision_with_pipe(self, other, info):
    self.world.is_running = False
    self.world.reset()
property rows: int#

Gets the number of vertical pixels (rows) visible in the world.

Rückgabe:

The height of the camera view in pixels.

run(fullscreen=False, fit_desktop=False, replit=False, event=None, data=None)[Quellcode]#

Starts the main application loop of the Miniworlds engine.

This should be called once at the end of a Miniworlds program. It prepares and starts: - The main loop - Event handling - Rendering - Actor updates - Asynchronous compatibility (e.g. for REPLs and Jupyter)

Rückgabetyp:

None

Parameter:
  • fullscreen – If True, the game launches in fullscreen mode.

  • fit_desktop – If True, window size adapts to desktop resolution.

  • replit – Set True if running in a Replit environment (special adjustments).

  • event – Optional event name to queue at startup (e.g. „start“, „setup“).

  • data – Optional data to include with the startup event.

Example

>>> world = World(800, 600)
>>> world.run(fullscreen=False, event="setup")

Notes

Automatically detects and handles running event loops (e.g. in Jupyter).

send_message(message, data=None)[Quellcode]#

Sends a broadcast message to the world and all actors.

The message is dispatched through the event system and can be handled by any registered method in the world or its actors.

Rückgabetyp:

None

Parameter:
  • message – The name of the message/event to send.

  • data – Optional additional data to pass with the message.

Example

>>> world.send_message("explode", {"power": 10})
set_background(source)[Quellcode]#

Sets a new background and replaces the current active background.

If multiple backgrounds already exist, this will override the active one with the new background. The source can be either an image path or a color tuple.

Rückgabetyp:

Background

Parameter:

source – A string path to an image (e.g. „images/bg.png“) or an RGB(A) color tuple (e.g. (0, 0, 255)).

Rückgabe:

The newly created Background object that was set as active.

Verursacht:

FileNotFoundError – If the image file cannot be found.

Example

>>> world.set_background("images/sky.png")
>>> world.set_background((30, 30, 30))  # dark gray
set_columns(value)[Quellcode]#

Internal method to set columns and sync world width.

Rückgabetyp:

None

Parameter:

value – New column count (width in pixels).

set_rows(value)[Quellcode]#

Internal method to set rows and sync world height.

Rückgabetyp:

None

Parameter:

value – New row count (height in pixels).

property size: Tuple[int, int]#

Gets the world size as a tuple (width, height), in pixels.

Rückgabe:

A tuple representing the world size in pixels.

Example

>>> w, h = world.size
>>> print(f"World is {w}x{h} pixels large")
start()[Quellcode]#

Starts or resumes the world.

Sets the internal running flag to True, allowing the world to continue updating and processing events.

Rückgabetyp:

None

Example

>>> world.start()
stop(frames=0)[Quellcode]#

Stops the world immediately or after a delay in frames.

Rückgabetyp:

None

Parameter:

frames – Number of frames to wait before stopping. If 0, stops immediately.

Example

>>> world.stop()         # stops immediately
>>> world.stop(frames=5) # stops after 5 frames
subclasses = None#
switch_background(background)[Quellcode]#

Switches the current background to a specified one.

You can switch by index or directly using an Appearance object. If you pass -1 as index, it will switch to the next available background in the list.

Rückgabetyp:

Background

Parameter:

background – Index of the background to switch to, or an Appearance instance. Use -1 to switch to the next background in order.

Rückgabe:

The new active Background object.

Verursacht:

FileNotFoundError – If the background image file is not found.

Example

>>> world.add_background("images/1.png")
>>> world.add_background("images/2.png")
>>> world.switch_background(1)  # switches to second background

Beispiele

Zwischen verschiedenen Hintergründen wechseln:

from miniworlds import *

world = World()
actor = Actor()

world.add_background("images/1.png")
world.add_background((255, 0, 0, 255))
world.add_background("images/2.png")

@timer(frames = 40)
def switch():
    world.switch_background(0)

@timer(frames = 80)
def switch():
    world.switch_background(1)

@timer(frames = 160)
def switch():
    world.switch_background(2)

world.run()

Ausgabe:

Hintergrund wechseln
property tick_rate: int#

Tick rate defines how often the method act() will be called.

If e.g. tick_rate = 30, the game logic will be called every 30th-frame.

Bemerkung

Sie können die Bildrate mit world.fps anpassen

Beispiele

Geschwindigkeit und fps einstellen.

from miniworlds import *

world = World()
world.size = (120,210)

@world.register
def on_setup(self):
    world.fps = 1
    world.speed = 3

@world.register
def act(self):

world.run()

Ausgabe:

` 3 6 9 12Step 15 `

to_pixel(position)[Quellcode]#

Converts a world position to a screen pixel position.

In PixelWorlds, this is an identity function. In TiledWorlds, override this.

Rückgabetyp:

Tuple[float, float]

Parameter:

position – World coordinate (x, y)

Rückgabe:

Pixel coordinate (x, y)

Example

>>> world.to_pixel((5, 8))
(5, 8)
property world_size_x: int#

Gets the horizontal size of the world in pixels.

This usually equals the camera’s world width.

Rückgabe:

Width of the world in pixels.

Example

>>> print(world.world_size_x)
800
property world_size_y: int#

Gets the vertical size of the world in pixels.

Rückgabe:

Height of the world in pixels.