World#
The base class for all of your worlds
World#
- class miniworlds.worlds.world.World(x=400, y=400)[source]#
A world is a playing field on which actors can move.
A world has a background and provides basic functions for the positioning of actors and for the collision detection of actors, which can be queried via the sensors of the actors.
You can create your own world by creating a class that inherits from World or you can directly create a world object of type World or one of its child classes (TiledWorld, PhysicsWorld, …).
World
A world for pixel accurate games.
The position of a actor on a World is the pixel at topleft of actor.
New actors are created with top-left corner of actor rect at position.
Two actors collide when their sprites overlap.
Other worlds:
TiledWorld: For worlds using Tiles, like rogue-like rpgs, see TiledWorld)
PhysicsWorld: For worlds using the PhysicsEngine, see PhysicsWorld)
Examples
Creating a TiledWorld Object:
from miniworlds import * my_world = TiledWorld() my_world.columns = 30 my_world.rows = 20 my_world.tile_size = 20
Creating a TiledWorld-Subclass.
import miniworlds class MyWorld(miniworlds.TiledWorld): def on_setup(self): self.columns = 30 self.rows = 20 self.tile_size = 20
Creating a World Object:
from miniworlds import * my_world = World() my_world.columns = 300 my_world.rows = 200
Creating a World Subclass
import miniworlds class MyWorld(miniworlds.World): def on_setup(self): self.columns = 300 self.rows = 200
See also
See: World
See: TiledWorld
- Parameters:
view_x – columns of new world (default: 40)
view_y – rows of new world (default:40)
tile_size – Size of tiles (1 for normal worlds, can differ for Tiledworlds)
Public Data Attributes:
Tick rate defines how often the method
act()
will be called.Frames per second shown on the screen.
Gets the horizontal size of the world in pixels.
Gets the vertical size of the world in pixels.
Gets the number of horizontal pixels (columns) visible in the world.
Gets the number of vertical pixels (rows) visible in the world.
Gets the world size as a tuple (width, height), in pixels.
Returns the currently active 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
size
topleft
width
height
class_name
registered_events
Returns the set of all event names that are currently registered.
Public Methods:
__init__
([x, y])contains_position
(pos)Checks if position is in the world.
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.
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.
send_message
(message[, data])Sends a broadcast message to the world and all actors.
quit
([exit_code])Immediately quits the application and closes the game window.
reset
()Resets the world Creates a new world with init-function - recreates all actors and actors on the world.
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__
()remove
(actor)Implemented in subclasses
on_change
()implemented in subclasses
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 Data Attributes:
_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 Methods:
_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
()needed by get_world_connector in parent class
_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)[source]#
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.
- Return type:
- Parameters:
source – Either a path to an image file (e.g. “images/bg.png”) or an RGB/RGBA color tuple (e.g. (0, 0, 255)).
- Returns:
The newly created Background object.
- Raises:
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().
- Returns:
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.
- Returns:
The width of the camera view in pixels.
- contains_position(pos)[source]#
Checks if position is in the world.
- Returns:
True, if Position is in the world.
- contains_rect(rect)[source]#
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)[source]#
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)[source]#
Gets all actors which are found at a specific position (in global world coordinates)
- Return type:
- Parameters:
position – Position, where actors should be searched.
- Returns:
A list of actors
Examples
Get all actors at mouse position:
position = world.get_mouse_position() actors = world.get_actors_by_pixel(position)
- direction_to(pos1, pos2)[source]#
Calculates the angle from pos1 to pos2 in degrees.
- Return type:
- Parameters:
pos1 – Starting position (x, y)
pos2 – Target position (x, y)
- Returns:
Angle in degrees between the two points.
Example
>>> world.direction_to((0, 0), (0, 1)) 90.0
- static distance_to(pos1, pos2)[source]#
Calculates the Euclidean distance between two positions.
- Return type:
- Parameters:
pos1 – First position (x, y)
pos2 – Second position (x, y)
- Returns:
The distance as a float.
Example
>>> World.distance_to((0, 0), (3, 4)) 5.0
- property fps: int#
Frames per second shown on the screen.
This controls how often the screen is redrawn. However, the game logic can be called more often or less often independently of this with
world.speed.
Examples
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)[source]#
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.
- Return type:
- Parameters:
pixel – A tuple (x, y) representing the screen pixel.
- Returns:
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()[source]#
Returns the current active background from the backgrounds manager.
- Return type:
- Returns:
The current Background object.
Example
>>> bg = world.get_background()
- get_from_pixel(position)[source]#
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).
- Return type:
- Parameters:
position – A screen pixel coordinate (x, y)
- Returns:
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)[source]#
Checks whether a given world position lies within the world’s boundaries.
- Return type:
- Parameters:
position – A tuple (x, y) representing a position in world coordinates.
- Returns:
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()[source]#
Hook method to define initial setup logic when the world is created.
Override this in subclasses or register via @world.register.
- Return type:
Example
>>> def on_setup(): ... actor = Actor()
- quit(exit_code=0)[source]#
Immediately quits the application and closes the game window.
- Return type:
- Parameters:
exit_code – Exit code returned by the application. Defaults to 0.
Example
>>> world.quit()
- remove_background(background=None)[source]#
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.
- Return type:
- Parameters:
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()[source]#
Resets the world Creates a new world with init-function - recreates all actors and actors on the world.
Examples
Restarts flappy the bird game after collision with pipe:
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.
- Returns:
The height of the camera view in pixels.
- run(fullscreen=False, fit_desktop=False, replit=False, event=None, data=None)[source]#
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)
- Return type:
- Parameters:
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)[source]#
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.
- Return type:
- Parameters:
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)[source]#
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.
- Return type:
- Parameters:
source – A string path to an image (e.g. “images/bg.png”) or an RGB(A) color tuple (e.g. (0, 0, 255)).
- Returns:
The newly created Background object that was set as active.
- Raises:
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)[source]#
Internal method to set columns and sync world width.
- Return type:
- Parameters:
value – New column count (width in pixels).
- set_rows(value)[source]#
Internal method to set rows and sync world height.
- Return type:
- Parameters:
value – New row count (height in pixels).
- property size: Tuple[int, int]#
Gets the world size as a tuple (width, height), in pixels.
- Returns:
A tuple representing the world size in pixels.
Example
>>> w, h = world.size >>> print(f"World is {w}x{h} pixels large")
- start()[source]#
Starts or resumes the world.
Sets the internal running flag to True, allowing the world to continue updating and processing events.
- Return type:
Example
>>> world.start()
- stop(frames=0)[source]#
Stops the world immediately or after a delay in frames.
- Return type:
- Parameters:
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)[source]#
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.
- Return type:
- Parameters:
background – Index of the background to switch to, or an Appearance instance. Use -1 to switch to the next background in order.
- Returns:
The new active Background object.
- Raises:
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
Examples
Switch between different backgrounds:
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()
Output:
- 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.Note
You can adjust the frame-rate with
world.fps
Examples
Set speed and fps.
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()
Output:
` 3 6 9 12Step 15 `
- to_pixel(position)[source]#
Converts a world position to a screen pixel position.
In PixelWorlds, this is an identity function. In TiledWorlds, override this.
- Return type:
- Parameters:
position – World coordinate (x, y)
- Returns:
Pixel coordinate (x, y)
Example
>>> world.to_pixel((5, 8)) (5, 8)