Skip to content

xnano.art

xnano.art

xnano.art

What is seen: pixel art written as text, worlds seen through a camera, single pixels and decoded images. Images need the optional image extra: pip install "xnano[image]".

To paint pixels and images into a Region, draw an image with Region.draw_image on a region viewed as Region.half_blocks (two pixels per cell) or Region.braille (eight dots per cell). Region.pixel_for_cell and Region.cell_for_pixel convert between the two coordinate systems.

Classes:

  • Image –

    An image and how it is shown: what Screen.write takes

  • Pixel –

    One cell (or one dot, at half-block and braille resolution) of a region.

  • Art –

    Pixel art, and a world that holds other art.

  • Camera –

    Which part of a world is on screen.

Functions:

  • load_image –

    Load an image or an animation from a file path or from bytes.

  • pixel_art –

    Build pixel art from text, a picture, bytes or nothing (does not draw).

Attributes:

PixelPreset module-attribute

PixelPreset: TypeAlias = Literal['block', 'half_top', 'half_bottom', 'shade_light', 'shade_medium', 'shade_dark', 'braille', 'circle', 'circle_outline', 'dot', 'diamond', 'star', 'line_horizontal', 'line_vertical', 'corner_top_left_rounded', 'corner_top_right_rounded', 'corner_bottom_left_rounded', 'corner_bottom_right_rounded', 'corner_top_left_square', 'corner_top_right_square', 'corner_bottom_left_square', 'corner_bottom_right_square', 'arrow_up', 'arrow_down', 'arrow_left', 'arrow_right', 'check', 'cross']

The names of the characters Pixel knows: Pixel('diamond') draws ◆.

ImageFit module-attribute

ImageFit: TypeAlias = Literal['contain', 'cover', 'stretch', 'crop', 'smart']

How a picture sits in a box of a given width and height.

'contain' fits it entirely inside the box. 'cover' fills the box and crops what overflows. 'stretch' fills the box exactly. 'crop' never resizes it: it is centered, cropped or padded. 'smart' is 'cover' when the aspect ratios nearly match and 'contain' otherwise.

ResamplingFilter module-attribute

ResamplingFilter: TypeAlias = Literal['nearest', 'bilinear', 'catmull_rom', 'lanczos3']

How pixels are blended when a picture is resized.

'nearest' keeps hard pixel edges, which suits a small picture that is enlarged. 'bilinear', 'catmull_rom' and 'lanczos3' smooth the result, which suits photographs.

Image dataclass

Image(source: TerminalImage | PathLike[str] | str | bytes, *, x: Axis | None = None, y: Axis | None = None, width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, fit: ImageFit | None = None, resampling_filter: ResamplingFilter | None = None, background: ColorValue = (0, 0, 0), speed: float = 1.0, symbol: str | None = None)

An image and how it is shown: what Screen.write takes to put a picture on the canvas.

Make one from the path of an image file, its bytes, or a TerminalImage. A file is read once, here, where you can see it; write never takes a path. The placement values are what write uses when it is not given its own. An image sized by a percentage (or not sized at all) is converted again whenever the canvas is resized, so it always fits; give it a number, or lock=True, and it keeps its size.

A picture with transparent pixels (a PNG with an alpha channel, for example) lets what is below it on the canvas show through them. Pixels that are only partly transparent blend with background, and a cell with one transparent half and one drawn half shows the terminal's default color in the transparent half.

Maps to xnano_image.TerminalImage.

Attributes:

  • decoded (TerminalImage) –

    The decoded picture, a TerminalImage.

  • x (Axis | None) –

    The column of the left edge, or None for the top-left corner.

  • y (Axis | None) –

    The row of the top edge, or None.

  • width (Axis | None) –

    The width: cells, a percentage, an expression, or None for the picture's own.

  • height (Axis | None) –

    The height, in the same forms.

  • layer (int) –

    Content with a higher layer is drawn over content with a lower one.

  • lock (bool) –

    Whether the image keeps the size it was shown at when the canvas is resized.

  • fit (ImageFit | None) –

    How the picture sits in a box of width by height: 'contain' (the default), 'cover', 'stretch', 'crop' or 'smart'.

  • resampling_filter (ResamplingFilter | None) –

    How pixels are blended when it is resized. By default a small picture that is enlarged keeps hard pixel edges ('nearest') and any other is smoothed ('lanczos3').

  • background (tuple[int, int, int]) –

    The color of the margins around a picture with no transparent pixel, and the color its partly transparent pixels are blended with. Fully transparent pixels let the canvas show through.

  • symbol (str | None) –

    The name the image is registered under in symbols, or None.

Examples:

import xnano
from xnano_image import TerminalImage

picture = xnano.Image(TerminalImage.from_rgba(2, 2, bytes([255, 0, 0, 255]) * 4), width=8)
with xnano.new(width=20, height=6) as canvas:
    canvas.screen.write(picture, x='center')
# xnano.Image('photo.png', width='100%') loads a file, and refits when the window resizes.

Load an image and set how it is shown.

Parameters:

  • source (TerminalImage | PathLike[str] | str | bytes) –

    The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one, or an image. An animated file plays on the canvas's clock.

  • x (Axis | None, default: None ) –

    The column of the left edge: cells, a percentage, a word such as 'center', an expression or a range. See Axis.

  • y (Axis | None, default: None ) –

    The row of the top edge, in the same forms.

  • width (Axis | None, default: None ) –

    The width, in the same forms; the picture's own when None.

  • height (Axis | None, default: None ) –

    The height, in the same forms.

  • layer (int, default: 0 ) –

    Content with a higher layer is drawn over content with a lower one.

  • lock (bool, default: False ) –

    Keep the size the image has when it is added, whatever the canvas does.

  • fit (ImageFit | None, default: None ) –

    How the picture sits in a box of width by height.

  • resampling_filter (ResamplingFilter | None, default: None ) –

    How pixels are blended when it is resized.

  • background (ColorValue, default: (0, 0, 0) ) –

    The color of the margins around a picture with no transparent pixel and the color partly transparent pixels are blended with, as a color name, a hex string, an (r, g, b) tuple or a Color. Fully transparent pixels let the canvas show through.

  • speed (float, default: 1.0 ) –

    How fast an animated image plays: 2.0 is twice as fast.

  • symbol (str | None, default: None ) –

    A name to register the image under in symbols.

Raises:

  • ImportError –

    xnano-image is not installed. Install it with pip install "xnano[image]".

  • TypeError –

    source is not a path, bytes or an image.

  • FileNotFoundError –

    source is a path with no file at it.

  • ValueError –

    symbol cannot be a symbol name, or another kind of value already has it.

