Skip to content

API reference

This page gives an overview of all public pizzoo objects, functions and methods. All classes and functions exposed in pizzoo.* namespace are public.

Pizzoo

Pizzoo(address, renderer=Pixoo64Renderer, renderer_params={}, debug=False)

Initialize the Pizzoo object with the given renderer. Additional parameters can be passed to the renderer.

Parameters:

Name Type Description Default
address str

The IP address of the Pixoo device, or any renderer that needs an address.

required
renderer Renderer

The renderer to use. Default is Pixoo64Renderer.

Pixoo64Renderer
renderer_params dict

Additional parameters to pass to the renderer.

{}
debug bool

Whether to enable debug mode or not. Default is False.

False

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def __init__(self, address, renderer=Pixoo64Renderer, renderer_params={}, debug=False):
	'''Initialize the Pizzoo object with the given renderer. Additional parameters can be passed to the renderer.

	Args:
		address (str): The IP address of the Pixoo device, or any renderer that needs an address.
		renderer (Renderer): The renderer to use. Default is Pixoo64Renderer.
		renderer_params (dict): Additional parameters to pass to the renderer.
		debug (bool): Whether to enable debug mode or not. Default is False.

	Returns:
		None
	'''
	self.renderer = renderer(address=address, pizzoo=self, debug=debug, **renderer_params)
	self.__compute_device_specs()
	self.__debug = debug
	# Initialize buffer
	self.add_frame()
	# get current dir of this file:
	self.load_font('default', join(self.__current_dir, 'MatrixLight6.bdf'), False)

add_frame

add_frame(rgb=(0, 0, 0))

Adds a new frame to the animation buffer.

Parameters:

Name Type Description Default
rgb tuple(int, int, int) | int | string

The color to fill the frame with. Default is black.

(0, 0, 0)

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def add_frame(self, rgb=(0, 0, 0)):
	'''Adds a new frame to the animation buffer.

	Args:
		rgb (tuple(int, int, int) | int | string): The color to fill the frame with. Default is black.

	Returns:
		None
	'''
	assert self.__current_frame <= self.__max_frames, f'Frame limit reached, push before reaching {self.__max_frames} frames'
	frame = []
	for _ in range(self.pixel_count):
		frame.extend(rgb)
	self.__buffer.append(frame)
	self.__current_frame = len(self.__buffer) - 1

cls

cls(rgb=(0, 0, 0))

Clears the current frame with the given color.

Parameters:

Name Type Description Default
rgb tuple(int, int, int) | int | string

The color to clear the frame with. Default is black.

(0, 0, 0)

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def cls(self, rgb=(0, 0, 0)):
	'''Clears the current frame with the given color.

	Args:
		rgb (tuple(int, int, int) | int | string): The color to clear the frame with. Default is black.

	Returns:
		None
	'''
	rgb = get_color_rgb(rgb)
	self.__buffer[self.__current_frame] = [rgb[0], rgb[1], rgb[2]] * self.pixel_count

draw_circle

draw_circle(xy, radius, color, filled=True)

Draws a circle on the current frame at the given coordinates.

Parameters:

