diff --git a/docs/animation.en.md b/docs/animation.en.md index a5013ac..613d121 100644 --- a/docs/animation.en.md +++ b/docs/animation.en.md @@ -121,8 +121,9 @@ keep the default value `1`. Besides the timing, `tick()` empties the window event queue. It collects all new mouse moves, button clicks, and key presses so you can read them from the global -lists in `drawzero.utils.events`. If you skip `tick()`, you will not see user -input and the window may stop responding. +lists such as `keysdown`, `keysup`, `mousemotions`, and `mousebuttonsdown` +that appear after `from drawzero import *`. If you skip `tick()`, you will not +see user input and the window may stop responding. ### `sleep(t=1)` diff --git a/docs/animation.ru.md b/docs/animation.ru.md index 5934f3b..140afdc 100644 --- a/docs/animation.ru.md +++ b/docs/animation.ru.md @@ -121,8 +121,9 @@ DrawZero выполнит внутреннее обновление кадра ` Помимо тайминга, `tick()` очищает очередь событий окна. Он собирает все новые движения мыши, нажатия кнопок и клавиш, чтобы вы могли прочитать их из -глобальных списков в `drawzero.utils.events`. Если вы пропустите `tick()`, вы не -увидите ввод пользователя, и окно может перестать отвечать. +глобальных списков `keysdown`, `keysup`, `mousemotions`, `mousebuttonsdown`, +которые появляются после `from drawzero import *`. Если вы пропустите `tick()`, +вы не увидите ввод пользователя, и окно может перестать отвечать. ### `sleep(t=1)` diff --git a/docs/architecture.en.md b/docs/architecture.en.md index 71a589a..f8c7a3c 100644 --- a/docs/architecture.en.md +++ b/docs/architecture.en.md @@ -1,81 +1,52 @@ # DrawZero Architecture Overview -This document summarizes the internal layout of the DrawZero project so that contributors can quickly orient themselves in the codebase. +This document summarizes how DrawZero is put together without exposing low-level implementation details. It highlights the responsibilities of each part so that contributors know where to add new features while keeping the public API simple for learners. -## Package layout +## Public API surface -``` -src/drawzero/ -├── __init__.py # Re-exported public API -├── __main__.py # CLI entry point (copies examples, draws demo frame) -├── examples/ # Tutorial-style scripts executed by tests -└── utils/ # Core rendering, math, and convenience helpers -``` - -Other notable top-level folders: - -* `docs/` – MkDocs documentation shipped on PyPI; suitable place for additional guides. -* `tests/` – Pytest and unittest suites that import examples, validate converters, gradients, points, and internationalization helpers. - -## Public API surface (`src/drawzero/__init__.py`) - -The package exposes a “flat” API meant to mimic turtle/pygame zero ergonomics. All drawing helpers are imported from `utils.draw`, while math helpers come from sibling modules: +Everything in the library is re-exported, so one import is enough: -* Drawing primitives: `line`, `circle`, `rect`, `polygon`, `text`, `image`, etc. -* Filled variants share the same renderer entry points by passing `line_width=0`. -* Animation and timing helpers: `tick`, `sleep`, `run`, `fps`, `quit`. -* Input helpers proxy the renderer’s key/mouse state (`get_keys_pressed`, `keysdown`, `mousebuttonsdown`, ...). -* Utilities: `Pt` (vector/turtle hybrid), `Gradient`, `copy_examples`, color constants (`C`, `COLORS`, `ALL_COLORS`). - -Every user-facing function ultimately routes through the renderer stack described below. - -## Rendering pipeline (`utils.draw` → `utils.renderer`) - -`utils.draw` performs argument validation and coercion before delegating to the actual drawing backend. Common steps for each primitive: - -1. Convert user-supplied data through converter helpers (`utils.converters`). These functions normalize coordinates, radii, rectangles, and colors, while collecting rich error messages via `BadDrawParmsError` and localized strings in `utils.i18n`. -2. Choose the backend module depending on the `EJUDGE_MODE` environment variable. GUI builds import `utils.renderer` (pygame-based). Text-mode/CI builds fall back to `utils.renderer_ejudge`, which prints commands for automated judges. -3. After the renderer call, update cached input event lists so that consumers see mouse/key positions in logical (virtual) coordinates. +```python +from drawzero import * +``` -### `utils.renderer` +The call exposes: -The pygame renderer lazily creates a resizable window and keeps an off-screen copy to survive resizes. Important responsibilities: +* Drawing helpers such as `line`, `circle`, `rect`, `polygon`, `text`, `image`, and their filled variants. +* Animation and timing helpers: `run`, `tick`, `sleep`, `fps`, and `quit`. +* Input helpers for reading the keyboard and mouse: `get_keys_pressed`, `keys_mods_pressed`, `get_mouse_pressed`, plus the shared lists `keysdown`, `keysup`, `mousemotions`, `mousebuttonsdown`, and `mousebuttonsup`. +* Utility objects: the `screen` shim used by Pygame Zero style scripts, the `Pt` vector/turtle hybrid, the `Gradient` color ramp builder, localization via `set_lang`, the color namespaces (`C`, `COLORS`, `THECOLORS`, `ALL_COLORS`), keyboard constants (`K`, `KEY`), and `copy_examples()` for scaffolding tutorials. +* Canvas configuration helpers such as `set_virtual_size()`. -* Surface management: `_create_surface()` defers window creation until the first drawing call; `_resize()` rescales existing content when SDL emits a resize event. -* Primitive drawing: each `draw_*` function handles optional alpha blending by drawing into temporary `pygame.Surface` buffers when needed. -* Event pump: `draw_tick()` advances the clock (30 FPS target), flushes the event queue, and populates global lists (`keysdown`, `mousebuttonsdown`, etc.) consumed by `utils.draw`. -* Lifecycle hooks: `atexit.register(_draw_go)` keeps the pygame loop alive until the process exits; `_init()` configures DPI-awareness on Windows and centers the window. -* Coordinate scaling: setter functions from `utils.screen_size` maintain the mapping between “virtual” 1000×1000 coordinates (used by the API) and the actual window size. +All user guides in the documentation assume this import style. -### `utils.renderer_ejudge` +## Rendering flow -A lightweight stub used when `EJUDGE_MODE=true` (e.g., tests running without a GUI). It mirrors the renderer API but simply prints serialized drawing commands. Screen size is fixed to 1000×1000 so coordinate conversion remains consistent. +Every drawing helper validates and normalizes its arguments (coordinates, angles, colors, and radii) before forwarding them to the active renderer. The renderer choice depends on the `EJUDGE_MODE` environment variable: -## Coordinate transforms (`utils.screen_size`) +* When the variable is unset or false, DrawZero opens a graphical window backed by pygame and renders directly to the screen. +* When `EJUDGE_MODE` is true (used in automated graders and CI), DrawZero switches to a text-mode backend that prints serialized drawing commands instead of opening a window. -DrawZero always exposes a 1000×1000 virtual canvas. `set_virtual_size()` can change that logical resolution, and `set_real_size()` is called by the renderer when it knows the real pixel size. The module exposes helpers to convert between coordinate spaces: +Regardless of the backend, calling `tick()` processes window events, updates the shared input lists, and keeps the animation running near 30 FPS. Skipping `tick()` prevents new events from reaching the program, so the documentation emphasizes placing it in every frame loop. -* `to_canvas_x` / `to_canvas_y` – convert virtual coordinates to actual pixels. -* `from_canvas_x` / `from_canvas_y` – convert back to logical coordinates (used when reporting mouse positions). +## Virtual canvas and coordinate scaling -All converters and event wrappers rely on this module, so adjust it carefully if supporting non-square canvases. +The library works with a virtual 1000×1000 canvas. Drawing helpers accept integers or floats; values are converted to the current virtual size and then mapped to the actual window size. `set_virtual_size()` lets scripts change the logical resolution when they want to draw in a different coordinate space. Mouse helpers always return positions in the same virtual coordinate system, regardless of the real window dimensions. -## Math and utility helpers +## Utility helpers and constants -* `utils.pt.Pt` implements a mutable 2D vector with turtle-style movement, arithmetic operators, and convenience methods (`forward`, `rotate_around`, `distance`, etc.). Examples rely on it for animation logic. -* `utils.gradient.Gradient` constructs color ramps over a numeric domain (default 0–1). It uses the same converter/error infrastructure to provide consistent validation. -* `utils.colors` exposes pygame’s color table both as attribute access (`C.red`) and dictionaries (`COLORS`, `ALL_COLORS`). -* `utils.key_flags` mirrors pygame key constants so code can use `K.` even when pygame is absent (constants are loaded lazily when available). -* `utils.copy_examples.copy_examples()` copies `src/drawzero/examples` into the current working directory; the CLI entry point calls it to bootstrap learners. +Several helpers ship with the public API and are heavily used by examples and tests: -## Examples (`src/drawzero/examples`) +* `Pt` stores a position and heading, supports turtle-style movement, and acts like a mutable 2D vector. +* `Gradient` converts numbers into colors by interpolating across a list of samples. +* Color namespaces (`C`, `COLORS`, `THECOLORS`, `ALL_COLORS`) make pygame's color table easy to access without typing RGB triples. +* Keyboard constants `K` and `KEY` mirror pygame's naming so programs can use `K.space`, `K.left`, and similar attributes in both GUI and headless environments. +* `copy_examples()` copies the bundled examples into the working directory to help newcomers start experimenting. -Short, bilingual scripts demonstrate the API: drawing primitives, loops, animations, gradients, images, and simple interactive games. Tests import many of them to ensure they still execute, so keep side effects (e.g., infinite loops) behind guards if you add new ones. +## Examples and documentation -## Tests (`tests/`) +The package includes bilingual example scripts that demonstrate primitives, animations, gradients, image loading, and keyboard/mouse interaction. The MkDocs documentation mirrors those scripts with detailed explanations. Tests import many of the examples directly, so new examples must avoid side effects at import time unless they are guarded by `if __name__ == "__main__":`. -* `test_examples_gui_mode.py` imports each example module to ensure it runs against the real renderer. -* `test_examples_text_mode.py` sets `EJUDGE_MODE` and asserts the text renderer paths work. -* The remaining pytest modules cover specific utilities: converter validation, localized error messages, gradient interpolation, the `Pt` vector API, and `copy_examples()` behavior. +## Test suite -Use these tests as references when extending validation logic or adding new primitives. +Automated tests cover the drawing helpers, gradients, localization messages, point arithmetic, and example imports. Continuous integration runs them in both graphical mode and text mode (with `EJUDGE_MODE=true`) to ensure the public API behaves the same in either environment. diff --git a/docs/architecture.ru.md b/docs/architecture.ru.md index 3cc43f7..280e53d 100644 --- a/docs/architecture.ru.md +++ b/docs/architecture.ru.md @@ -1,81 +1,52 @@ # Обзор архитектуры DrawZero -Этот документ обобщает внутреннюю структуру проекта DrawZero, чтобы контрибьюторы могли быстро сориентироваться в кодовой базе. +Этот документ объясняет, как устроен DrawZero, не раскрывая низкоуровневые детали реализации. Он помогает участникам проекта понимать зоны ответственности и при этом сохранять простой публичный API для учащихся. -## Структура пакета +## Публичный интерфейс -``` -src/drawzero/ -├── __init__.py # Реэкспортированный публичный API -├── __main__.py # Точка входа CLI (копирует примеры, рисует демонстрационный кадр) -├── examples/ # Скрипты в стиле туториалов, выполняемые тестами -└── utils/ # Основные утилиты для рендеринга, математики и удобства -``` - -Другие примечательные папки верхнего уровня: - -* `docs/` – Документация MkDocs, поставляемая на PyPI; подходящее место для дополнительных руководств. -* `tests/` – Наборы тестов Pytest и unittest, которые импортируют примеры, проверяют конвертеры, градиенты, точки и утилиты интернационализации. - -## Публичный API (`src/drawzero/__init__.py`) - -Пакет предоставляет "плоский" API, предназначенный для имитации эргономики turtle/pygame zero. Все утилиты рисования импортируются из `utils.draw`, а математические утилиты — из соседних модулей: +Все функции библиотеки переэкспортируются, поэтому достаточно одного импорта: -* Графические примитивы: `line`, `circle`, `rect`, `polygon`, `text`, `image` и т.д. -* Заполненные варианты используют те же точки входа рендерера, передавая `line_width=0`. -* Утилиты для анимации и времени: `tick`, `sleep`, `run`, `fps`, `quit`. -* Утилиты ввода проксируют состояние клавиатуры/мыши рендерера (`get_keys_pressed`, `keysdown`, `mousebuttonsdown`, ...). -* Утилиты: `Pt` (гибрид вектора/черепахи), `Gradient`, `copy_examples`, константы цветов (`C`, `COLORS`, `ALL_COLORS`). - -Каждая функция, предназначенная для пользователя, в конечном итоге проходит через стек рендерера, описанный ниже. - -## Конвейер рендеринга (`utils.draw` → `utils.renderer`) - -`utils.draw` выполняет проверку и приведение типов аргументов перед делегированием фактическому бэкенду рисования. Общие шаги для каждого примитива: - -1. Преобразование данных, предоставленных пользователем, с помощью утилит-конвертеров (`utils.converters`). Эти функции нормализуют координаты, радиусы, прямоугольники и цвета, собирая при этом подробные сообщения об ошибках через `BadDrawParmsError` и локализованные строки в `utils.i18n`. -2. Выбор модуля бэкенда в зависимости от переменной окружения `EJUDGE_MODE`. Сборки с GUI импортируют `utils.renderer` (на основе pygame). Сборки в текстовом режиме/CI возвращаются к `utils.renderer_ejudge`, который выводит команды для автоматизированных судей. -3. После вызова рендерера обновить кэшированные списки событий ввода, чтобы потребители видели положения мыши/клавиш в логических (виртуальных) координатах. +```python +from drawzero import * +``` -### `utils.renderer` +Этот вызов открывает доступ к: -Рендерер pygame лениво создает окно с изменяемым размером и хранит его копию вне экрана, чтобы пережить изменение размера. Важные обязанности: +* Функциям рисования `line`, `circle`, `rect`, `polygon`, `text`, `image` и их заполненным вариантам. +* Помощникам для анимации и времени: `run`, `tick`, `sleep`, `fps`, `quit`. +* Вводу с клавиатуры и мыши: `get_keys_pressed`, `keys_mods_pressed`, `get_mouse_pressed`, а также общим спискам `keysdown`, `keysup`, `mousemotions`, `mousebuttonsdown`, `mousebuttonsup`. +* Утилитам: объекту `screen` в стиле Pygame Zero, вектору-"черепашке" `Pt`, построителю цветовых переходов `Gradient`, локализации через `set_lang`, цветовому пространству (`C`, `COLORS`, `THECOLORS`, `ALL_COLORS`), константам клавиатуры (`K`, `KEY`) и функции `copy_examples()` для копирования учебных примеров. +* Настройке холста, включая `set_virtual_size()`. -* Управление поверхностью: `_create_surface()` откладывает создание окна до первого вызова рисования; `_resize()` перемасштабирует существующее содержимое, когда SDL генерирует событие изменения размера. -* Рисование примитивов: каждая функция `draw_*` обрабатывает необязательное альфа-смешивание путем рисования во временных буферах `pygame.Surface` при необходимости. -* Насос событий: `draw_tick()` продвигает часы (цель 30 FPS), очищает очередь событий и заполняет глобальные списки (`keysdown`, `mousebuttonsdown` и т.д.), используемые `utils.draw`. -* Хуки жизненного цикла: `atexit.register(_draw_go)` поддерживает цикл pygame в рабочем состоянии до завершения процесса; `_init()` настраивает осведомленность о DPI в Windows и центрирует окно. -* Масштабирование координат: функции-сеттеры из `utils.screen_size` поддерживают сопоставление между "виртуальными" координатами 1000×1000 (используемыми API) и фактическим размером окна. +Все пользовательские руководства в документации используют именно такой стиль импорта. -### `utils.renderer_ejudge` +## Поток рендеринга -Облегченная заглушка, используемая, когда `EJUDGE_MODE=true` (например, тесты, работающие без GUI). Он зеркально отражает API рендерера, но просто выводит сериализованные команды рисования. Размер экрана фиксирован на 1000×1000, поэтому преобразование координат остается согласованным. +Каждая функция рисования проверяет и нормализует аргументы (координаты, углы, цвета, радиусы), а затем передает их активному рендереру. Выбор рендерера зависит от переменной окружения `EJUDGE_MODE`: -## Преобразования координат (`utils.screen_size`) +* Если переменная не установлена или равна `false`, DrawZero открывает графическое окно на pygame и рисует напрямую на экране. +* Если `EJUDGE_MODE` равна `true` (например, в автоматических проверяющих системах и CI), DrawZero переключается на текстовый режим и печатает сериализованные команды вместо открытия окна. -DrawZero всегда предоставляет виртуальный холст 1000×1000. `set_virtual_size()` может изменить это логическое разрешение, а `set_real_size()` вызывается рендерером, когда он знает реальный размер в пикселях. Модуль предоставляет утилиты для преобразования между пространствами координат: +Независимо от выбранного режима, вызов `tick()` обрабатывает события окна, обновляет общие списки ввода и поддерживает анимацию на скорости около 30 FPS. Если пропускать `tick()`, новые события не попадут в программу, поэтому руководство подчеркивает необходимость вызывать его в каждом кадровом цикле. -* `to_canvas_x` / `to_canvas_y` – преобразование виртуальных координат в фактические пиксели. -* `from_canvas_x` / `from_canvas_y` – преобразование обратно в логические координаты (используется при сообщении о положениях мыши). +## Виртуальный холст и масштабирование координат -Все конвертеры и обертки событий полагаются на этот модуль, поэтому настраивайте его осторожно, если поддерживаете неквадратные холсты. +Библиотека работает с виртуальным холстом 1000×1000. Функции рисования принимают целые и дробные числа; значения приводятся к текущему виртуальному размеру и затем сопоставляются с реальными размерами окна. `set_virtual_size()` позволяет сценариям менять логическое разрешение, когда нужно использовать другую систему координат. Функции ввода мыши всегда возвращают позиции в тех же виртуальных координатах вне зависимости от физических размеров окна. -## Математические и вспомогательные утилиты +## Утилиты и константы -* `utils.pt.Pt` реализует изменяемый 2D-вектор с движением в стиле черепахи, арифметическими операторами и удобными методами (`forward`, `rotate_around`, `distance` и т.д.). Примеры полагаются на него для логики анимации. -* `utils.gradient.Gradient` создает цветовые пандусы в числовой области (по умолчанию 0–1). Он использует ту же инфраструктуру конвертера/ошибок для обеспечения последовательной проверки. -* `utils.colors` предоставляет цветовую таблицу pygame как через доступ к атрибутам (`C.red`), так и через словари (`COLORS`, `ALL_COLORS`). -* `utils.key_flags` зеркально отражает константы клавиш pygame, поэтому код может использовать `K.`, даже когда pygame отсутствует (константы загружаются лениво, когда доступны). -* `utils.copy_examples.copy_examples()` копирует `src/drawzero/examples` в текущий рабочий каталог; точка входа CLI вызывает его для начальной настройки для учащихся. +Публичный API содержит несколько помощников, которые активно используются примерами и тестами: -## Примеры (`src/drawzero/examples`) +* `Pt` хранит позицию и направление, поддерживает движение в стиле "черепашки" и ведет себя как изменяемый 2D-вектор. +* `Gradient` преобразует числа в цвета, интерполируя по списку образцов. +* Цветовые пространства (`C`, `COLORS`, `THECOLORS`, `ALL_COLORS`) дают доступ к таблице цветов pygame без ручного ввода RGB-троек. +* Константы клавиатуры `K` и `KEY` повторяют соглашения pygame, поэтому можно писать `K.space`, `K.left` и другие атрибуты как в GUI, так и в headless-режиме. +* `copy_examples()` копирует встроенные примеры в рабочую директорию, помогая новичкам быстрее начать эксперименты. -Короткие двуязычные скрипты демонстрируют API: примитивы рисования, циклы, анимации, градиенты, изображения и простые интерактивные игры. Тесты импортируют многие из них, чтобы убедиться, что они все еще выполняются, поэтому держите побочные эффекты (например, бесконечные циклы) за защитными блоками, если вы добавляете новые. +## Примеры и документация -## Тесты (`tests/`) +В пакете есть двуязычные примеры, демонстрирующие примитивы, анимацию, градиенты, загрузку изображений и работу с клавиатурой/мышью. Документация MkDocs повторяет эти сценарии с подробными пояснениями. Тесты напрямую импортируют многие примеры, поэтому новые примеры должны избегать побочных эффектов при импорте, если только они не заключены в блок `if __name__ == "__main__":`. -* `test_examples_gui_mode.py` импортирует каждый модуль примера, чтобы убедиться, что он работает с реальным рендерером. -* `test_examples_text_mode.py` устанавливает `EJUDGE_MODE` и утверждает, что пути текстового рендерера работают. -* Остальные модули pytest охватывают конкретные утилиты: проверку конвертера, локализованные сообщения об ошибках, интерполяцию градиента, API вектора `Pt` и поведение `copy_examples()`. +## Набор тестов -Используйте эти тесты в качестве справочных материалов при расширении логики проверки или добавлении новых примитивов. +Автотесты покрывают функции рисования, градиенты, локализованные сообщения об ошибках, арифметику точек и импорт примеров. В непрерывной интеграции они запускаются как в графическом режиме, так и в текстовом (`EJUDGE_MODE=true`), чтобы убедиться, что публичный API ведет себя одинаково в обеих средах. diff --git a/docs/gradient.en.md b/docs/gradient.en.md index 7a83126..1fa4770 100644 --- a/docs/gradient.en.md +++ b/docs/gradient.en.md @@ -1,7 +1,7 @@ # Gradient helper reference -`Gradient` is a class that turns a number into a color. -It lives in [`drawzero.utils.gradient`](https://github.com/ShashkovS/drawzero/blob/master/src/drawzero/utils/gradient.py) and is available after `from drawzero import *`. +`Gradient` is a class that turns a number into a color. +It is available as soon as you write `from drawzero import *`. Use it when you need smooth color transitions for temperature maps, progress bars, particle systems, or animated trails. This guide also shows how to combine gradients with shapes from [Drawing primitives](primitives.md), transparency tips from @@ -18,7 +18,7 @@ print(heat(0.5)) # (0, 255, 255) - middle color print(heat(1.0)) # (255, 0, 0) - last color ``` -* The first argument is a list of colors. You can mix constants from `drawzero.utils.colors.C`, named strings (`'gold'`), or RGB tuples like `(34, 139, 34)`. +* The first argument is a list of colors. You can mix constants from `C`, named strings (`'gold'`), or RGB tuples like `(34, 139, 34)`. * By default the valid input range (the **domain**) goes from `0` to `1`. * Passing a value smaller than the start clamps to the first color; bigger values clamp to the last color. diff --git a/docs/gradient.ru.md b/docs/gradient.ru.md index 72631a3..691535f 100644 --- a/docs/gradient.ru.md +++ b/docs/gradient.ru.md @@ -1,7 +1,7 @@ # Справочник по Gradient `Gradient` — это класс, который превращает число в цвет. -Он находится в [`drawzero.utils.gradient`](https://github.com/ShashkovS/drawzero/blob/master/src/drawzero/utils/gradient.py) и доступен после `from drawzero import *`. +Он доступен сразу после `from drawzero import *`. Используйте его, когда вам нужны плавные цветовые переходы для тепловых карт, индикаторов выполнения, систем частиц или анимированных следов. Это руководство также показывает, как комбинировать градиенты с фигурами из [Графические примитивы](primitives.md), советами по прозрачности из @@ -18,7 +18,7 @@ print(heat(0.5)) # (0, 255, 255) - средний цвет print(heat(1.0)) # (255, 0, 0) - последний цвет ``` -* Первый аргумент — это список цветов. Вы можете смешивать константы из `drawzero.utils.colors.C`, именованные строки (`'gold'`) или кортежи RGB, такие как `(34, 139, 34)`. +* Первый аргумент — это список цветов. Вы можете смешивать константы из `C`, именованные строки (`'gold'`) или кортежи RGB, такие как `(34, 139, 34)`. * По умолчанию допустимый диапазон ввода (**домен**) от `0` до `1`. * Передача значения меньше начального приводит к выбору первого цвета; большие значения — к выбору последнего. diff --git a/docs/images.en.md b/docs/images.en.md index 232a044..467278f 100644 --- a/docs/images.en.md +++ b/docs/images.en.md @@ -5,11 +5,13 @@ This guide shows how to draw pictures on the canvas with the `image()` helper. I ## Function signature at a glance ```python -from drawzero import image +from drawzero import * image(image, pos, width: int = None, alpha=255) ``` +All examples below follow the same import pattern so that `image()` is available without extra steps. + The four parameters control what file is loaded, where it appears, how wide it becomes, and how transparent it looks. | Parameter | What it means | Required? | Typical values | diff --git a/docs/images.ru.md b/docs/images.ru.md index d989afc..e08e8d6 100644 --- a/docs/images.ru.md +++ b/docs/images.ru.md @@ -5,11 +5,13 @@ ## Краткий обзор сигнатуры функции ```python -from drawzero import image +from drawzero import * image(image, pos, width: int = None, alpha=255) ``` +Все примеры ниже используют такой же импорт, поэтому `image()` сразу доступна без дополнительных шагов. + Четыре параметра управляют тем, какой файл загружается, где он появляется, какой ширины становится и насколько прозрачным выглядит. | Параметр | Что это значит | Обязательный? | Типичные значения | diff --git a/docs/pt.en.md b/docs/pt.en.md index d9d3938..84afe17 100644 --- a/docs/pt.en.md +++ b/docs/pt.en.md @@ -1,7 +1,7 @@ # Pt helper reference -The `Pt` class is a small helper that acts both like a 2D point and like a very light turtle. -It lives in [`drawzero.utils.pt`](https://github.com/ShashkovS/drawzero/blob/master/src/drawzero/utils/pt.py) and is imported for you when you write `from drawzero import *`. +The `Pt` class is a small helper that acts both like a 2D point and like a very light turtle. +It is imported for you when you write `from drawzero import *`. Use `Pt` whenever you want to store a position, move it around, and pass it into the drawing helpers from [Drawing primitives](primitives.md) or [Animations](animation.md). diff --git a/docs/pt.ru.md b/docs/pt.ru.md index 48d64f2..b0c7376 100644 --- a/docs/pt.ru.md +++ b/docs/pt.ru.md @@ -1,7 +1,7 @@ # Справочник по `Pt` Класс `Pt` — это небольшой помощник, который ведет себя и как 2D-точка, и как очень легкая "черепашка". -Он находится в [`drawzero.utils.pt`](https://github.com/ShashkovS/drawzero/blob/master/src/drawzero/utils/pt.py) и импортируется для вас, когда вы пишете `from drawzero import *`. +Он сразу доступен после `from drawzero import *`. Используйте `Pt` всякий раз, когда вы хотите сохранить позицию, перемещать ее и передавать в функции рисования из [Графические примитивы](primitives.md) или [Анимации](animation.md).