Source code in xnano/art/_images.py
def __init__(
    self,
    source: TerminalImage | os.PathLike[str] | str | bytes,
    *,
    x: Axis | None = None,
    y: Axis | None = None,
    width: Axis | None = None,
    height: Axis | None = None,
    layer: int = 0,
    lock: bool = False,
    fit: ImageFit | None = None,
    resampling_filter: ResamplingFilter | None = None,
    background: ColorValue = (0, 0, 0),
    speed: float = 1.0,
    symbol: str | None = None,
) -> None:
    """
    Load an image and set how it is shown.

    Args:
        source: The path of an image file (PNG, JPEG, GIF, WebP or XNI), the bytes of one,
            or an image. An animated file plays on the canvas's clock.
        x: The column of the left edge: cells, a percentage, a word such as ``'center'``, an
            expression or a range. See [`Axis`][xnano.layout.Axis].
        y: The row of the top edge, in the same forms.
        width: The width, in the same forms; the picture's own when ``None``.
        height: The height, in the same forms.
        layer: Content with a higher layer is drawn over content with a lower one.
        lock: Keep the size the image has when it is added, whatever the canvas does.
        fit: How the picture sits in a box of ``width`` by ``height``.
        resampling_filter: How pixels are blended when it is resized.
        background: The color of the margins around a picture with no transparent pixel
            and the color partly transparent pixels are blended with, as a color name, a
            hex string, an ``(r, g, b)`` tuple or a [`Color`][xnano_core.Color]. Fully
            transparent pixels let the canvas show through.
        speed: How fast an animated image plays: ``2.0`` is twice as fast.
        symbol: A name to register the image under in [`symbols`][xnano.symbols].

    Raises:
        ImportError: ``xnano-image`` is not installed. Install it with
            ``pip install "xnano[image]"``.
        TypeError: ``source`` is not a path, bytes or an image.
        FileNotFoundError: ``source`` is a path with no file at it.
        ValueError: ``symbol`` cannot be a symbol name, or another kind of value
            already has it.
    """
    if is_image(source):
        image = cast('TerminalImage', source)
    else:
        module = require('image', needed_for='xnano.Image')
        if isinstance(source, bytes):
            image = module.TerminalImage.from_bytes(source)
        elif isinstance(source, (str, os.PathLike)):
            path = pathlib.Path(source)
            if not path.is_file():
                raise FileNotFoundError(
                    f'Image could not load {str(path)!r}, because no image file exists '
                    f'there. Check the path, or pass the bytes of the image.'
                )
            image = module.TerminalImage.open(path)
        else:
            raise TypeError(
                f'Image needs the path of an image file, the bytes of an image or an '
                f'image, but got {type(source).__name__}. Pass Image("picture.png").'
            )
    if speed != 1.0:
        image = image.with_speed(speed)
    for name, value in (
        ('decoded', image),
        ('x', x),
        ('y', y),
        ('width', width),
        ('height', height),
        ('layer', layer),
        ('lock', lock),
        ('fit', fit),
        ('resampling_filter', resampling_filter),
        ('background', to_rgb(background)),
        ('symbol', symbol),
    ):
        object.__setattr__(self, name, value)
    if symbol is not None:
        symbols.register(symbol, self)

decoded instance-attribute

decoded: TerminalImage

The decoded picture, a TerminalImage.

x instance-attribute

x: Axis | None

The column of the left edge, or None for the top-left corner.

y instance-attribute

y: Axis | None

The row of the top edge, or None.

width instance-attribute

width: Axis | None

The width: cells, a percentage, an expression, or None for the picture's own.

height instance-attribute

height: Axis | None

The height, in the same forms.

layer instance-attribute

layer: int

Content with a higher layer is drawn over content with a lower one.

lock instance-attribute

lock: bool

Whether the image keeps the size it was shown at when the canvas is resized.

fit instance-attribute

fit: ImageFit | None

How the picture sits in a box of width by height, or None for the default.

resampling_filter instance-attribute

resampling_filter: ResamplingFilter | None

How pixels are blended when it is resized, or None to choose by scale.

background instance-attribute

background: tuple[int, int, int]

The color of margins and partly transparent pixels, as (red, green, blue).

symbol instance-attribute

symbol: str | None

The name the image is registered under in symbols, or None.

Pixel dataclass

Pixel(preset_or_character: PixelPreset | str = 'block', *, foreground: ColorValue | None = None, background: ColorValue | None = None, symbol: str | None = None)

One cell (or one dot, at half-block and braille resolution) of a region.

The first argument is a preset name such as 'diamond', the name of a registered symbol, or a single character that is drawn as it is. A pixel is a value: it compares by its fields, and region[x, y] returns one and accepts one.

Parameters:

  • preset_or_character (PixelPreset | str, default: 'block' ) –

    A PixelPreset, the name of a registered symbol, or one character.

  • foreground (ColorValue | None, default: None ) –

    The color of the character.

  • background (ColorValue | None, default: None ) –

    The color behind the character.

  • symbol (str | None, default: None ) –

    A name to register this pixel under, so that Pixel('wall') finds it later. The name takes two characters or more; see register.

Attributes:

  • character (str) –

    The glyph drawn in the cell or dot.

  • foreground (ColorValue | None) –

    The color of the glyph, or None for the cell's own.

  • background (ColorValue | None) –

    The color behind the glyph, or None for the cell's own.

  • symbol (str | None) –

    The registered symbol name, or None.

Raises:

  • ValueError –

    The name is not a preset or a registered symbol (the message lists both and the closest names first), or the character is empty.

Examples:

import xnano
from xnano import Pixel

diamond = Pixel('diamond', foreground='red')
assert diamond.character == '◆'
assert Pixel('x').character == 'x'

with xnano.new(width=4, height=1) as canvas:
    canvas.screen.region[1, 0] = diamond
    assert canvas.screen.region[1, 0].character == '◆'

Make a pixel from a preset, a symbol name or a character.

Parameters:

  • preset_or_character (PixelPreset | str, default: 'block' ) –

    A preset name, a registered symbol name or one character.

  • foreground (ColorValue | None, default: None ) –

    The color of the character.

  • background (ColorValue | None, default: None ) –

    The color behind the character.

  • symbol (str | None, default: None ) –

    A name to register this pixel under.

Methods:

  • cell –

    Return the core cell that draws this pixel.

  • __str__ –

    Return the character of the pixel, so print(pixel) shows what it draws.

  • __xnano_write__ –

    Return a buffer of one cell that shows the pixel.

Source code in xnano/art/_pixels.py
def __init__(
    self,
    preset_or_character: PixelPreset | str = 'block',
    *,
    foreground: ColorValue | None = None,
    background: ColorValue | None = None,
    symbol: str | None = None,
) -> None:
    """
    Make a pixel from a preset, a symbol name or a character.

    Args:
        preset_or_character: A preset name, a registered symbol name or one character.
        foreground: The color of the character.
        background: The color behind the character.
        symbol: A name to register this pixel under.
    """
    if not isinstance(preset_or_character, str) or not preset_or_character:
        raise ValueError(
            f'A pixel is made from a preset name, a symbol name or one character, but '
            f'got {preset_or_character!r}. Try Pixel("block") or Pixel("#").'
        )
    for color_name, color in (('foreground', foreground), ('background', background)):
        if color is None:
            continue
        try:
            if color_name == 'foreground':
                _core.Cell(' ', foreground=color)
            else:
                _core.Cell(' ', background=color)
        except (TypeError, ValueError) as error:
            raise type(error)(
                f'The {color_name} of a pixel must be a color, but was {color!r}. Use a '
                f'name such as "red", a hex string such as "#ff8800", an (r, g, b) '
                f'tuple or a Color.'
            ) from error
    name = preset_or_character
    known_symbol: str | None = None
    if len(name) == 1:
        if unicodedata.category(name) == 'Cc':
            raise ValueError(
                f'A pixel cannot be the control character {name!r}, because a cell '
                f'cannot hold one. Pass a printable character such as Pixel("#"), or a '
                f'preset such as Pixel("block").'
            )
        character = name
    elif name in _PRESET_CHARACTERS:
        character = _PRESET_CHARACTERS[name]
    elif name in symbols.names(kind=Pixel):
        registered = symbols.lookup(name, kind=Pixel)
        character = registered.character
        foreground = registered.foreground if foreground is None else foreground
        background = registered.background if background is None else background
        known_symbol = name
    else:
        raise _unknown_name_error(name)
    object.__setattr__(self, 'character', character)
    object.__setattr__(self, 'foreground', foreground)
    object.__setattr__(self, 'background', background)
    object.__setattr__(self, 'symbol', symbol if symbol is not None else known_symbol)
    object.__setattr__(self, '_cell', None)
    if symbol is not None:
        symbols.register(symbol, self)