Name Type Description Default
xy tuple(int, int

The coordinates of the center of the circle.

required
radius int

The radius of the circle.

required
color tuple(int, int, int) | int | string

The color to draw the circle with.

required
filled bool

Whether to fill the circle or not.

True

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def draw_circle(self, xy, radius, color, filled=True):
	'''Draws a circle on the current frame at the given coordinates.

	Args:
		xy (tuple(int, int)): The coordinates of the center of the circle.
		radius (int): The radius of the circle.
		color (tuple(int, int, int) | int | string): The color to draw the circle with.
		filled (bool): Whether to fill the circle or not.

	Returns:
		None
	'''
	for x in range(xy[0] - radius, xy[0] + radius + 1):
		for y in range(xy[1] - radius, xy[1] + radius + 1):
			if (x - xy[0]) ** 2 + (y - xy[1]) ** 2 <= radius ** 2:
				self.draw_pixel((x, y), color)

draw_gif

draw_gif(gif_path, xy=(0, 0), size='auto', loop=False, resample_method=Image.NEAREST, fill='auto')

Draws a gif on the animation buffer, starting on current frame. If the gif is larger than the screen, it will be resized to fit the screen.

Parameters:

Name Type Description Default
gif_path str

The path to the gif file.

required
xy tuple(int, int

The coordinates to start drawing the gif at.

(0, 0)
size tuple(int, int) | str

The size to resize the gif to. If 'auto' is given, width and height of the gif will be used and resized if needed to fit the screen.

'auto'
loop bool

Whether to loop the gif or not.

False
resample_method Resampling

The resample mode to use when resizing the gif to fit the screen. Default is Image.NEAREST.

NEAREST
fill tuple(int, int, int) | str

The color to fill the screen with before drawing the gif. If 'auto' is given, the color will be black.

'auto'

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def draw_gif(self, gif_path, xy=(0, 0), size='auto', loop=False, resample_method=Image.NEAREST, fill='auto'):
	'''Draws a gif on the animation buffer, starting on current frame. If the gif is larger than the screen, it will be resized to fit the screen.

	Args:
		gif_path (str): The path to the gif file.
		xy (tuple(int, int)): The coordinates to start drawing the gif at.
		size (tuple(int, int) | str): The size to resize the gif to. If 'auto' is given, width and height of the gif will be used and resized if needed to fit the screen.
		loop (bool): Whether to loop the gif or not.
		resample_method (Resampling): The resample mode to use when resizing the gif to fit the screen. Default is Image.NEAREST.
		fill (tuple(int, int, int) | str): The color to fill the screen with before drawing the gif. If 'auto' is given, the color will be black.

	Returns:
		None
	'''
	current_frame = self.__current_frame if self.__current_frame >= 0 else 0
	gif = Image.open(gif_path)
	remaining_frames = self.__max_frames - current_frame
	total_frames = remaining_frames if loop else min(remaining_frames, gif.n_frames)
	current_gif_frame = 0
	for frame in range(0, total_frames):
		if frame >= self.__max_frames:
			break
		try:
			current_gif_frame += 1
			gif.seek(current_gif_frame)
		except EOFError:
			current_gif_frame = 0
			gif.seek(current_gif_frame)
		if fill == 'auto':
			self.cls()
		elif fill is not None:
			self.cls(fill)
		self.draw_image(gif, xy, size, resample_method)
		if frame < total_frames - 1:
			if len(self.__buffer) < self.__current_frame + 2:
				self.add_frame()
			else:
				self.__current_frame += 1
	self.__current_frame = current_frame

draw_image

draw_image(image_or_path, xy=(0, 0), size='auto', resample_method=Image.NEAREST)

Draws an image on the current frame at the given coordinates.

Parameters:

Name Type Description Default
image_or_path str | Image

The path to the image file or the Image object to draw.

required
xy tuple(int, int

The coordinates of the top-left corner of the image.

(0, 0)
size tuple(int, int) | str

The size to resize the image to. If 'auto' is given, the image will be resized to fit the screen if needed.

'auto'
resample_method Resampling

The resample mode to use when resizing the image to fit the screen. Default is Image.NEAREST.

NEAREST

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def draw_image(self, image_or_path, xy=(0, 0), size='auto', resample_method=Image.NEAREST):
	'''Draws an image on the current frame at the given coordinates.

	Args:
		image_or_path (str | Image): The path to the image file or the Image object to draw.
		xy (tuple(int, int)): The coordinates of the top-left corner of the image.
		size (tuple(int, int) | str): The size to resize the image to. If 'auto' is given, the image will be resized to fit the screen if needed.
		resample_method (Resampling): The resample mode to use when resizing the image to fit the screen. Default is Image.NEAREST.

	Returns:
		None
	'''
	if isinstance(image_or_path, str):
		image = Image.open(image_or_path)
	else:
		image = image_or_path
	width, height = self.__compute_image_resize(image, size)
	image = ImageOps.fit(image, (width, height), method=resample_method, centering=(0.5, 0.5))
	image = image.convert('RGBA')
	for x in range(image.width):
		for y in range(image.height):
			rgba = image.getpixel((x, y))
			if rgba[3] > 0:
				placed_x, placed_y = x + xy[0], y + xy[1]
				if self.size - 1 < placed_x or placed_x < 0 or self.size - 1 < placed_y or placed_y < 0:
					continue
				self.draw_pixel((placed_x, placed_y), rgba)

draw_line

draw_line(start, end, color)

Draws a line on the current frame from the start to the end coordinates.

Parameters:

Name Type Description Default
start tuple(int, int

The coordinates of the start of the line.

required
end tuple(int, int

The coordinates of the end of the line.

required
color tuple(int, int, int) | int | string

The color to draw the line with.

required

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def draw_line(self, start, end, color):
	'''Draws a line on the current frame from the start to the end coordinates.

	Args:
		start (tuple(int, int)): The coordinates of the start of the line.
		end (tuple(int, int)): The coordinates of the end of the line.
		color (tuple(int, int, int) | int | string): The color to draw the line with.

	Returns:
		None
	'''
	x0, y0 = start
	x1, y1 = end
	dx = abs(x1 - x0)
	dy = abs(y1 - y0)
	sx = 1 if x0 < x1 else -1
	sy = 1 if y0 < y1 else -1
	err = dx - dy
	while x0 != x1 or y0 != y1:
		self.draw_pixel((x0, y0), color)
		e2 = 2 * err
		if e2 > -dy:
			err -= dy
			x0 += sx
		if e2 < dx:
			err += dx
			y0 += sy

draw_pixel

draw_pixel(xy, color)

Draws a single pixel on the current frame at the given coordinates.

Parameters:

Name Type Description Default
xy tuple(int, int

The coordinates to draw the pixel at.

required
color tuple(int, int, int) | int | string

The color to draw the pixel with.

required

Raises:

Type Description
ValueError

If the given coordinates are out of bounds.

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def draw_pixel(self, xy, color):
	'''Draws a single pixel on the current frame at the given coordinates.

	Args:
		xy (tuple(int, int)): The coordinates to draw the pixel at.
		color (tuple(int, int, int) | int | string): The color to draw the pixel with.

	Raises:
		ValueError: If the given coordinates are out of bounds.

	Returns:
		None
	'''
	index = xy[0] + (xy[1] * self.size)
	rgb = get_color_rgb(color)
	if index < 0 or index >= self.pixel_count:
		raise ValueError(f'Invalid index given: {index} (maximum index is {self.pixel_count - 1})')
	# FIXME: Could we maybe move to rgba and use the alpha channel to determine if the pixel is on or off? -> index = index * 4
	index = index * 3
	self.__buffer[self.__current_frame][index + 1] = rgb[1]
	self.__buffer[self.__current_frame][index] = rgb[0]
	self.__buffer[self.__current_frame][index + 2] = rgb[2]

draw_rectangle

draw_rectangle(xy, width, height, color, filled=True)

Draws a rectangle on the current frame at the given coordinates.

Parameters:

Name Type Description Default
xy tuple(int, int

The coordinates of the top-left corner of the rectangle.

required
width int

The width of the rectangle.

required
height int

The height of the rectangle.

required
color tuple(int, int, int) | int | string

The color to draw the rectangle with.

required
filled bool

Whether to fill the rectangle or not.

True

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def draw_rectangle(self, xy, width, height, color, filled=True):
	'''Draws a rectangle on the current frame at the given coordinates.

	Args:
		xy (tuple(int, int)): The coordinates of the top-left corner of the rectangle.
		width (int): The width of the rectangle.
		height (int): The height of the rectangle.
		color (tuple(int, int, int) | int | string): The color to draw the rectangle with.
		filled (bool): Whether to fill the rectangle or not.

	Returns:
		None
	'''
	for x in range(xy[0], xy[0] + width):
		for y in range(xy[1], xy[1] + height):
			if filled or x == xy[0] or x == xy[0] + width - 1 or y == xy[1] or y == xy[1] + height - 1:
				self.draw_pixel((x, y), color)

draw_text

draw_text(text, xy=(0, 0), font='default', color='#FFFFFF', align=0, line_width='auto', shadow=None, shadow_rgb=(0, 0, 0))

Draws a text on the current frame at the given coordinates.

Parameters:

Name Type Description Default
text str

The text to draw.

required
xy tuple(int, int

The coordinates of the top-left corner of the text.

(0, 0)
font str

The name of the font to use. Default is 'default'.

'default'
color tuple(int, int, int) | int | string

The color to draw the text with.

'#FFFFFF'
align int

The alignment of the text. 0 is left, 1 is center and 2 is right.

0
shadow str | tuple | None

The type of shadow to add to the text. Values are 'horizontal', 'vertical', 'diagonal', tuple with displacements, or None.

None

shadow_rgb (tuple(int, int, int) | int | string): The color of the shadow. line_width (int): The maximum width of the text. Default is 'auto'.

Returns:

Type Description

None

Source code in pizzoo\__init__.py
	def draw_text(self, text, xy=(0, 0), font='default', color='#FFFFFF', align=0, line_width='auto', shadow=None, shadow_rgb=(0, 0, 0)):
		'''Draws a text on the current frame at the given coordinates.

		Args:
			text (str): The text to draw.
			xy (tuple(int, int)): The coordinates of the top-left corner of the text.
			font (str): The name of the font to use. Default is 'default'.
			color (tuple(int, int, int) | int | string): The color to draw the text with.
			align (int): The alignment of the text. 0 is left, 1 is center and 2 is right.
			shadow (str | tuple | None): The type of shadow to add to the text. Values are 'horizontal', 'vertical', 'diagonal', tuple with displacements, or None.
        	shadow_rgb (tuple(int, int, int) | int | string): The color of the shadow.
			line_width (int): The maximum width of the text. Default is 'auto'.

		Returns:
			None
		'''
		line_width = self.size if line_width == 'auto' else line_width
		font = self.__get_font(font)
		rgb = get_color_rgb(color)
		bitmap = font.draw(text, missing='?', linelimit=line_width)
		if shadow is not None:
			shadow_rgb = get_color_rgb(shadow_rgb)
			shadow_displacement = (0, 0)
			if type(shadow) == tuple:
				shadow_displacement = shadow
			elif shadow == 'horizontal':
				shadow_displacement = (1, 0)
			elif shadow == 'vertical':
				shadow_displacement = (0, -1)
			elif shadow == 'diagonal':
				shadow_displacement = (1, -1)
			bitmap.shadow(shadow_displacement[0], shadow_displacement[1])
		text_data = bitmap.todata(2)
		width, height = bitmap.width(), bitmap.height()
		for x in range(width):
			for y in range(height):
				if text_data[y][x]:
					placed_x, placed_y = x + xy[0], y + xy[1]
					if self.size - 1 < placed_x or placed_x < 0 or self.size - 1 < placed_y or placed_y < 0:
						continue
					self.draw_pixel((placed_x, placed_y), rgb if text_data[y][x] == 1 else shadow_rgb)

get_settings

get_settings()

Get the current settings from the device.

Returns:

Type Description

A dict with the current settings of the device.

Source code in pizzoo\__init__.py
def get_settings(self):
	'''Get the current settings from the device.

	Returns:
		A dict with the current settings of the device.
	'''
	return self.renderer.get_settings()

load_font

load_font(font_name, path, soft=True)

Loads a new font on bdf format to be used on the draw_text method.

Parameters:

Name Type Description Default
font_name str

The name to identify the font.

required
path str

The path to the font file.

required
soft bool

If True, the font will be loaded when used. If False, the font will be loaded now.

True

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def load_font(self, font_name, path, soft=True):
	'''Loads a new font on bdf format to be used on the draw_text method.

	Args:
		font_name (str): The name to identify the font.
		path (str): The path to the font file.
		soft (bool): If True, the font will be loaded when used. If False, the font will be loaded now.

	Returns:
		None
	'''
	if soft:
		self.__fonts[font_name] = path
	else:
		from bdfparser import Font
		self.__fonts[font_name] = Font(path)

load_fonts

load_fonts(fonts)

Loads multiple fonts at once.

Parameters:

Name Type Description Default
fonts dict

A dictionary with the font name as key and the font path as value.

required

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def load_fonts(self, fonts):
	'''Loads multiple fonts at once.

	Args:
		fonts (dict): A dictionary with the font name as key and the font path as value.

	Returns:
		None
	'''
	for font_name, path in fonts.items():
		self.load_font(font_name, path)

render

render(frame_speed=150)

Renders the current animation buffer to the Pixoo device. After that it resets the buffer.

Take into account that only a max of 60 frames can be rendered at once. So any buffer with more than 60 frames will be truncated.

Parameters:

Name Type Description Default
frame_speed int

The speed in milliseconds per frame. Default is 150. (Only useful if more than 1 frame is being rendered)

150

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def render(self, frame_speed=150):
	'''Renders the current animation buffer to the Pixoo device. After that it resets the buffer.

	Take into account that only a max of 60 frames can be rendered at once. So any buffer with more than 60 frames will be truncated.

	Args:
		frame_speed (int): The speed in milliseconds per frame. Default is 150. (Only useful if more than 1 frame is being rendered)

	Returns:
		None
	'''
	self.renderer.render(self.__buffer, frame_speed)
	self.reset_buffer()

render_template

render_template(template, use_cache=False)

Renders an XML template to the given renderer.

This template can have a number of valid tags that are directly supported by the library, but any other renderer can add his own nodes. The template must have a root tag named 'pizzoo' and can have the following tags:

  • section - A container for other elements. It can have x, y, width, height and position attributes.
  • rectangle - Draws a rectangle. It can have x, y, width, height, color and filled attributes.
  • circle - Draws a circle. It can have x, y, radius and color attributes.
  • text - Draws a text. It can have x, y, color, wrap, shadow, shadowColor and font attributes.
  • pixel - Draws a single pixel. It can have x, y and color attributes.
  • image - Draws an image. It can have x, y and src attributes.
  • line - Draws a line. It can have x, y, x2, y2 and color attributes. Aside from that, any container as section or rectangle can have a position attribute with the following values:
  • static - x and y are relative to last non-absolute parent
  • relative - as static, but absolute children are relative to this element
  • absolute - x and y are absolute to the last relative element or the screen

Parameters:

Name Type Description Default
template str

The XML template to render.

required
use_cache bool

Whether to use the cache or not. Default is False. (Currently not in use)

False

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def render_template(self, template, use_cache=False):
	'''Renders an XML template to the given renderer.

	This template can have a number of valid tags that are directly supported by the library, but any other renderer can add his own nodes.
	The template must have a root tag named 'pizzoo' and can have the following tags:

	* section - A container for other elements. It can have x, y, width, height and position attributes.
	* rectangle - Draws a rectangle. It can have x, y, width, height, color and filled attributes.
	* circle - Draws a circle. It can have x, y, radius and color attributes.
	* text - Draws a text. It can have x, y, color, wrap, shadow, shadowColor and font attributes.
	* pixel - Draws a single pixel. It can have x, y and color attributes.
	* image - Draws an image. It can have x, y and src attributes.
	* line - Draws a line. It can have x, y, x2, y2 and color attributes.
	Aside from that, any container as section or rectangle can have a position attribute with the following values:
	* static - x and y are relative to last non-absolute parent
	* relative - as static, but absolute children are relative to this element
	* absolute - x and y are absolute to the last relative element or the screen

	Args:
		template (str): The XML template to render.
		use_cache (bool): Whether to use the cache or not. Default is False. (Currently not in use)

	Returns:
		None
	'''
	self.cls()
	commands = self.__compile_template(template)
	renderer_items = []
	for command in commands:
		if callable(command[0]):
			command[0](**command[1])
		else:
			renderer_items.append(command)
	self.render()
	if len(renderer_items) > 0:
		self.renderer.render_template_items(renderer_items, use_cache)

reset_buffer

reset_buffer()

Resets the animation buffer, removing all frames and adding a new one.

Returns:

Type Description

And int with the number of items removed from the buffer.

Source code in pizzoo\__init__.py
def reset_buffer(self):
	'''Resets the animation buffer, removing all frames and adding a new one.

	Returns:
		And int with the number of items removed from the buffer.
	'''
	removed_items = len(self.__buffer)
	self.__buffer = []
	self.__current_frame = -1
	self.add_frame()
	return removed_items

set_brightness

set_brightness(brightness)

Sets the brightness of the device.

Parameters:

Name Type Description Default
brightness int

The brightness value to set. Must be between 0 and 100.

required

Returns:

Type Description

None

Source code in pizzoo\__init__.py
def set_brightness(self, brightness):
	'''Sets the brightness of the device.

	Args:
		brightness (int): The brightness value to set. Must be between 0 and 100.

	Returns:
		None
	'''
	self.renderer.set_brightness(brightness)

switch

switch(on=True)

Turns the device on or off.

Source code in pizzoo\__init__.py
def switch(self, on=True):
	'''Turns the device on or off.
	'''
	self.renderer.switch(on)

Renderer

Renderer(address, pizzoo, debug)

A renderer is an object that is used to render the frames on the device. It can be a real device, an emulator or a static image.

Source code in pizzoo\_renderers.py
def __init__(self, address, pizzoo, debug):
	'''
	A renderer is an object that is used to render the frames on the device. It can be a real device, an emulator or a static image.
	'''
	self._debug = debug
	self._address = address
	self._pizzoo = pizzoo

compile_node

compile_node(node, parent, inherited_props, node_props)

Compiles an XML node into a command that can be executed on the device.

Parameters:

Name Type Description Default
node Element

The XML node to compile.

required
parent Element

The parent XML node.

required
inherited_props dict

The properties inherited from the parent node.

required
node_props dict

The properties of the current node.

required
Source code in pizzoo\_renderers.py
def compile_node(self, node, parent, inherited_props, node_props):
	'''
	Compiles an XML node into a command that can be executed on the device.

	Args:
		node (Element): The XML node to compile.
		parent (Element): The parent XML node.
		inherited_props (dict): The properties inherited from the parent node.
		node_props (dict): The properties of the current node.
	'''
	return None

compile_node_root_options

compile_node_root_options(options)

Compiles the root options of the XML into a list of commands that can be executed on the device.

Parameters:

Name Type Description Default
options dict

The options of the root node.

required
Source code in pizzoo\_renderers.py
def compile_node_root_options(self, options):
	'''
	Compiles the root options of the XML into a list of commands that can be executed on the device.

	Args:
		options (dict): The options of the root node.
	'''
	return []

get_max_frames

get_max_frames()

Returns the maximum amount of frames the device buffer can store.

Returns:

Name Type Description
int

The maximum amount of frames the device can store.

Source code in pizzoo\_renderers.py
def get_max_frames(self):
	'''
	Returns the maximum amount of frames the device buffer can store.

	Returns:
		int: The maximum amount of frames the device can store.	
	'''
	return self._max_frames

get_settings

get_settings()

Gets the current settings of the device.

Source code in pizzoo\_renderers.py
def get_settings(self):
	'''
	Gets the current settings of the device.
	'''
	raise NotImplementedError

get_size

get_size()

Returns the size of the device screen.

Returns:

Name Type Description
int

The size of the device screen.

Source code in pizzoo\_renderers.py
def get_size(self):
	'''
	Returns the size of the device screen.

	Returns:
		int: The size of the device screen.
	'''
	return self._size

render

render(buffer, frame_speed)

Renders the buffer on the device.

Parameters:

Name Type Description Default
buffer list

A list of frames to render on the device.

required
frame_speed int

The speed at which the frames should be displayed.

required
Source code in pizzoo\_renderers.py
def render(self, buffer, frame_speed):
	'''
	Renders the buffer on the device.

	Args:
		buffer (list): A list of frames to render on the device.
		frame_speed (int): The speed at which the frames should be displayed.
	'''
	raise NotImplementedError

render_template_items

render_template_items(items, use_cache=True)

Renders or process a list of items on the device.

Parameters:

Name Type Description Default
items list

A list of items to render on the device.

required
use_cache bool

Whether to use the cache or not.

True
Source code in pizzoo\_renderers.py
def render_template_items(self, items, use_cache=True):
	'''
	Renders or process a list of items on the device.

	Args:
		items (list): A list of items to render on the device.
		use_cache (bool): Whether to use the cache or not.
	'''
	return None

set_brightness

set_brightness(brightness)

Sets the brightness of the device.

Parameters:

Name Type Description Default
brightness int

The brightness level to set. Between 0 and 100.

required
Source code in pizzoo\_renderers.py
def set_brightness(self, brightness):
	'''
	Sets the brightness of the device.

	Args:
		brightness (int): The brightness level to set. Between 0 and 100.
	'''
	raise NotImplementedError

switch

switch(on=True)

Turns the device on or off.

Parameters:

Name Type Description Default
on bool

Whether to turn the device on or off.

True
Source code in pizzoo\_renderers.py
def switch(self, on=True):
	'''
	Turns the device on or off.

	Args:
		on (bool): Whether to turn the device on or off.
	'''
	raise NotImplementedError

Pixoo64Renderer

Pixoo64Renderer(address, pizzoo, debug)

Bases: Renderer

This renderer is used to render the frames on the Divoom Pixoo64 device. It uses the Divoom API to send the frames to the device. Also includes some built-in methods for controlling the device like the buzzer, scoreboard, countdown, etc.

Source code in pizzoo\_renderers.py
def __init__(self, address, pizzoo, debug):
	'''
	This renderer is used to render the frames on the Divoom Pixoo64 device. It uses the Divoom API to send the frames to the device.
	Also includes some built-in methods for controlling the device like the buzzer, scoreboard, countdown, etc.
	'''
	super().__init__(address, pizzoo, debug)
	self._size = 64
	self._max_frames = 60
	self.__id_limit = 100
	self.__url = f'http://{address}/post'
	self.__pic_id = self.__request('Draw/GetHttpGifId')['PicId']
	if self.__pic_id > self.__id_limit:
		self.__reset_pic_id()

buzzer

buzzer(active=0.5, inactive=0.5, duration=1)

Plays a sound on the device buzzer.

Parameters:

Name Type Description Default
active float

The time in seconds the buzzer is active.

0.5
inactive float

The time in seconds the buzzer is inactive.

0.5
duration float

The total time in seconds the buzzer will play.

1

Returns:

Type Description

None

Source code in pizzoo\_renderers.py
def buzzer(self, active=0.5, inactive=0.5, duration=1):
	'''
	Plays a sound on the device buzzer.

	Args:
		active (float): The time in seconds the buzzer is active.
		inactive (float): The time in seconds the buzzer is inactive.
		duration (float): The total time in seconds the buzzer will play.

	Returns:
		None
	'''
	self.__request('Device/PlayBuzzer', {
		'ActiveTimeInCycle': active * 1000,
		'OffTimeInCycle': inactive * 1000,
		'PlayTotalTime': duration * 1000
	})

clear_remote_text

clear_remote_text()

Clears the remote text on the device.

Source code in pizzoo\_renderers.py
def clear_remote_text(self):
	'''
	Clears the remote text on the device.
	'''
	return self.__request('Draw/ClearHttpText')

set_dial

set_dial(items, background=None, clear=True)

Sets the dial on the device with the given items. These are networking commands on the pixoo device that manage things like temperature, weather, time, etc. Most of them just auto-update, so it's useful for creating custom dials (Like watchfaces, for example).

Parameters:

Name Type Description Default
items list(dict

A list of items to display on the dial. Each item should have at least a 'DisplayType' type.

required
background str

The path to an image to use as the background of the dial. Default is None.

None
clear bool

Whether to send a network clear for the current text on the device or not. Default is True.

True

Returns:

Type Description

None

Note: This method is pretty raw and depends on knowing the exact parameters to send to the device. It's recommended to use the higher-level render_template method. If needed additional documentation can be found on the official API.

Source code in pizzoo\_renderers.py
def set_dial(self, items, background=None, clear=True):
	'''
	Sets the dial on the device with the given items. These are networking commands on the pixoo device that manage things like temperature, weather, time, etc.
	Most of them just auto-update, so it's useful for creating custom dials (Like watchfaces, for example).

	Args:
		items (list(dict)): A list of items to display on the dial. Each item should have at least a 'DisplayType' type.
		background (str): The path to an image to use as the background of the dial. Default is None.
		clear (bool): Whether to send a network clear for the current text on the device or not. Default is True.

	Returns:
		None

	Note: This method is pretty raw and depends on knowing the exact parameters to send to the device. It's recommended to use the higher-level render_template method.
	If needed additional documentation [can be found on the official API](https://doc.divoom-gz.com/web/#/12?page_id=234).
	'''
	if background is not None:
		path_ext = background.split('.')[-1]
		if path_ext == 'gif':
			self._pizoo.draw_gif(background, size='auto', fill='auto')
		else:
			self._pizoo.draw_image(background)
		self._pizoo.render()
	if clear:
		self.clear_remote_text()
	processed_items = [{'TextId': index + 1, **DIAL_DEFAULT_ITEM, **item} for index, item in enumerate(items)]
	self.__request('Draw/SendHttpItemList', {
		'ItemList': processed_items
	})

set_scoreboard

set_scoreboard(blue_score=0, red_score=0)

Sets the scoreboard on the device for every team.

Parameters:

Name Type Description Default
blue_score int

The score for the blue team.

0
red_score int

The score for the red team.

0

Returns:

Type Description

None

Source code in pizzoo\_renderers.py
def set_scoreboard(self, blue_score=0, red_score=0):
	'''
	Sets the scoreboard on the device for every team.

	Args:
		blue_score (int): The score for the blue team.
		red_score (int): The score for the red team.

	Returns:
		None
	'''
	self.__request('Tools/SetScoreBoard', {
		'BlueScore': blue_score,
		'RedScore': red_score
	})

start_countdown

start_countdown(seconds=0)

Creates and starts the countdown timer on the device.

Parameters:

Name Type Description Default
seconds int

The amount of seconds to countdown from.

0

Returns:

Type Description

None

Source code in pizzoo\_renderers.py
def start_countdown(self, seconds=0):
	'''
	Creates and starts the countdown timer on the device.

	Args:
		seconds (int): The amount of seconds to countdown from.

	Returns:
		None
	'''
	minutes = int(seconds / 60)
	seconds = seconds % 60
	self.__request('Tools/SetTimer', {
		'Minute': minutes,
		'Second': seconds,
		'Status': 1
	})
	self.__start_countdown_time = time()

stop_countdown

stop_countdown()

Stops the countdown timer on the device.

Returns:

Name Type Description
int

Elapsed time in seconds

Source code in pizzoo\_renderers.py
def stop_countdown(self):
	'''
	Stops the countdown timer on the device.

	Args:
		None

	Returns:
		int: Elapsed time in seconds
	'''
	self.__request('Tools/SetTimer', {
		'Status': 0
	})
	return int(time() - self.__start_countdown_time)

ImageRenderer

ImageRenderer(address, pizzoo, debug, resize_factor=5, resample_method=Image.NEAREST)

Bases: Renderer

This renderer creates a static image or gif with the frames and saves it to the disk. It can be used for debugging or demo purposes.

Source code in pizzoo\_renderers.py
def __init__(self, address, pizzoo, debug, resize_factor=5, resample_method=Image.NEAREST):
	'''
	This renderer creates a static image or gif with the frames and saves it to the disk. It can be used for debugging or demo purposes.
	'''
	super().__init__(address, pizzoo, debug)
	self._size = 64
	self._max_frames = 60
	self._resize_factor = resize_factor
	self._resample_method = resample_method

render

render(buffer, frame_speed)

The static render creates an image (if one frame) or a gif (if multiple frames) and then shows and returns it.

Source code in pizzoo\_renderers.py
def render(self, buffer, frame_speed):
	'''
	The static render creates an image (if one frame) or a gif (if multiple frames) and then shows and returns it.
	'''
	buffer = buffer[-self._max_frames:]
	if len(buffer) == 1:
		image = Image.frombytes('RGB', (self._size, self._size), bytes(buffer[0]), 'raw')
		if self._resize_factor > 1:
			image = image.resize((self._size * self._resize_factor, self._size * self._resize_factor), resample=self._resample_method)
		image.save('temp.png')
		image.show()
	else:
		# Create gif with all frames
		images = []
		for frame in buffer:
			images.append(Image.frombytes('RGB', (self._size, self._size), bytes(frame), 'raw'))
		if self._resize_factor > 1:
			images = [image.resize((self._size * self._resize_factor, self._size * self._resize_factor), resample=self._resample_method) for image in images]
		images[0].save('temp.gif', save_all=True, append_images=images[1:], loop=0, duration=frame_speed)

WindowRenderer

WindowRenderer(address, pizzoo, debug)

Bases: Renderer

This renderer creates a window with a canvas to render the frames on the screen. It can be used for debugging or testing purposes.

Source code in pizzoo\_renderers.py
def __init__(self, address, pizzoo, debug):
	'''
	This renderer creates a window with a canvas to render the frames on the screen. It can be used for debugging or testing purposes.
	'''
	super().__init__(address, pizzoo, debug)
	self._size = 64
	self._max_frames = 60
	self._resize_factor = 5
	self.__resize_size = (self._size * self._resize_factor, self._size * self._resize_factor)
	self._root = tk.Tk()
	self._root.title('Pizzoo emulator')
	self._root.geometry('{0}x{1}'.format(self.__resize_size[0], self.__resize_size[1]))
	self._root.attributes('-topmost', True)
	self.__canvas = tk.Canvas(self._root, width=self._size * self._resize_factor, height=self._size * self._resize_factor, bg='black')
	self.__canvas.pack()

	image = Image.new('RGB', (self._size, self._size), color='black')

	image = self._process_image(image)
	self.__image = self.__canvas.create_image(self.__resize_size[0] / 2, self.__resize_size[0] / 2, image=image)

	self._root.update()

render

render(buffer, frame_speed)

The static render creates an image (if one frame) or a gif (if multiple frames) and then displays it on the window.

Source code in pizzoo\_renderers.py
def render(self, buffer, frame_speed):
	'''
	The static render creates an image (if one frame) or a gif (if multiple frames) and then displays it on the window.
	'''
	buffer = buffer[-self._max_frames:]
	wh = self._size * self._resize_factor
	if len(buffer) == 1:
		image = Image.frombytes('RGB', (self._size, self._size), bytes(buffer[0]), 'raw')
		image = self._process_image(image)
		self.__canvas.itemconfig(self.__image, image=image)
	else:
		# Create gif with all frames
		images = []
		for frame in buffer:
			images.append(Image.frombytes('RGB', (self._size, self._size), bytes(frame), 'raw'))
		images = [image.resize((wh, wh), resample=Image.NEAREST) for image in images]
	self._root.update()

game

Actor

Actor(x, y, frame_src, game, base_path=None, z_index=0, bounding_box_size=None, visible=True, solid=True)

Creates a new actor object. An actor is an object that can be rendered on the screen and can interact with other objects.

Parameters:

Name Type Description Default
x int

the x coordinate of the actor

required
y int

the y coordinate of the actor

required
frame_src (str, list)

Can be a list of paths to images or an iterable of images (like a gif)

required
game PizzooGame

the game object

required
base_path str

the base path to the image files

None
z_index int

the z index of the actor

0
bounding_box_size tuple

a tuple with the width and height of the bounding box

None
visible bool

if True, the actor will be rendered on the screen

True
solid bool

if True, the actor will collide with other objects

True
Source code in pizzoo\game.py
def __init__(self, x, y, frame_src, game, base_path=None, z_index=0, bounding_box_size=None, visible=True, solid=True):
	'''
	Creates a new actor object. An actor is an object that can be rendered on the screen and can interact with other objects.

	Args:
		x (int): the x coordinate of the actor
		y (int): the y coordinate of the actor
		frame_src (str, list): Can be a list of paths to images or an iterable of images (like a gif)
		game (PizzooGame): the game object
		base_path (str): the base path to the image files
		z_index (int): the z index of the actor
		bounding_box_size (tuple): a tuple with the width and height of the bounding box
		visible (bool): if True, the actor will be rendered on the screen
		solid (bool): if True, the actor will collide with other objects
	'''
	self.x = x
	self.y = y
	self.sprite = Sprite(frame_src, base_path=base_path)
	self.z_index = z_index
	self.visible = visible
	self.solid = solid
	self.g = game
	self.bounding_box_size = bounding_box_size if bounding_box_size is not None else self.sprite.size()

check_collisions

check_collisions(class_names=None)

Checks the collisions of the actor with other objects in the game.

Parameters:

Name Type Description Default
class_names (list, str)

a list of class names or a single class name to filter the collisions

None

Returns:

Type Description

Collision list (list): a list of objects that collided with the actor

Source code in pizzoo\game.py
def check_collisions(self, class_names=None):
	'''
	Checks the collisions of the actor with other objects in the game.

	Args:
		class_names (list, str): a list of class names or a single class name to filter the collisions

	Returns:
		Collision list (list): a list of objects that collided with the actor
	'''
	return self.g.check_collisions(self, class_names)

collisions

collisions()

Checks the collisions of the actor with other objects in the game.

Source code in pizzoo\game.py
def collisions(self):
	'''
	Checks the collisions of the actor with other objects in the game.
	'''
	pass

destroy

destroy()

Removes the actor from the game.

Source code in pizzoo\game.py
def destroy(self):
	'''
	Removes the actor from the game.
	'''
	self.g.remove_instance(self)

on_press

on_press(key)

Handles the key press events.

Parameters:

Name Type Description Default
key str

the key that was pressed

required
Source code in pizzoo\game.py
def on_press(self, key):
	'''
	Handles the key press events.

	Args:
		key (str): the key that was pressed
	'''
	pass

step

step()

Updates the actor state, moving the actor and checking the collisions.

Source code in pizzoo\game.py
def step(self):
	'''
	Updates the actor state, moving the actor and checking the collisions.
	'''
	pass

Camera

Camera(game, x, y, center_on=None)

Creates a new camera object. A camera is a portion of the map that is visible/rendered on the screen, it can be centered on an object or moved manually.

Parameters:

Name Type Description Default
game PizzooGame

the game object

required
x int

the x coordinate of the camera

required
y int

the y coordinate of the camera

required
center_on Actor

the object to center the camera on

None
Source code in pizzoo\game.py
def __init__(self, game, x, y, center_on=None):
	'''
	Creates a new camera object. A camera is a portion of the map that is visible/rendered on the screen, it can be centered on an object or moved manually.

	Args:
		game (PizzooGame): the game object
		x (int): the x coordinate of the camera
		y (int): the y coordinate of the camera
		center_on (Actor): the object to center the camera on
	'''
	self.g = game
	self.x = x
	self.y = y
	self.width = 64
	self.height = 64
	self.center_on = center_on
	if self.center_on is not None:
		self.center(self.center_on)

center

center(target)

Centers the camera on a target object.

Parameters:

Name Type Description Default
target Actor

the object to center the camera on

required
Source code in pizzoo\game.py
def center(self, target):
	'''
	Centers the camera on a target object.

	Args:
		target (Actor): the object to center the camera on
	'''
	current_map = self.g.maps[self.g.current_map]
	current_map_width = current_map.tiles_width * current_map.tile_size
	current_map_height = current_map.tiles_height * current_map.tile_size
	self.x = target.x - int(self.width / 2)
	self.y = target.y - int(self.height / 2)
	if self.x < 0:
		self.x = 0
	elif self.x + self.width > current_map_width:
		self.x = current_map_width - self.width
	if self.y < 0:
		self.y = 0
	elif self.y + self.height > current_map_height:
		self.y = current_map_height - self.height

step

step()

Updates the camera position based on the target object if center_on is selected, else does nothing by default.

Source code in pizzoo\game.py
def step(self):
	'''
	Updates the camera position based on the target object if `center_on` is selected, else does nothing by default.
	'''
	if self.center_on is None:
		return
	self.center(self.center_on)

Map

Map(tile_size, tiles_width, tiles_height)

Creates a new map object. A map is a grid of tiles that can be filled with sprites.

Parameters:

Name Type Description Default
tile_size int

the size of the tiles in pixels

required
tiles_width int

the width of the map in tiles

required
tiles_height int

the height of the map in tiles

required
Source code in pizzoo\game.py
def __init__(self, tile_size, tiles_width, tiles_height):
	'''
	Creates a new map object. A map is a grid of tiles that can be filled with sprites.

	Args:
		tile_size (int): the size of the tiles in pixels
		tiles_width (int): the width of the map in tiles
		tiles_height (int): the height of the map in tiles
	'''
	self.tile_size = tile_size
	self.tiles_width = tiles_width
	self.tiles_height = tiles_height
	# create tiles by value not by reference
	self.tiles = [[None for x in range(tiles_width)] for y in range(tiles_height)]
	self.map_image = None
	self.map_memo = {}

add_tile

add_tile(tile, x, y, span=(0, 0))

Adds a tile to the map at a specific position with a span.

Parameters:

Name Type Description Default
tile Sprite

the tile to add

required
x int

the x index of the tile

required
y int

the y index of the tile

required
span tuple

a tuple with the width and height of the tile in tiles

(0, 0)
Source code in pizzoo\game.py
def add_tile(self, tile, x, y, span=(0, 0)):
	'''
	Adds a tile to the map at a specific position with a span.

	Args:
		tile (Sprite): the tile to add
		x (int): the x index of the tile
		y (int): the y index of the tile
		span (tuple): a tuple with the width and height of the tile in tiles
	'''
	for i in range(span[0]):
		for j in range(span[1]):
			self.add_tile_at(Sprite(tile.frame_src, current_frame=tile.current_frame, base_path=tile.base_path, offset=(i * self.tile_size, j * self.tile_size, self.tile_size), z_index=1), x + i, y + j)
	self.generate_map_image()

add_tile_at

add_tile_at(tile, x, y)

Adds a tile to the map at a specific position.

Parameters:

Name Type Description Default
tile Sprite

the tile to add

required
x int

the x index of the tile

required
y int

the y index of the tile

required
Source code in pizzoo\game.py
def add_tile_at(self, tile, x, y):
	'''
	Adds a tile to the map at a specific position.

	Args:
		tile (Sprite): the tile to add
		x (int): the x index of the tile
		y (int): the y index of the tile
	'''
	if self.tiles[y][x] is None:
		self.tiles[y][x] = []
	self.tiles[y][x].append(tile)
	self.tiles[y][x].sort(key=lambda x: x.z_index)

draw

draw(pizzoo, camera)

Draws the map on the screen using a cropped image of the map image and a memoization based on the camera position

Parameters:

Name Type Description Default
pizzoo Pizzoo

the pizzoo object

required
camera Camera

the camera object

required
Source code in pizzoo\game.py
def draw(self, pizzoo, camera):
	'''
	Draws the map on the screen using a cropped image of the map image and a memoization based on the camera position

	Args:
		pizzoo (Pizzoo): the pizzoo object
		camera (Camera): the camera object
	'''
	if self.map_image is None:
		return
	# check map memo
	result = None
	index = (camera.x, camera.y, camera.width, camera.height)
	if not index in self.map_memo:
		result = self.map_image.crop((camera.x, camera.y, camera.x + camera.width, camera.y + camera.height))
		self.map_memo[index] = result
	else:
		result = self.map_memo[index]
	pizzoo.draw_image(result, (0, 0))

fill

fill(tile)

Fills the entire map with a single tile.

Parameters:

Name Type Description Default
tile Sprite

the tile to fill the map with

required
Source code in pizzoo\game.py
def fill(self, tile):
	'''
	Fills the entire map with a single tile.

	Args:
		tile (Sprite): the tile to fill the map with
	'''
	for y in range(self.tiles_height):
		for x in range(self.tiles_width):
			if self.tiles[y][x] is None:
				self.tiles[y][x] = []
			self.tiles[y][x].append(tile)
			self.tiles[y][x].sort(key=lambda x: x.z_index)
	self.generate_map_image()

generate_map_image

generate_map_image()

Generates a map image based on the tiles in the map. This static image is used to render the map on the screen and is memoized for performance.

Source code in pizzoo\game.py
def generate_map_image(self):
	'''
	Generates a map image based on the tiles in the map. This static image is used to render the map on the screen and is memoized for performance.	
	'''
	self.map_memo = {}
	self.map_image = Image.new('RGB', (self.tiles_width * self.tile_size, self.tiles_height * self.tile_size))
	for y in range(self.tiles_height):
		for x in range(self.tiles_width):
			if self.tiles[y][x] is not None:
				for tile in self.tiles[y][x]:
					tile_x, tile_y = tile_to_coords(self.tile_size, x, y)
					self.map_image.paste(tile.get_frame(), (tile_x, tile_y))
	return self.map_image

Path

Path(nodes, current=0, tile_size=1, closed=False)
Source code in pizzoo\game.py
def __init__(self, nodes, current=0, tile_size=1, closed=False):
	self.nodes = nodes
	self.closed = closed
	self.tile_size = tile_size
	self.current = current
	self.has_ended = False

next

next(x, y, coords=False)

Returns the next node in the path, if the path is closed, it will return to the first node when it reaches the end.

Parameters:

Name Type Description Default
x int

the x coordinate of the object that is following the path

required
y int

the y coordinate of the object that is following the path

required
coords bool

if True, x and y will be treated as coordinates and result will be a tuple of coordinates, otherwise it will return a tuple of tile indexes

False

Returns:

Type Description

Next node (tuple): a tuple with the x and y indexes of the next node in the path

Source code in pizzoo\game.py
def next(self, x, y, coords=False):
	'''
	Returns the next node in the path, if the path is closed, it will return to the first node when it reaches the end.

	Args:
		x (int): the x coordinate of the object that is following the path
		y (int): the y coordinate of the object that is following the path
		coords (bool): if True, x and y will be treated as coordinates and result will be a tuple of coordinates, otherwise it will return a tuple of tile indexes

	Returns:
		Next node (tuple): a tuple with the x and y indexes of the next node in the path
	'''
	if self.has_ended:
		return None
	if coords:
		x, y = coords_to_tile(self.tile_size, x, y)
	if self.current >= len(self.nodes):
		if self.closed:
			self.current = 0
		else:
			self.has_ended = True
			return None
	if self.nodes[self.current][0] == x and self.nodes[self.current][1] == y:
		self.current += 1
		if self.current >= len(self.nodes):
			if self.closed:
				self.current = 0
			else:
				self.has_ended = True
				return None
	return self.nodes[self.current] if not coords else tile_to_coords(self.tile_size, self.nodes[self.current][0], self.nodes[self.current][1])		

prev

prev(x, y, coords=False)

Returns the previous node in the path, if the path is closed, it will return to the last node when it reaches the beginning.

Parameters:

Name Type Description Default
x int

the x coordinate of the object that is following the path

required
y int

the y coordinate of the object that is following the path

required
coords bool

if True, x and y will be treated as coordinates and result will be a tuple of coordinates, otherwise it will return a tuple of tile indexes

False

Returns:

Type Description

Previous node (tuple): a tuple with the x and y indexes of the previous node in the path

Source code in pizzoo\game.py
def prev(self, x, y, coords=False):
	'''
	Returns the previous node in the path, if the path is closed, it will return to the last node when it reaches the beginning.

	Args:
		x (int): the x coordinate of the object that is following the path
		y (int): the y coordinate of the object that is following the path
		coords (bool): if True, x and y will be treated as coordinates and result will be a tuple of coordinates, otherwise it will return a tuple of tile indexes

	Returns:
		Previous node (tuple): a tuple with the x and y indexes of the previous node in the path
	'''
	if self.has_ended:
		return None
	if coords:
		x, y = coords_to_tile(self.tile_size, x, y)
	if self.current < 0:
		if self.closed:
			self.current = len(self.nodes) - 1
		else:
			self.has_ended = True
			return None
	if self.nodes[self.current][0] == x and self.nodes[self.current][1] == y:
		self.current -= 1
		if self.current < 0:
			if self.closed:
				self.current = len(self.nodes) - 1
			else:
				self.has_ended = True
				return None
	return self.nodes[self.current] if not coords else tile_to_coords(self.tile_size, self.nodes[self.current][0], self.nodes[self.current][1])

PizzooGame

PizzooGame(pizzoo, frame_limit=5, dev=False)

Creates a new game object. A game is a container for maps, instances, cameras, and timers. It also handles the game loop and the rendering of the game.

Parameters:

Name Type Description Default
pizzoo Pizzoo

the pizzoo object

required
frame_limit int

the frame limit of the game

5
dev bool

if True, the game will print the FPS on the console

False
Source code in pizzoo\game.py
def __init__(self, pizzoo, frame_limit=5, dev=False):
	'''
	Creates a new game object. A game is a container for maps, instances, cameras, and timers. It also handles the game loop and the rendering of the game.

	Args:
		pizzoo (Pizzoo): the pizzoo object
		frame_limit (int): the frame limit of the game
		dev (bool): if True, the game will print the FPS on the console
	'''
	from pynput import keyboard
	self.pizzoo = pizzoo
	self.listener = keyboard.Listener(on_press=self.on_press)
	self.running = False
	self.frame_limit = frame_limit
	self.step_time = 1 / self.frame_limit
	self.timers = {}
	self.instances = []
	# maps is an array of maps, an every map is a multidimensional array of tiles (like a matrix)
	self.maps = []
	self.current_map = 0
	self.camera = Camera(self, 0, 0)
	self.dev = dev

add_instance

add_instance(instance)

Adds an instance to the game, the instances are sorted by the z_index attribute.

Parameters:

Name Type Description Default
instance Actor

the instance to add

required
Source code in pizzoo\game.py
def add_instance(self, instance):
	'''
	Adds an instance to the game, the instances are sorted by the z_index attribute.

	Args:
		instance (Actor): the instance to add
	'''
	self.instances.append(instance)
	self.instances.sort(key=lambda x: x.z_index)

check_collision_point

check_collision_point(x, y, object_x, object_y, size)

Checks if a point is inside a bounding box.

Parameters:

Name Type Description Default
x int

the x coordinate of the point

required
y int

the y coordinate of the point

required
object_x int

the x coordinate of the bounding box

required
object_y int

the y coordinate of the bounding box

required
size int

the size of the bounding box

required

Returns:

Name Type Description
Collision bool

True if the point is inside the bounding box, False otherwise

Source code in pizzoo\game.py
def check_collision_point(self, x, y, object_x, object_y, size):
	'''
	Checks if a point is inside a bounding box.

	Args:
		x (int): the x coordinate of the point
		y (int): the y coordinate of the point
		object_x (int): the x coordinate of the bounding box
		object_y (int): the y coordinate of the bounding box
		size (int): the size of the bounding box

	Returns:
		Collision (bool): True if the point is inside the bounding box, False otherwise
	'''
	if x >= object_x and x <= object_x + size:
		if y >= object_y and y <= object_y + size:
			return True
	return False

check_collisions

check_collisions(target, class_names=None)

Checks the collisions of an object with other objects in the game.

Parameters:

Name Type Description Default
target Actor

the object to check the collisions with

required
class_names (list, str)

a list of class names or a single class name to filter the collisions

None

Returns:

Type Description

Collision list (list): a list of objects that collided with the target

Source code in pizzoo\game.py
def check_collisions(self, target, class_names=None):
	'''
	Checks the collisions of an object with other objects in the game.

	Args:
		target (Actor): the object to check the collisions with
		class_names (list, str): a list of class names or a single class name to filter the collisions

	Returns:
		Collision list (list): a list of objects that collided with the target
	'''
	if class_names is None:
		filtered = self.instances
	else:
		if type(class_names) != list:
			class_names = [class_names]
		filtered = [instance for instance in self.instances if instance.solid and instance.__class__.__name__ in class_names]
	collision_list = []
	for instance in filtered:
		if self.collision(target, instance):
			collision_list.append(instance)
	return collision_list

collision

collision(source, target)

Checks if two objects are colliding.

Parameters:

Name Type Description Default
source Actor

the first object

required
target Actor

the second object

required

Returns:

Name Type Description
Collision bool

True if the objects are colliding, False otherwise

Source code in pizzoo\game.py
def collision(self, source, target):
	'''
	Checks if two objects are colliding.

	Args:
		source (Actor): the first object
		target (Actor): the second object

	Returns:
		Collision (bool): True if the objects are colliding, False otherwise
	'''
	if source.x >= target.x and source.x <= target.x + target.bounding_box_size[0]:
		if source.y >= target.y and source.y <= target.y + target.bounding_box_size[1]:
			return True
	return False

create_camera

create_camera(x=0, y=0, center_on=None)

Creates a new camera object.

Parameters:

Name Type Description Default
x int

the x coordinate of the camera

0
y int

the y coordinate of the camera

0
center_on Actor

the object to center the camera on

None
Source code in pizzoo\game.py
def create_camera(self, x=0, y=0, center_on=None):
	'''
	Creates a new camera object.

	Args:
		x (int): the x coordinate of the camera
		y (int): the y coordinate of the camera
		center_on (Actor): the object to center the camera on
	'''
	self.camera = Camera(self, x, y, center_on)

create_map

create_map(tile_size, tiles_width, tiles_height)

Creates a new map with a tile size and a width and height in tiles

Parameters:

Name Type Description Default
tile_size int

the size of the tiles in pixels

required
tiles_width int

the width of the map in tiles

required
tiles_height int

the height of the map in tiles

required

Returns:

Name Type Description
Map Map

the map object

Source code in pizzoo\game.py
def create_map(self, tile_size, tiles_width, tiles_height):
	'''
	Creates a new map with a tile size and a width and height in tiles

	Args:
		tile_size (int): the size of the tiles in pixels
		tiles_width (int): the width of the map in tiles
		tiles_height (int): the height of the map in tiles

	Returns:
		Map (Map): the map object
	'''
	return Map(tile_size, tiles_width, tiles_height)

draw

draw()

Draws the game on the screen, rendering the maps, instances, and the UI.

Source code in pizzoo\game.py
def draw(self):
	'''
	Draws the game on the screen, rendering the maps, instances, and the UI.
	'''
	self.pizzoo.cls()
	self.maps[self.current_map].draw(self.pizzoo, self.camera)
	visible_instances = [instance for instance in self.instances if instance.visible]
	'''Render instances relative to the camera'''
	for instance in visible_instances:
		self.pizzoo.draw_image(instance.sprite.get_frame(), (int(instance.x - self.camera.x), int(instance.y - self.camera.y)))

draw_ui

draw_ui()

Draws the UI on the screen, rendering the UI elements.

Source code in pizzoo\game.py
def draw_ui(self):
	'''
	Draws the UI on the screen, rendering the UI elements.
	'''
	pass

on_press

on_press(key)

Handles the key press events and forwards them to the instances.

Parameters:

Name Type Description Default
key str

the key that was pressed

required
Source code in pizzoo\game.py
def on_press(self, key):
	'''
	Handles the key press events and forwards them to the instances.

	Args:
		key (str): the key that was pressed
	'''
	key = key.char if hasattr(key, 'char') else key
	try:
		for instance in self.instances:
			instance.on_press(key)
	except AttributeError as e:
		print(e) 
		pass

remove_instance

remove_instance(instance)

Removes an instance from the game.

Parameters:

Name Type Description Default
instance Actor

the instance to remove

required

Returns:

Name Type Description
Instance Actor

the removed instance

Source code in pizzoo\game.py
def remove_instance(self, instance):
	'''
	Removes an instance from the game.

	Args:
		instance (Actor): the instance to remove

	Returns:
		Instance (Actor): the removed instance
	'''
	if instance not in self.instances:
		return
	self.instances.remove(instance)
	self.instances.sort(key=lambda x: x.z_index)
	return instance

remove_timer

remove_timer(name)

Removes a timer from the game.

Parameters:

Name Type Description Default
name str

the name of the timer to remove

required

Returns:

Name Type Description
Timer dict

the removed timer

Source code in pizzoo\game.py
def remove_timer(self, name):
	'''
	Removes a timer from the game.

	Args:
		name (str): the name of the timer to remove

	Returns:
		Timer (dict): the removed timer
	'''
	if name not in self.timers:
		return
	selected = self.timers[name]
	del self.timers[name]
	return selected

run

run()

Runs the game loop, updating the game state and rendering the game on the screen.

Source code in pizzoo\game.py
def run(self):
	'''
	Runs the game loop, updating the game state and rendering the game on the screen.
	'''
	prev_time = perf_counter()
	current_time = prev_time
	count = 0
	accum = 0
	while self.running:
		prev_time = current_time
		current_time = perf_counter()
		dt = current_time - prev_time
		self.run_task()
		if self.dev:
			accum += dt
			count += 1
			if accum >= 1.0:
				accum -= 1.0
				print(f'FPS: {count}')
				count = 0
		while perf_counter() < (current_time + self.step_time):
			pass

start

start()

Starts the game loop and the keyboard listener.

Source code in pizzoo\game.py
def start(self):
	'''
	Starts the game loop and the keyboard listener.
	'''
	self.pizzoo.switch()
	self.listener.start()
	self.running = True
	self.run()

step

step()

Updates the game state, moving the instances, checking the collisions, and updating the camera.

Source code in pizzoo\game.py
def step(self):
	'''
	Updates the game state, moving the instances, checking the collisions, and updating the camera.
	'''
	for instance in self.instances:
		instance.step()
		instance.collisions()
	self.camera.step()

stop

stop()

Stops the game loop and the keyboard listener.

Source code in pizzoo\game.py
def stop(self):
	'''
	Stops the game loop and the keyboard listener.
	'''
	self.running = False
	self.listener.stop()
	self.pizzoo.switch(False)

timer

timer(name, callback, interval, repeat=False, force=False)

Creates a new timer with a name, a callback function, an interval in seconds, and a repeat flag.

Parameters:

Name Type Description Default
name str

the name of the timer

required
callback function

the callback function to execute

required
interval float

the interval in seconds

required
repeat bool

if True, the timer will repeat

False
force bool

if True, the timer will be created even if it already exists

False
Source code in pizzoo\game.py
def timer(self, name, callback, interval, repeat=False, force=False):
	'''
	Creates a new timer with a name, a callback function, an interval in seconds, and a repeat flag.

	Args:
		name (str): the name of the timer
		callback (function): the callback function to execute
		interval (float): the interval in seconds
		repeat (bool): if True, the timer will repeat
		force (bool): if True, the timer will be created even if it already exists
	'''
	if name in self.timers and not force:
		return
	self.timers[name] = {
		'interval': interval,
		'callback': callback,
		'last': time(),
		'repeat': repeat
	}

timer_exists

timer_exists(name)

Checks if a timer exists.

Parameters:

Name Type Description Default
name str

the name of the timer

required

Returns:

Name Type Description
Exists bool

True if the timer exists, False otherwise

Source code in pizzoo\game.py
def timer_exists(self, name):
	'''
	Checks if a timer exists.

	Args:
		name (str): the name of the timer

	Returns:
		Exists (bool): True if the timer exists, False otherwise
	'''
	return name in self.timers

Sprite

Sprite(frame_src, base_path=None, current_frame=0, z_index=0, offset=(0, 0, 0))

Creates a new sprite object. A sprite is a sequence of frames that can be rendered on the screen.

Parameters:

Name Type Description Default
frame_src (str, list)

Can be a list of paths to images or an iterable of images (like a gif)

required
base_path str

the base path to the image files

None
current_frame int

the current frame of the sprite

0
z_index int

the z index of the sprite

0
offset tuple

a tuple with the x, y, and size of the offset to crop the image

(0, 0, 0)
Source code in pizzoo\game.py
def __init__(self, frame_src, base_path=None, current_frame=0, z_index=0, offset=(0, 0, 0)):
	'''
	Creates a new sprite object. A sprite is a sequence of frames that can be rendered on the screen.

	Args:
		frame_src (str, list): Can be a list of paths to images or an iterable of images (like a gif)
		base_path (str): the base path to the image files
		current_frame (int): the current frame of the sprite
		z_index (int): the z index of the sprite
		offset (tuple): a tuple with the x, y, and size of the offset to crop the image
	'''
	self.base_path = base_path
	self.frame_src = frame_src
	self.frames = self._create_frames(frame_src, offset, base_path)
	self.current_frame = current_frame
	self.z_index = z_index

get_frame

get_frame(index=None)

Returns a frame based on an index.

Parameters:

Name Type Description Default
index int

the index of the frame to return

None

Returns:

Name Type Description
Frame Image

the frame

Source code in pizzoo\game.py
def get_frame(self, index=None):
	'''
	Returns a frame based on an index.

	Args:
		index (int): the index of the frame to return

	Returns:
		Frame (PIL.Image): the frame
	'''
	if index is not None:
		return self.frames[index]
	return self.frames[self.current_frame]

next_frame

next_frame()

Sets the next frame as the current frame.

Source code in pizzoo\game.py
def next_frame(self):
	'''
	Sets the next frame as the current frame.
	'''
	if self.current_frame + 1 >= len(self.frames):
		self.current_frame = 0
	else:
		self.current_frame += 1

set_frame

set_frame(index)

Sets a frame as the current frame.

Parameters:

Name Type Description Default
index int

the index of the frame to set as the current frame

required
Source code in pizzoo\game.py
def set_frame(self, index):
	'''
	Sets a frame as the current frame.

	Args:
		index (int): the index of the frame to set as the current frame
	'''
	self.current_frame = index

size

size()

Returns the size of the current frame.

Returns:

Name Type Description
Size tuple

a tuple with the width and height of the current frame

Source code in pizzoo\game.py
def size(self):
	'''
	Returns the size of the current frame.

	Returns:
		Size (tuple): a tuple with the width and height of the current frame
	'''
	return self.frames[self.current_frame].size

coords_to_tile

coords_to_tile(tile_size, x, y, use_ceil=False)

Returns the indexes of a tile in the map based on the tile size and the coordinates.

Parameters:

Name Type Description Default
tile_size int

the size of the tile in pixels

required
x int

the x coordinate of the tile

required
y int

the y coordinate of the tile

required
use_ceil bool

if True, the indexes will be rounded up, otherwise they will be rounded down

False

Returns:

Type Description

Tile indexes (tuple): a tuple with the x and y indexes of the tile

Source code in pizzoo\game.py
def coords_to_tile(tile_size, x, y, use_ceil=False):
	'''
	Returns the indexes of a tile in the map based on the tile size and the coordinates.

	Args:
		tile_size (int): the size of the tile in pixels
		x (int): the x coordinate of the tile
		y (int): the y coordinate of the tile
		use_ceil (bool): if True, the indexes will be rounded up, otherwise they will be rounded down

	Returns:
		Tile indexes (tuple): a tuple with the x and y indexes of the tile
	'''
	round_method = ceil if use_ceil else floor
	return (round_method(x / tile_size), round_method(y / tile_size))

distance

distance(a, b)

Returns the distance between two points in a 2D space.

Parameters:

Name Type Description Default
a tuple

a tuple with the x and y coordinates of the first point

required
b tuple

a tuple with the x and y coordinates of the second point

required

Returns:

Name Type Description
Distance float

the distance between the two points

Source code in pizzoo\game.py
def distance(a, b):
	'''
	Returns the distance between two points in a 2D space.

	Args:
		a (tuple): a tuple with the x and y coordinates of the first point
		b (tuple): a tuple with the x and y coordinates of the second point

	Returns:
		Distance (float): the distance between the two points
	'''
	return ((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2) ** (1 / 2)

tile_to_coords

tile_to_coords(tile_size, tile_x, tile_y)

Returns the coordinates of a tile in the map based on the tile size and the tile indexes.

Parameters:

Name Type Description Default
tile_size int

the size of the tile in pixels

required
tile_x int

the x index of the tile

required
tile_y int

the y index of the tile

required

Returns:

Name Type Description
Coordinates tuple

a tuple with the x and y coordinates of the tile

Source code in pizzoo\game.py
def tile_to_coords(tile_size, tile_x, tile_y):
	'''
	Returns the coordinates of a tile in the map based on the tile size and the tile indexes.

	Args:
		tile_size (int): the size of the tile in pixels
		tile_x (int): the x index of the tile
		tile_y (int): the y index of the tile

	Returns:
		Coordinates (tuple): a tuple with the x and y coordinates of the tile
	'''
	return (tile_x * tile_size, tile_y * tile_size)