character instance-attribute

character: str

The glyph drawn in the cell or dot.

foreground instance-attribute

foreground: ColorValue | None

The color of the glyph, or None for the cell's own.

background instance-attribute

background: ColorValue | None

The color behind the glyph, or None for the cell's own.

symbol instance-attribute

symbol: str | None

The registered symbol name, or None.

cell

cell() -> Cell

Return the core cell that draws this pixel.

The cell is built once and kept, so writing the same pixel many times is cheap.

Source code in xnano/art/_pixels.py
def cell(self) -> _core.Cell:
    """
    Return the core cell that draws this pixel.

    The cell is built once and kept, so writing the same pixel many times is cheap.
    """
    built = self._cell
    if built is None:
        built = _core.Cell(
            self.character,
            foreground=self.foreground,
            background=self.background,
        )
        object.__setattr__(self, '_cell', built)
    return built

__str__

__str__() -> str

Return the character of the pixel, so print(pixel) shows what it draws.

Source code in xnano/art/_pixels.py
def __str__(self) -> str:
    """Return the character of the pixel, so ``print(pixel)`` shows what it draws."""
    return self.character

__xnano_write__

__xnano_write__(context: Context | None = None) -> Buffer

Return a buffer of one cell that shows the pixel.

Source code in xnano/art/_pixels.py
def __xnano_write__(self, context: Context | None = None) -> _core.Buffer:
    """Return a buffer of one cell that shows the pixel."""
    buffer = _core.Buffer(width=1, height=1)
    buffer[0, 0] = self.cell()
    return buffer

Art

Art(rgba: bytes | bytearray | None, width: int, height: int, *, background: ColorValue | None = None, symbol: str | None = None, effects: Sequence[WritableEffectSpecification] = (), encoding: PixelEncoding = 'half_blocks', borders: bool = False)

Pixel art, and a world that holds other art.

Make one with pixel_art. A pixel is half a cell tall, so art that is 8 pixels tall takes 4 rows of a canvas. Write it with canvas.screen.write(art), or print it on its own with render.

An art can hold other art: add puts a child at a position in the world, and the world is drawn through its camera. Change any attribute of an art or of a child and the canvas draws it again on the next frame; nothing else is needed, and a world that stands still costs nothing. Positions and sizes of art are in pixels and may be fractional; a child is drawn at its rounded position. A child's x and y place it inside its parent in pixels, while placement.x and placement.y place the whole art on the canvas in cells: art.up() moves one pixel, half a cell, and placement.up() moves one cell.

Attributes:

  • width (int) –

    The width in pixels.

  • height (int) –

    The height in pixels (two pixel rows make one cell row).

  • x (float) –

    The pixel column of the anchor inside the parent art.

  • y (float) –

    The pixel row of the anchor inside the parent art.

  • layer (int) –

    Children with a higher layer are drawn over lower ones.

  • is_visible (bool) –

    Whether the art is drawn.

  • anchor (Anchor) –

    The (x, y) pixel inside the art that sits at (x, y).

  • background (Color | None) –

    The color behind the art and its children, or None for none.

  • solid_map (bytes | bytearray | None) –

    Which pixels of the art's world cannot be walked on, or None.

  • pixels (bytes | None) –

    The art's own pixels as red, green, blue and alpha bytes, or None.

  • children (tuple[Art, ...]) –

    The art added to this one, in the order it was added.

  • camera –

    What part of the world is on screen.

  • symbol (str | None) –

    The name the art is registered under in symbols, or None.

Examples:

import xnano

world = xnano.pixel_art(None, width=40, height=20, background='black')
hero = world.add(xnano.pixel_art(['HH', 'HH'], {'H': 'red'}), x=10, y=10, anchor=(1, 1))
hero.move(2, 0)
assert hero.x == 12

with xnano.new(width=20, height=5) as canvas:
    canvas.screen.write(world, width='100%', height='100%')
    canvas.clock.step()

Create art from pixels. Use pixel_art instead of calling this.

Parameters:

  • rgba (bytes | bytearray | None) –

    width * height * 4 bytes of red, green, blue and alpha, or None for a world with no pixels of its own.

  • width (int) –

    The width in pixels.

  • height (int) –

    The height in pixels.

  • background (ColorValue | None, default: None ) –

    The color behind the art.

  • symbol (str | None, default: None ) –

    The name to register the art under.

  • effects (Sequence[WritableEffectSpecification], default: () ) –

    Effects to start on the placement when the art is written.

  • encoding (PixelEncoding, default: 'half_blocks' ) –

    How the pixels are packed into cells: 'half_blocks', one column and two rows of pixels per cell, or 'braille', two by four, in one colour per cell.

  • borders (bool, default: False ) –

    Whether to show one pixel per cell, with the edges between colours and against the background traced in box-drawing characters and the inside of each colour filled with it.

Methods:

  • pixel –

    The red, green, blue and alpha of one of the art's own pixels.

  • add –

    Put another art in this one, at a position in pixels.

  • replace –

    Swap the pixels for others, keeping the position, layer and parent.

  • remove –

    Take the art out of the art that holds it. Removing a loose art does nothing.

  • move –

    Move the art by a number of pixels, sliding along solid ground instead of stopping.

  • up –

    Move up by count pixels, sliding along solid ground, and say how far it got.

  • down –

    Move down by count pixels, sliding along solid ground, and say how far it got.

  • left –

    Move left by count pixels, sliding along solid ground, and say how far it got.

  • right –

    Move right by count pixels, sliding along solid ground, and say how far it got.

  • is_solid –

    Whether a pixel of this art's world cannot be walked on.

  • world_for_cell –

    The world pixel under a cell of the screen, such as the one the pointer is over.

  • render –

    Draw the art to a string, without a canvas.

  • __xnano_write__ –

    Return the cells that show the art, as large as the area it is written in.

Source code in xnano/art/_worlds.py
def __init__(
    self,
    rgba: bytes | bytearray | None,
    width: int,
    height: int,
    *,
    background: ColorValue | None = None,
    symbol: str | None = None,
    effects: Sequence[WritableEffectSpecification] = (),
    encoding: PixelEncoding = 'half_blocks',
    borders: bool = False,
) -> None:
    """
    Create art from pixels. Use [`pixel_art`][xnano.pixel_art] instead of calling this.

    Args:
        rgba: ``width * height * 4`` bytes of red, green, blue and alpha, or ``None`` for
            a world with no pixels of its own.
        width: The width in pixels.
        height: The height in pixels.
        background: The color behind the art.
        symbol: The name to register the art under.
        effects: Effects to start on the placement when the art is written.
        encoding: How the pixels are packed into cells: ``'half_blocks'``, one column and
            two rows of pixels per cell, or ``'braille'``, two by four, in one colour per
            cell.
        borders: Whether to show one pixel per cell, with the edges between colours and
            against the background traced in box-drawing characters and the inside of
            each colour filled with it.
    """
    if encoding not in _CELL_PIXELS:
        raise ValueError(
            f"encoding must be 'half_blocks' or 'braille', but was {encoding!r}."
        )
    if width < 1 or height < 1:
        raise ValueError(
            f'Art needs at least 1 by 1 pixels, but got {width} by {height}. Give '
            f'pixel_art(...) rows of text, or width= and height= in pixels.'
        )
    if rgba is not None and len(rgba) != width * height * _RGBA:
        raise ValueError(
            f'{width} by {height} pixels need {width * height * _RGBA} bytes of red, '
            f'green, blue and alpha, but got {len(rgba)}.'
        )
    self._rgba: bytes | None = None if rgba is None else bytes(rgba)
    self._width = width
    self._height = height
    self._encoding: PixelEncoding = encoding
    self._borders = bool(borders)
    self._x = 0.0
    self._y = 0.0
    self._layer = 0
    self._is_visible = True
    self._anchor: Anchor = (0, 0)
    self._background: tuple[int, int, int] | None = (
        None if background is None else to_rgb(background)
    )
    self._solid_map: bytes | bytearray | None = None
    self._blocks_movement = False
    self._children: list[Art] = []
    self._parent: Art | None = None
    self._symbol: str | None = None
    effects = cast(
        'tuple[WritableEffectSpecification, ...]',
        effect_sequence(effects, 'writable'),
    )
    for effect in effects:
        normalize_effect(effect, 'writable')
    self._effects: tuple[WritableEffectSpecification, ...] = effects
    self._version = 0
    self._cache_key: tuple[int, ...] | None = None
    self._cache_buffer: _core.Buffer | None = None
    self._last_view: tuple[int, int] | None = None
    self._observers: weakref.WeakSet[Placement[object, object]] = weakref.WeakSet()
    self.camera = Camera()
    """What part of the world is on screen."""
    if symbol is not None:
        symbols.register(symbol, self)
        self._symbol = symbol

camera instance-attribute

camera = Camera()

What part of the world is on screen.

width property

width: int

The width in pixels.

height property

height: int

The height in pixels.

symbol property

symbol: str | None

The name the art is registered under in symbols, or None.

x property writable

x: float

The pixel column of the anchor inside the parent art.

y property writable

y: float

The pixel row of the anchor inside the parent art.

layer property writable

layer: int

Children with a higher layer are drawn over lower ones.

is_visible property writable

is_visible: bool

Whether the art is drawn.

anchor property writable

anchor: Anchor

The (x, y) pixel inside the art that sits at (x, y).

encoding property

encoding: PixelEncoding

How the pixels are packed into cells: 'half_blocks' or 'braille'.

borders property

borders: bool

Whether the art shows one pixel per cell, its edge in box-drawing characters.

background property writable

background: Color | None

The color behind the art and its children, or None for none.

solid_map property writable

solid_map: bytes | bytearray | None

Which pixels of the art's world cannot be walked on, or None when all can: one byte per pixel, row after row (width * height bytes), with a non-zero byte for solid ground.

pixels property

pixels: bytes | None

The art's own pixels as red, green, blue and alpha bytes, or None for a world.

The bytes run row after row from the top-left pixel, four bytes a pixel (width * height * 4 in all), and a pixel with an alpha of 0 is transparent. Children added with add are not part of them. The bytes are a copy: change the art with replace.

Examples:

import xnano

dot = xnano.pixel_art(['R.'], {'R': '#ff0000'})
assert dot.pixels == bytes([255, 0, 0, 255, 0, 0, 0, 0])
assert xnano.pixel_art(None, width=4, height=4).pixels is None

children property

children: tuple[Art, ...]

The art added to this one with add, in the order it was added.

Examples:

import xnano

world = xnano.pixel_art(None, width=10, height=10)
hero = world.add(xnano.pixel_art(['H'], {'H': 'red'}), x=2, y=3)
assert world.children == (hero,)

pixel

pixel(x: int, y: int) -> tuple[int, int, int, int] | None

The red, green, blue and alpha of one of the art's own pixels.

Parameters:

  • x (int) –

    The pixel column, from 0 at the left.

  • y (int) –

    The pixel row, from 0 at the top.

Returns:

  • tuple[int, int, int, int] | None –

    The four values from 0 to 255; an alpha of 0 is a transparent pixel.

  • tuple[int, int, int, int] | None –

    None for a world, which has no pixels of its own.

Raises:

Examples:

import xnano

dot = xnano.pixel_art(['R.'], {'R': '#ff0000'})
assert dot.pixel(0, 0) == (255, 0, 0, 255)
assert dot.pixel(1, 0)[3] == 0
Source code in xnano/art/_worlds.py
def pixel(self, x: int, y: int) -> tuple[int, int, int, int] | None:
    """
    The red, green, blue and alpha of one of the art's own pixels.

    Args:
        x: The pixel column, from ``0`` at the left.
        y: The pixel row, from ``0`` at the top.

    Returns:
        The four values from ``0`` to ``255``; an alpha of ``0`` is a transparent pixel.
        ``None`` for a world, which has no pixels of its own.

    Raises:
        IndexError: The pixel is outside the art.

    Examples:
        ```python
        import xnano

        dot = xnano.pixel_art(['R.'], {'R': '#ff0000'})
        assert dot.pixel(0, 0) == (255, 0, 0, 255)
        assert dot.pixel(1, 0)[3] == 0
        ```
    """
    if not (0 <= x < self._width and 0 <= y < self._height):
        raise IndexError(
            f'Art.pixel({x}, {y}) is outside the art, which is {self._width} by '
            f'{self._height} pixels. Pass x from 0 to {self._width - 1} and y from 0 to '
            f'{self._height - 1}.'
        )
    rgba = self._rgba
    if rgba is None:
        return None
    start = (y * self._width + x) * _RGBA
    return (rgba[start], rgba[start + 1], rgba[start + 2], rgba[start + 3])

add

add(art: Art, /, *, x: float = 0, y: float = 0, layer: int = 0, anchor: Anchor = (0, 0), is_solid: bool = False) -> Art

Put another art in this one, at a position in pixels.

Parameters:

  • art (Art) –

    The art to add. It may be added to one art only.

  • x (float, default: 0 ) –

    The pixel column of the child's anchor inside this art.

  • y (float, default: 0 ) –

    The pixel row of the child's anchor inside this art.

  • layer (int, default: 0 ) –

    Children with a higher layer are drawn over lower ones; children on the same layer are drawn in the order they were added.

  • anchor (Anchor, default: (0, 0) ) –

    The (x, y) pixel of the child that sits at (x, y).

  • is_solid (bool, default: False ) –

    Whether the child's opaque pixels block the movement of other children.

Returns:

  • Art –

    The child, to move, change or remove.

Raises:

  • ValueError –

    The art already belongs to an art, or is this art or one that holds it.

Examples:

import xnano

world = xnano.pixel_art(None, width=8, height=8)
hero = world.add(xnano.pixel_art(['R', 'R'], {'R': 'red'}), x=3, y=2, anchor=(0, 1))
assert (hero.x, hero.y) == (3, 2)
Source code in xnano/art/_worlds.py
def add(
    self,
    art: Art,
    /,
    *,
    x: float = 0,
    y: float = 0,
    layer: int = 0,
    anchor: Anchor = (0, 0),
    is_solid: bool = False,
) -> Art:
    """
    Put another art in this one, at a position in pixels.

    Args:
        art: The art to add. It may be added to one art only.
        x: The pixel column of the child's anchor inside this art.
        y: The pixel row of the child's anchor inside this art.
        layer: Children with a higher layer are drawn over lower ones; children on the
            same layer are drawn in the order they were added.
        anchor: The ``(x, y)`` pixel of the child that sits at ``(x, y)``.
        is_solid: Whether the child's opaque pixels block the movement of other children.

    Returns:
        The child, to move, change or remove.

    Raises:
        ValueError: The art already belongs to an art, or is this art or one that holds
            it.

    Examples:
        ```python
        import xnano

        world = xnano.pixel_art(None, width=8, height=8)
        hero = world.add(xnano.pixel_art(['R', 'R'], {'R': 'red'}), x=3, y=2, anchor=(0, 1))
        assert (hero.x, hero.y) == (3, 2)
        ```
    """
    if not isinstance(art, Art):
        raise TypeError(
            f'add() takes an Art made with xnano.pixel_art(...), but got '
            f'{type(art).__name__}. Wrap a picture with xnano.pixel_art(image) first.'
        )
    ancestor: Art | None = self
    while ancestor is not None:
        if ancestor is art:
            raise ValueError(
                'An art cannot be added to itself or to an art it holds. Add it to '
                'another world.'
            )
        ancestor = ancestor._parent
    if art._parent is not None:
        raise ValueError(
            'This art already belongs to another art. Call art.remove() first, or draw '
            'a second one.'
        )
    art._parent = self
    art._x = float(x)
    art._y = float(y)
    art._layer = layer
    art._anchor = anchor
    art._blocks_movement = is_solid
    self._children.append(art)
    self._changed()
    return art

replace

replace(source: str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None, palette: Mapping[str, ColorValue] | str | None = None, *, width: int | None = None, height: int | None = None) -> None

Swap the pixels for others, keeping the position, layer and parent.

The solid ground is kept when the new pixels have the same size and cleared when the size changes.

This is how a walk cycle or a zoom is made: draw every frame once, and replace the pixels of the art that is on screen. The sources are the ones pixel_art takes, except a symbol name.

Parameters:

  • source (str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None) –

    Text rows, an image, RGBA bytes or None.

  • palette (Mapping[str, ColorValue] | str | None, default: None ) –

    What each character of text rows means.

  • width (int | None, default: None ) –

    The width in pixels of RGBA bytes or of a blank world.

  • height (int | None, default: None ) –

    The height in pixels.

Examples:

import xnano

frame_one = ['AB']
hero = xnano.pixel_art(frame_one, {'A': 'red', 'B': 'blue'})
hero.replace(['BA'], {'A': 'red', 'B': 'blue'})
assert hero.width == 2
Source code in xnano/art/_worlds.py
def replace(
    self,
    source: str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None,
    palette: Mapping[str, ColorValue] | str | None = None,
    *,
    width: int | None = None,
    height: int | None = None,
) -> None:
    """
    Swap the pixels for others, keeping the position, layer and parent.

    The solid ground is kept when the new pixels have the same size and cleared when the
    size changes.

    This is how a walk cycle or a zoom is made: draw every frame once, and replace the
    pixels of the art that is on screen. The sources are the ones
    [`pixel_art`][xnano.pixel_art] takes, except a symbol name.

    Args:
        source: Text rows, an image, RGBA bytes or ``None``.
        palette: What each character of text rows means.
        width: The width in pixels of RGBA bytes or of a blank world.
        height: The height in pixels.

    Examples:
        ```python
        import xnano

        frame_one = ['AB']
        hero = xnano.pixel_art(frame_one, {'A': 'red', 'B': 'blue'})
        hero.replace(['BA'], {'A': 'red', 'B': 'blue'})
        assert hero.width == 2
        ```
    """
    rgba, pixel_width, pixel_height = _pixels_of(source, palette, width, height)
    previous_width, previous_height = self._width, self._height
    self._rgba = None if rgba is None else bytes(rgba)
    self._width = pixel_width
    self._height = pixel_height
    if (pixel_width, pixel_height) != (previous_width, previous_height):
        self._solid_map = None
    self._changed()

remove

remove() -> None

Take the art out of the art that holds it. Removing a loose art does nothing.

Source code in xnano/art/_worlds.py
def remove(self) -> None:
    """Take the art out of the art that holds it. Removing a loose art does nothing."""
    parent = self._parent
    if parent is None:
        return
    self._parent = None
    if self in parent._children:
        parent._children.remove(self)
    if parent.camera.target is self:
        parent.camera.target = None
    parent._changed()

move

move(x: float = 0, y: float = 0) -> tuple[float, float]

Move the art by a number of pixels, sliding along solid ground instead of stopping.

The two axes are tried one after the other, a pixel at a time, so walking diagonally into a wall keeps moving along it and a thin wall cannot be stepped over. The anchor pixel is what collides. An art without a parent art, or whose parent has no solid ground, moves freely. Positive x moves right and positive y moves down.

Pixels are half a cell: art.move(y=-1) moves one pixel up, where placement.move(y=-1) moves the whole art one cell up.

Parameters:

  • x (float, default: 0 ) –

    How far to move along x, in pixels.

  • y (float, default: 0 ) –

    How far to move along y, in pixels.

Returns:

  • tuple[float, float] –

    The distance moved along each axis, (0.0, 0.0) when blocked.

Examples:

import xnano

world = xnano.pixel_art(None, width=8, height=8)
solid = bytearray(64)
for row in range(8):
    solid[row * 8 + 5] = 1
world.solid_map = solid
hero = world.add(xnano.pixel_art(['R'], {'R': 'red'}), x=4, y=2)
assert hero.move(2, 1) == (0.0, 1.0)
assert (hero.x, hero.y) == (4, 3)
Source code in xnano/art/_worlds.py
def move(self, x: float = 0, y: float = 0) -> tuple[float, float]:
    """
    Move the art by a number of pixels, sliding along solid ground instead of stopping.

    The two axes are tried one after the other, a pixel at a time, so walking diagonally
    into a wall keeps moving along it and a thin wall cannot be stepped over. The anchor
    pixel is what collides. An art without a parent art, or whose parent has no solid
    ground, moves freely. Positive ``x`` moves right and positive ``y`` moves down.

    Pixels are half a cell: ``art.move(y=-1)`` moves one pixel up, where
    ``placement.move(y=-1)`` moves the whole art one cell up.

    Args:
        x: How far to move along ``x``, in pixels.
        y: How far to move along ``y``, in pixels.

    Returns:
        The distance moved along each axis, ``(0.0, 0.0)`` when blocked.

    Examples:
        ```python
        import xnano

        world = xnano.pixel_art(None, width=8, height=8)
        solid = bytearray(64)
        for row in range(8):
            solid[row * 8 + 5] = 1
        world.solid_map = solid
        hero = world.add(xnano.pixel_art(['R'], {'R': 'red'}), x=4, y=2)
        assert hero.move(2, 1) == (0.0, 1.0)
        assert (hero.x, hero.y) == (4, 3)
        ```
    """
    _check_pixels(x, name='x', verb='move')
    _check_pixels(y, name='y', verb='move')
    before_x, before_y = self._x, self._y
    self.x = self._advance(self._x, self._y, x, is_horizontal=True)
    self.y = self._advance(self._x, self._y, y, is_horizontal=False)
    return (self._x - before_x, self._y - before_y)

up

up(count: float = 1) -> float

Move up by count pixels, sliding along solid ground, and say how far it got.

Unlike Placement.up, which returns the placement so calls chain, this returns the distance moved, so a game can tell when the art was blocked.

Parameters:

  • count (float, default: 1 ) –

    How many pixels to move; pixels are half a cell.

Returns:

  • float –

    The distance moved in pixels, 0.0 when blocked.

Source code in xnano/art/_worlds.py
def up(self, count: float = 1) -> float:
    """
    Move up by ``count`` pixels, sliding along solid ground, and say how far it got.

    Unlike [`Placement.up`][xnano.layout.Placement.up], which returns the placement
    so calls chain, this returns the distance moved, so a game can tell when the art was
    blocked.

    Args:
        count: How many pixels to move; pixels are half a cell.

    Returns:
        The distance moved in pixels, ``0.0`` when blocked.
    """
    _check_pixels(count, name='count', verb='up', opposite='down')
    return abs(self.move(y=-count)[1])

down

down(count: float = 1) -> float

Move down by count pixels, sliding along solid ground, and say how far it got.

Unlike Placement.down, which returns the placement so calls chain, this returns the distance moved, so a game can tell when the art was blocked.

Parameters:

  • count (float, default: 1 ) –

    How many pixels to move; pixels are half a cell.

Returns:

  • float –

    The distance moved in pixels, 0.0 when blocked.

Source code in xnano/art/_worlds.py
def down(self, count: float = 1) -> float:
    """
    Move down by ``count`` pixels, sliding along solid ground, and say how far it got.

    Unlike [`Placement.down`][xnano.layout.Placement.down], which returns the placement
    so calls chain, this returns the distance moved, so a game can tell when the art was
    blocked.

    Args:
        count: How many pixels to move; pixels are half a cell.

    Returns:
        The distance moved in pixels, ``0.0`` when blocked.
    """
    _check_pixels(count, name='count', verb='down', opposite='up')
    return abs(self.move(y=count)[1])

left

left(count: float = 1) -> float

Move left by count pixels, sliding along solid ground, and say how far it got.

Unlike Placement.left, which returns the placement so calls chain, this returns the distance moved, so a game can tell when the art was blocked.

Parameters:

  • count (float, default: 1 ) –

    How many pixels to move; pixels are half a cell.

Returns:

  • float –

    The distance moved in pixels, 0.0 when blocked.

Source code in xnano/art/_worlds.py
def left(self, count: float = 1) -> float:
    """
    Move left by ``count`` pixels, sliding along solid ground, and say how far it got.

    Unlike [`Placement.left`][xnano.layout.Placement.left], which returns the placement
    so calls chain, this returns the distance moved, so a game can tell when the art was
    blocked.

    Args:
        count: How many pixels to move; pixels are half a cell.

    Returns:
        The distance moved in pixels, ``0.0`` when blocked.
    """
    _check_pixels(count, name='count', verb='left', opposite='right')
    return abs(self.move(x=-count)[0])

right

right(count: float = 1) -> float

Move right by count pixels, sliding along solid ground, and say how far it got.

Unlike Placement.right, which returns the placement so calls chain, this returns the distance moved, so a game can tell when the art was blocked.

Parameters:

  • count (float, default: 1 ) –

    How many pixels to move; pixels are half a cell.

Returns:

  • float –

    The distance moved in pixels, 0.0 when blocked.

Source code in xnano/art/_worlds.py
def right(self, count: float = 1) -> float:
    """
    Move right by ``count`` pixels, sliding along solid ground, and say how far it got.

    Unlike [`Placement.right`][xnano.layout.Placement.right], which returns the placement
    so calls chain, this returns the distance moved, so a game can tell when the art was
    blocked.

    Args:
        count: How many pixels to move; pixels are half a cell.

    Returns:
        The distance moved in pixels, ``0.0`` when blocked.
    """
    _check_pixels(count, name='count', verb='right', opposite='left')
    return abs(self.move(x=count)[0])

is_solid

is_solid(x: float, y: float) -> bool

Whether a pixel of this art's world cannot be walked on.

Everything outside the world is solid. Inside it, a pixel is solid where solid_map holds a non-zero byte, or where an opaque pixel of a child added with is_solid=True is.

Parameters:

  • x (float) –

    The world column.

  • y (float) –

    The world row.

Examples:

import xnano

world = xnano.pixel_art(None, width=4, height=4)
assert world.is_solid(-1, 0)
assert not world.is_solid(2, 2)
Source code in xnano/art/_worlds.py
def is_solid(self, x: float, y: float) -> bool:
    """
    Whether a pixel of this art's world cannot be walked on.

    Everything outside the world is solid. Inside it, a pixel is solid where
    [`solid_map`][xnano.art.Art.solid_map] holds a non-zero byte, or where an opaque pixel
    of a child added with ``is_solid=True`` is.

    Args:
        x: The world column.
        y: The world row.

    Examples:
        ```python
        import xnano

        world = xnano.pixel_art(None, width=4, height=4)
        assert world.is_solid(-1, 0)
        assert not world.is_solid(2, 2)
        ```
    """
    return self._is_solid_for(x, y, mover=None)

world_for_cell

world_for_cell(x: int, y: int) -> tuple[int, int]

The world pixel under a cell of the screen, such as the one the pointer is over.

The cell must be one of the cells the art was last drawn in; a cell holds one column and two rows of pixels (two by four with the 'braille' encoding, one pixel with borders), and the pixel returned is the lowest one in its left column.

Parameters:

  • x (int) –

    The cell's column in the placement of the art.

  • y (int) –

    The cell's row in the placement of the art.

Examples:

import xnano

world = xnano.pixel_art(None, width=40, height=40)
world.camera.x, world.camera.y = 16, 16
with xnano.new(width=8, height=4) as canvas:
    canvas.screen.write(world, width='100%', height='100%')
    canvas.clock.step()
assert world.world_for_cell(0, 0) == (16, 17)
Source code in xnano/art/_worlds.py
def world_for_cell(self, x: int, y: int) -> tuple[int, int]:
    """
    The world pixel under a cell of the screen, such as the one the pointer is over.

    The cell must be one of the cells the art was last drawn in; a cell holds one column
    and two rows of pixels (two by four with the ``'braille'`` encoding, one pixel with
    ``borders``), and the pixel returned is the lowest one in its left column.

    Args:
        x: The cell's column in the placement of the art.
        y: The cell's row in the placement of the art.

    Examples:
        ```python
        import xnano

        world = xnano.pixel_art(None, width=40, height=40)
        world.camera.x, world.camera.y = 16, 16
        with xnano.new(width=8, height=4) as canvas:
            canvas.screen.write(world, width='100%', height='100%')
            canvas.clock.step()
        assert world.world_for_cell(0, 0) == (16, 17)
        ```
    """
    left, top = self._origin()
    columns_per_cell, rows_per_cell = self._cell_pixels()
    return left + columns_per_cell * x, top + rows_per_cell * y + rows_per_cell - 1

render

render(*, width: int | None = None, height: int | None = None, format: Literal['text', 'ansi'] = 'text') -> str

Draw the art to a string, without a canvas.

Parameters:

  • width (int | None, default: None ) –

    The width in cells. The art's own width by default.

  • height (int | None, default: None ) –

    The height in cells. The art's own height in cells by default.

  • format (Literal['text', 'ansi'], default: 'text' ) –

    'text' for the characters only, 'ansi' with colors.

Examples:

import xnano

heart = xnano.pixel_art(['R.R', 'RRR'], {'R': 'red'})
assert heart.render() == ' ▄'
Source code in xnano/art/_worlds.py
def render(
    self,
    *,
    width: int | None = None,
    height: int | None = None,
    format: Literal['text', 'ansi'] = 'text',
) -> str:
    """
    Draw the art to a string, without a canvas.

    Args:
        width: The width in cells. The art's own width by default.
        height: The height in cells. The art's own height in cells by default.
        format: ``'text'`` for the characters only, ``'ansi'`` with colors.

    Examples:
        ```python
        import xnano

        heart = xnano.pixel_art(['R.R', 'RRR'], {'R': 'red'})
        assert heart.render() == ' ▄'
        ```
    """
    columns_per_cell, rows_per_cell = self._cell_pixels()
    columns = math.ceil(self._width / columns_per_cell) if width is None else width
    rows = math.ceil(self._height / rows_per_cell) if height is None else height
    return self._compose(columns, rows).render(format=format)

__xnano_write__

__xnano_write__(context: Context) -> Buffer

Return the cells that show the art, as large as the area it is written in.

Source code in xnano/art/_worlds.py
def __xnano_write__(self, context: Context) -> _core.Buffer:
    """Return the cells that show the art, as large as the area it is written in."""
    owner = context.target
    area = surface_of(owner).region
    if hasattr(owner, 'refresh'):
        self._observers.add(cast('Placement[object, object]', owner))
    area_columns, area_rows = area._grid_size()
    columns_per_cell, rows_per_cell = self._cell_pixels()
    columns = area_columns or math.ceil(self._width / columns_per_cell)
    rows = area_rows or math.ceil(self._height / rows_per_cell)
    return self._compose(columns, rows)

Camera

Camera()

Which part of a world is on screen.

By default the camera stays put. follow an art to keep it in the middle, or set x and y yourself. Either way the camera stays inside the world, and a world smaller than the screen is centered.

Attributes:

  • x –

    The world column at the left edge of the screen, when nothing is followed.

  • y –

    The world row at the top edge of the screen, when nothing is followed.

  • target (Art | None) –

    The art the camera follows, or None.

Examples:

import xnano

world = xnano.pixel_art(None, width=100, height=60, background='black')
hero = world.add(xnano.pixel_art(['H', 'H'], {'H': 'red'}), x=50, y=30)
world.camera.follow(hero)
assert world.camera.target is hero

Create a camera. Every art has one as art.camera.

Methods:

  • follow –

    Keep an art in the middle of the screen, or pass None to stop following.

Source code in xnano/art/_worlds.py
def __init__(self) -> None:
    """Create a camera. Every art has one as ``art.camera``."""
    self.x = 0
    """The world column at the left edge of the screen, when nothing is followed."""
    self.y = 0
    """The world row at the top edge of the screen, when nothing is followed."""
    self.target: Art | None = None
    """The art the camera follows, or ``None``."""

x instance-attribute

x = 0

The world column at the left edge of the screen, when nothing is followed.

y instance-attribute

y = 0

The world row at the top edge of the screen, when nothing is followed.

target instance-attribute

target: Art | None = None

The art the camera follows, or None.

follow

follow(art: Art | None) -> None

Keep an art in the middle of the screen, or pass None to stop following.

Parameters:

  • art (Art | None) –

    The art to follow.

Source code in xnano/art/_worlds.py
def follow(self, art: Art | None) -> None:
    """
    Keep an art in the middle of the screen, or pass ``None`` to stop following.

    Args:
        art: The art to follow.
    """
    self.target = art

load_image

load_image(source: TerminalImage | PathLike[str] | str | bytes, /, *, x: Axis | None = None, y: Axis | None = None, width: Axis | None = None, height: Axis | None = None, layer: int = 0, lock: bool = False, fit: ImageFit | None = None, resampling_filter: ResamplingFilter | None = None, background: ColorValue = (0, 0, 0), speed: float = 1.0, symbol: str | None = None) -> Image

Load an image or an animation from a file path or from bytes.

This is Image with the same arguments: PNG, JPEG, GIF, WebP and XNI files are read, and an animated one plays on the canvas's clock. Write the result with canvas.screen.write(picture).

Parameters:

  • source (TerminalImage | PathLike[str] | str | bytes) –

    The path of an image file, the bytes of one, or a TerminalImage.

  • x (Axis | None, default: None ) –

    The column of the left edge; see Image.

  • y (Axis | None, default: None ) –

    The row of the top edge.

  • width (Axis | None, default: None ) –

    The width: cells, a percentage, an expression, or None for the picture's own.

  • height (Axis | None, default: None ) –

    The height, in the same forms.

  • layer (int, default: 0 ) –

    Content with a higher layer is drawn over content with a lower one.

  • lock (bool, default: False ) –

    Keep the size the image has when it is added, whatever the canvas does.

  • fit (ImageFit | None, default: None ) –

    How the picture sits in a box of width by height.

  • resampling_filter (ResamplingFilter | None, default: None ) –

    How pixels are blended when it is resized.

  • background (ColorValue, default: (0, 0, 0) ) –

    The color of the margins around a picture with no transparent pixel, and the color partly transparent pixels are blended with.

  • speed (float, default: 1.0 ) –

    How fast an animated image plays: 2.0 is twice as fast.

  • symbol (str | None, default: None ) –

    A name to register the image under in symbols.

Returns:

Raises:

  • ImportError –

    xnano-image is not installed. Install it with pip install "xnano[image]".

  • TypeError –

    source is not a path, bytes or an image.

  • FileNotFoundError –

    The path does not exist.

Examples:

import xnano
from xnano_image import TerminalImage

picture = xnano.load_image(
    TerminalImage.from_rgba(1, 1, bytes([255, 0, 0, 255])), width=4, symbol='red_dot'
)
assert isinstance(picture, xnano.Image)
assert xnano.symbols.lookup('red_dot') is picture
Source code in xnano/art/_images.py
def load_image(
    source: TerminalImage | os.PathLike[str] | str | bytes,
    /,
    *,
    x: Axis | None = None,
    y: Axis | None = None,
    width: Axis | None = None,
    height: Axis | None = None,
    layer: int = 0,
    lock: bool = False,
    fit: ImageFit | None = None,
    resampling_filter: ResamplingFilter | None = None,
    background: ColorValue = (0, 0, 0),
    speed: float = 1.0,
    symbol: str | None = None,
) -> Image:
    """
    Load an image or an animation from a file path or from bytes.

    This is [`Image`][xnano.Image] with the same arguments: PNG, JPEG, GIF, WebP and XNI files
    are read, and an animated one plays on the canvas's clock. Write the result with
    ``canvas.screen.write(picture)``.

    Args:
        source: The path of an image file, the bytes of one, or a
            [`TerminalImage`][xnano_image.TerminalImage].
        x: The column of the left edge; see [`Image`][xnano.Image].
        y: The row of the top edge.
        width: The width: cells, a percentage, an expression, or ``None`` for the picture's own.
        height: The height, in the same forms.
        layer: Content with a higher layer is drawn over content with a lower one.
        lock: Keep the size the image has when it is added, whatever the canvas does.
        fit: How the picture sits in a box of ``width`` by ``height``.
        resampling_filter: How pixels are blended when it is resized.
        background: The color of the margins around a picture with no transparent pixel, and
            the color partly transparent pixels are blended with.
        speed: How fast an animated image plays: ``2.0`` is twice as fast.
        symbol: A name to register the image under in [`symbols`][xnano.symbols].

    Returns:
        The [`Image`][xnano.Image].

    Raises:
        ImportError: ``xnano-image`` is not installed. Install it with
            ``pip install "xnano[image]"``.
        TypeError: ``source`` is not a path, bytes or an image.
        FileNotFoundError: The path does not exist.

    Examples:
        ```python
        import xnano
        from xnano_image import TerminalImage

        picture = xnano.load_image(
            TerminalImage.from_rgba(1, 1, bytes([255, 0, 0, 255])), width=4, symbol='red_dot'
        )
        assert isinstance(picture, xnano.Image)
        assert xnano.symbols.lookup('red_dot') is picture
        ```
    """
    require('image', needed_for='xnano.load_image')
    return Image(
        source,
        x=x,
        y=y,
        width=width,
        height=height,
        layer=layer,
        lock=lock,
        fit=fit,
        resampling_filter=resampling_filter,
        background=background,
        speed=speed,
        symbol=symbol,
    )

pixel_art

pixel_art(source: str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None = None, palette: Mapping[str, ColorValue] | str | None = None, *, width: int | None = None, height: int | None = None, background: ColorValue | None = None, symbol: str | None = None, effects: Sequence[WritableEffectSpecification] = (), encoding: PixelEncoding = 'half_blocks', borders: bool = False) -> Art

Build pixel art from text, a picture, bytes or nothing (does not draw).

This is how pixel-art sprites are written in code, one character per pixel. Nothing is drawn: the art is a value that you write into a canvas. Text rows (a multi-line string, which may be indented, or a list of rows) are painted with a palette that says what each character means; any character the palette does not name, such as '.', is a transparent pixel. The palette is a mapping, or one string of character=color pairs.

What source is decides what is made:

  • Text with a newline, or a list of rows: pixel art painted with palette.
  • Text without a newline: the name of a registered art or image (see symbols); you get a copy of the art, or the pixels of the image. A one-row picture is a list, pixel_art(['GG'], palette), so that a call never changes meaning because a symbol was registered later.
  • An Image or a TerminalImage from xnano_image: its pixels are copied (the first frame of an animation).
  • bytes of red, green, blue and alpha, with width and height.
  • None: a blank world of width by height pixels filled with background.

Parameters:

  • source (str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None, default: None ) –

    What to draw.

  • palette (Mapping[str, ColorValue] | str | None, default: None ) –

    The color of each character of text rows, as a mapping to names, '#rrggbb' strings or (red, green, blue) tuples, or as a string such as 'R=#e03040 G=green'.

  • width (int | None, default: None ) –

    The width in pixels of bytes or of a blank world.

  • height (int | None, default: None ) –

    The height in pixels.

  • background (ColorValue | None, default: None ) –

    The color behind the art. Transparent pixels show it.

  • symbol (str | None, default: None ) –

    A name to register the art under, so pixel_art('name') returns a copy of it.

  • effects (Sequence[WritableEffectSpecification], default: () ) –

    Effects to start on the placement when the art is written, as dictionaries with a kind key.

  • encoding (PixelEncoding, default: 'half_blocks' ) –

    How the pixels are packed into cells: 'half_blocks' (one column and two rows of pixels per cell) or 'braille' (two by four, one colour per cell, for a finer, drawing-like look).

  • borders (bool, default: False ) –

    Whether to show one pixel per cell, with the edges between colours and against the background traced in box-drawing characters and the inside of each colour filled with it.

Raises:

  • ValueError –

    The rows are empty or differ in length, the palette or a color in it is not valid, a text without a newline is not a known symbol, the sizes do not match the bytes, or encoding is not one of the two.

  • TypeError –

    source is not one of the kinds above.

Examples:

import xnano

heart = xnano.pixel_art(
    '''
    .RR.RR.
    RRRRRRR
    .RRRRR.
    ..RRR..
    ...R...
    ''',
    'R=#e03040',
)
assert (heart.width, heart.height) == (7, 5)
print(heart.render())

xnano.pixel_art(['G'], {'G': 'green'}, symbol='grass')
assert xnano.pixel_art('grass').width == 1
Source code in xnano/art/_worlds.py
def pixel_art(
    source: str | Sequence[str] | Image | TerminalImage | bytes | bytearray | None = None,
    palette: Mapping[str, ColorValue] | str | None = None,
    *,
    width: int | None = None,
    height: int | None = None,
    background: ColorValue | None = None,
    symbol: str | None = None,
    effects: Sequence[WritableEffectSpecification] = (),
    encoding: PixelEncoding = 'half_blocks',
    borders: bool = False,
) -> Art:
    """
    Build pixel art from text, a picture, bytes or nothing (does not draw).

    This is how pixel-art sprites are written in code, one character per pixel. Nothing is
    drawn: the art is a value that you write into a canvas. Text rows (a multi-line string, which
    may be indented, or a list of rows) are painted with a palette that says what each
    character means; any character the palette does not name, such as ``'.'``, is a
    transparent pixel. The palette is a mapping, or one string of ``character=color`` pairs.

    What ``source`` is decides what is made:

    * Text with a newline, or a list of rows: pixel art painted with ``palette``.
    * Text without a newline: the name of a registered art or image (see
      [`symbols`][xnano.symbols]); you get a copy of the art, or the pixels of the image.
      A one-row picture is a list, ``pixel_art(['GG'], palette)``, so that a call never changes
      meaning because a symbol was registered later.
    * An [`Image`][xnano.Image] or a ``TerminalImage`` from ``xnano_image``: its pixels are copied
      (the first frame of an animation).
    * ``bytes`` of red, green, blue and alpha, with ``width`` and ``height``.
    * ``None``: a blank world of ``width`` by ``height`` pixels filled with ``background``.

    Args:
        source: What to draw.
        palette: The color of each character of text rows, as a mapping to names,
            ``'#rrggbb'`` strings or ``(red, green, blue)`` tuples, or as a string such as
            ``'R=#e03040 G=green'``.
        width: The width in pixels of ``bytes`` or of a blank world.
        height: The height in pixels.
        background: The color behind the art. Transparent pixels show it.
        symbol: A name to register the art under, so ``pixel_art('name')`` returns a copy of it.
        effects: Effects to start on the placement when the art is written, as dictionaries
            with a ``kind`` key.
        encoding: How the pixels are packed into cells: ``'half_blocks'`` (one column and two
            rows of pixels per cell) or ``'braille'`` (two by four, one colour per cell, for a
            finer, drawing-like look).
        borders: Whether to show one pixel per cell, with the edges between colours and
            against the background traced in box-drawing characters and the inside of each
            colour filled with it.

    Raises:
        ValueError: The rows are empty or differ in length, the palette or a color in it is
            not valid, a text without a newline is not a known symbol, the sizes do not match
            the bytes, or ``encoding`` is not one of the two.
        TypeError: ``source`` is not one of the kinds above.

    Examples:
        ```python
        import xnano

        heart = xnano.pixel_art(
            '''
            .RR.RR.
            RRRRRRR
            .RRRRR.
            ..RRR..
            ...R...
            ''',
            'R=#e03040',
        )
        assert (heart.width, heart.height) == (7, 5)
        print(heart.render())

        xnano.pixel_art(['G'], {'G': 'green'}, symbol='grass')
        assert xnano.pixel_art('grass').width == 1
        ```
    """
    if isinstance(source, str) and '\n' not in source:
        if source in symbols.names(kind=Image):
            # The name of a registered image draws that image.
            source = symbols.lookup(source, kind=Image)
    if isinstance(source, str) and '\n' not in source:
        try:
            registered = symbols.lookup(source, kind=Art)
        except ValueError as error:
            raise ValueError(
                f'{error} To draw a one-row picture, pass a list: pixel_art([{source!r}], '
                f'palette).'
            ) from None
        art = registered._copy()
        if background is not None:
            art.background = background
        effects = cast(
            'tuple[WritableEffectSpecification, ...]',
            effect_sequence(effects, 'writable'),
        )
        if effects:
            for effect in effects:
                normalize_effect(effect, 'writable')
            art._effects = effects
        if symbol is not None:
            symbols.register(symbol, art)
            art._symbol = symbol
        return art
    rgba, pixel_width, pixel_height = _pixels_of(source, palette, width, height)
    return Art(
        rgba,
        pixel_width,
        pixel_height,
        background=background,
        symbol=symbol,
        effects=effects,
        encoding=encoding,
        borders=borders,
    )