Metadata-Version: 2.4
Name: qgame
Version: 1.2.1
Summary: A professional game library based on PySide6
Author: WatermelonCode
Author-email: watermeloncode@foxmail.com
License: MIT
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PySide6>=6.0.0
Dynamic: author
Dynamic: author-email
Dynamic: description
Dynamic: description-content-type
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: summary

# QGame Engine

A lightweight, modern, and high-performance 2D game framework built on PySide6. Designed to draw like Pygame, yet harness the power of modern UI systems, absolute path scaling, high-performance memory image operations, and smooth matrix transformations.

QGame Engine 是一个基于 PySide6 构建的轻量级、现代且高性能的 2D 游戏开发框架。它在提供类似于 Pygame 的极简绘制 API 的同时，还融合了现代 UI 系统接口、无 DPI 偏差缩放、高性能内存位图离屏缓冲以及轻量平滑的矩阵变换。

---

# Changelog / 更新日志

### [2026.07.26] Version 1.2.0

**English:**
*   **Added ECS (Entity Component System)**: Unifies game entities (monsters, bullets, players) under the `Entity` base class for convenient batch lifecycle management.
    *   **Y-Sorting**: Resolves depth-occlusion relation (e.g., player walking behind a tree trunk).
    *   **Size-Sorting**: Automatically rendering entities sorted by their scaling factor to simulate perfect depth perception in side-scrolling pseudo-3D games.
*   **Extreme Performance Optimization for Particle System**: Refactored unoptimized OOP allocations with Flat List batch management.
*   **Tilemap Engine & Built-in Editor**: Hand-crafting tilemaps is tedious. We bootstrapped a "QGame Tilemap Editor" using the QGame library! No extra downloads needed—simply run `python -m editor`! (Note: The exported `.qmap` map packet is heavily encrypted/obfuscated—don't even think about manually reversing it! 😉)

**中文:**
*   **添加 ECS 实体组件系统**：游戏中的怪物、子弹、玩家统一继承于 `Entity`，更方便进行批量的生命周期与碰撞关系更新。
    *   **Y-Sorting（Y轴深度排序）**：解决了前后景深遮蔽关系，例如玩家走向树木后方时能被树冠完美遮挡。
    *   **Size-Sorting（缩放深度排序）**：在伪 3D 横版街机游戏场景中，根据物体大小进行智能分层，带来绝佳的立体感。
*   **粒子系统性能飞跃优化**：重构了落后的 OOP 渲染管线，采用扁平化内存批处理（Flat List Batching）大幅提升同屏计算上限。
*   **Tilemap 瓦片层架与自举编辑器**：为了消除手写大地图矩阵的痛苦，我们用 QGame 框架自研了一个“QGame 瓦片地图编辑器”！无需配置额外编译器，下载本库后在终端键入指令： `python -m editor` 即可一键启动。（注意，编辑器保存导出的 `.qmap` 文件为强混淆高压加密文件，以防美术资源被逆向提取哦~）

#### 粒子同屏性能对比表格 / Performance Comparison (60Hz Target)

| 粒子同屏数量 (Particles count) | 未优化的 OOP 方案 (Unoptimized OOP) | 优化后的 Flat List 批处理方案 (Optimized Batching) |
| :----------------------------- | :---------------------------------- | :------------------------------------------------- |
| **200 个**                      | 60 FPS (CPU 占用 ~25%)              | 60 FPS (CPU 占用 ~2%)                              |
| **500 个**                      | 35-45 FPS 出现卡顿 (CPU ~80%)       | 60 FPS (CPU 占用 ~5%)                              |
| **1500 个**                     | 12 FPS 严重幻灯片 (CPU 100%)        | 60 FPS 稳定运行 (CPU ~18%)                          |
| **3000 个**                     | 驱动写死无响应 (Crash/Freeze)       | 45-55 FPS 依然丝滑可玩                             |

### [2026.07.25] Version 1.1.2
**English:**
*   **Patch**: Document changes

**中文:**
*   **补丁**: 文档更改

### [2026.07.25] Version 1.1.1
**English:**
*   **Patch**: the sample command program had a problem, which has now been resolved

**中文:**
*   **补丁**: 示例命令程序有问题，目前已解决

### [2026.07.25] Version 1.1.0
**English:**
*   **Major Second Generation Update**: Added core modules and presets for commercial-grade 2D games.
*   **Color Presets (`qgame.color` / `Color` class)**: Predefined colors including standard, dark/light variants, game-specific ambient masks (e.g. night filters), and alpha-blending shadows.
*   **Layout Alignment Helpers (`qgame.align`)**: Standardized debug print lines and dynamic screen centering helpers.
*   **Enhanced Camera**: Smooth linear interpolation (`lerp_speed` dampening), shake FX, and bounding lock logic suited for large-world coordinate projection.
*   **Real 2D Rigid Body Physics Engine**: Added collision solver using Impulse-Clamping, material elasticity, and friction coefficients.
*   **Interactive Demos**: Run the updated desktop examples directly using the command `run-qgame-examples`.

**中文:**
*   **第二代版本大更新**：补充了商业级 2D 游戏最常用的一系列预设与核心模块。
*   **游戏色彩预设，Color类 (`qgame.color`)**：内置了标准基础色、暗色调、游戏特制滤镜（如夜幕遮罩）以及各类半透明 shadow 混合色，消除魔鬼数字。
*   **全局排版 & 定位预设，Align类 (`qgame.align`)**：提供标准行渲染基准行高，并增加动态边缘偏移与画布中心定位函数。
*   **更好的 Camera**：实现了带阻尼的平滑镜头跟随、多维震屏，支持无限大世界坐标系向主显示视口的偏移映射。
*   **真实的 2D 物理引擎**：引入了带摩擦力、弹力、重力加速度的刚体求解器与窄相 OBB 碰撞分离机制。
*   **示例程序更新**：使用终端命令 `run-qgame-examples` 即可启动全新的大世界物理与光影效果综合演示。

### [2026.07.24] Version 1.0.0
**English:**
*   **First Generation Release (Initial Version)**.
*   **Core Game Pipeline (`qgame`)**: Window lifecycle and OpenGL hardware acceleration.
*   **Input Processing (`qgame.keyboard` & `qgame.mouse`)**: Real-time keystroke and pointer tracking.
*   **2D Graphics (`qgame.graphics`)**: Antialiased geometric drawings and offscreen image buffers.
*   **AABB Collision System (`qgame.collision`)**: Low-overhead shape overlaps check.
*   **Audio Engine (`qgame.audio`)**: Sound effects player and streaming background music playback.
*   **UI Input Box (`qgame.ui`)**: Adaptive `TextBox` supporting system IME and resizing.
*   **Scene Architecture (`qgame.scene`)**: Unified stage lifecycle management.
*   **Advanced Tools**: `Camera` tracking and `Spritesheet` grid/atlas packers parser.

**中文:**
*   **初代版本正式发布**。
*   **核心模块 (`qgame`)**：Qt/OpenGL 底层混合生命周期管理。
*   **输入处理 (`qgame.keyboard` & `qgame.mouse`)**：高反应灵敏的键鼠捕获。
*   **2D 绘图与渲染 (`qgame.graphics`)**：抗锯齿几何画板与离屏图像矩阵翻转。
*   **碰撞检测系统 (`qgame.collision`)**：基础 AABB 数学相交判定。
*   **音频控制系统 (`qgame.audio`)**：音效快速触发与多媒体背景音乐循环。
*   **UI 输入控件 (`qgame.ui`)**：完美兼容输入法与全屏缩放的文本输入框。
*   **游戏场景结构 (`qgame.scene`)**：生命周期托管的场景切替管理器。
*   **工具支持**：带死区限制的 `Camera` 及 `Spritesheet` 雪碧图/合图解析器。

---

# Usage Notes & Precautions / 使用注意事项 ⚠️

To ensure the best development experience and performance, please read the following guidelines:

为了保证最佳的开发体验与稳定性，请在开发时注意以下策略：

### 1. High-DPI Scaling & Device Pixel Ratio (高分屏与设备像素比)
On Windows or macOS with screen scaling (e.g., 125%, 150%, 200%), Qt automatically resizes canvas dimensions, which might distort pixel-art textures. 
*   `qgame.Spritesheet` and `qgame.Tilemap` have built-in `setDevicePixelRatio(1.0)` logic to ensure pixel-perfect crops.
*   When performing manual drawing coordinates, be aware that canvas sizes will automatically fit the actual hardware coordinate points.

在 Windows 10/11 或 macOS 的高分辨率缩放屏幕下，Qt 会默认开启虚拟像素缩放，这会导致裁剪像素图时计算错误。
*   `qgame` 的 `Spritesheet` 与 `Tilemap` 内部已强制指定 `DevicePixelRatio` 为 `1.0`（物理点对点图层）。
*   若你打算自己派生底层的 `QImage` 并直接传递给绘图，请确保使用 `setDevicePixelRatio(1.0)`，防止贴图发生二倍变小。

### 2. Time-Step Tunneling (物理隧穿与 Delta Time 截断限幅)
If you drag, resize, or suspend the OS window, Qt's main thread pauses. Upon release, the accumulative delta time ($dt$) could be abnormally high (e.g., $dt > 1.0$), making the player move hundreds of pixels in a single frame. This will cause the player to pass through thin obstacle walls (tunneling).
*   **Solution**: Always clamp your delta time in the game loop before updating positions or ticking physics worlds:
    ```python
    dt = clock.tick(60)
    dt = min(dt, 0.03)  # Clamp delta time to maximum 30ms step!
    ```

在玩家拖拽窗口标题栏、缩放或者桌面弹出系统对话框时，Qt 主线程会被挂起。松开鼠标后瞬时传回的 Delta Time ($dt$) 会发生累积暴涨。一旦 $dt$ 激增，角色单帧的位移增量就会超出普通阻挡物强度的厚度，直接发生穿模隧穿。
*   **规避手段**：请在更新角色的物理判定前强行写入单帧变化量限幅限制，截住时延信号：
    ```python
    dt = clock.tick(60)
    dt = min(dt, 0.03)  # 强制截断单步上限为 30 毫秒，大步长将拆分为小分段执行
    ```

### 3. File System Lock Releases (文件锁的释放处理)
When parsing JSON or crop sheets dynamically (`run_spritesheet_demo`), if you try to clean up paths/files on Windows immediately after rendering, OS permissions might throw an `Access Denied` error because the GC hasn't collected the cache yet.
*   **Best Practice**: Explicitly delete references using `del sheet, tiles` before calling `os.remove()`.

在 Windows 系统下进行解析大图切片时，若紧接着想要擦除磁盘生成的临时图片缓存，往往由于 Python GC 垃圾回收延时，底层文件权标仍驻留在进程句柄中，抛出拒绝删除异常。
*   **最佳实践**：在用 `os.remove` 销毁数据前，先通过句柄 `del` 指令明确断开引用指针：
    ```python
    del sheet, tiles, atlas
    os.remove("temp.png")
    ```

### 4. Tilemap Grid Renderer Optimization (瓦片辅助网格优化)
Looping through matrix lists and starting a dedicated paint device for each tile individually (like multiple local `qgame.draw.rect` calls) is highly unoptimized.
*   **Best Practice**: For drawing wireframes or customized debugging visuals, instantiate a single backend `QPainter` block to do batch renders. See `run_tilemap_demo` implementation details.

遍历瓦片矩阵并在底层开启成百上千次 `QPainter` 画笔绘制调试线会造成严重的 CPU 瓶颈。
*   **最佳实践**：如需显示自定义的大图或者碰撞线描，应当像 `run_tilemap_demo` 那样使用单局部的 Painters 批量打包刷图，以此节省创建/消解状态机的上下文消耗。

---

# English Reference

## Installation & Running Demo
If installed via setuptools, run the demo directly in the terminal:
```bash
run-qgame-examples
```
Or run as a module:
```bash
python -m qgame
```

---

## Editor Mode (New)
Launch the built-in tilemap maker:
```bash
python -m editor
```
Design your level layers, brush block collisions, and hit "Save Map" to export the secure binary `.qmap` mapping config directly.

---

## Core Module (`qgame`)

### Functions
* **`init()`**
  Initializes the PySide6 Application context. Must be called before any graphics operations.
* **`set_settings(*, width: int, height: int, title: str = "QGame") -> QImage`**
  Sets the game window resolution and title. Returns the primary QImage canvas for rendering.

### `window` (Window Instance)
* **`update()`**
  Redraws the window and processes window events. Call once per frame inside the game loop.
* **`set_title(title: str)`**
  Dynamically changes the window title.
* **`set_icon(icon_path: str)`**
  Loads and sets the window icon.
* **`set_size(width: int, height: int) -> QImage`**
  Changes the canvas dimensions dynamically.
* **`toggle_fullscreen()`**
  Toggles between fullscreen and windowed modes.
* **`show_cursor(visible: bool)`**
  Shows or hides the OS cursor.

### `events` (Events Instance)
* **`get() -> List[Event]`**
  Pulls and returns all pending events in the queue.
* **`get_mouse_pos() -> tuple`**
  Get the mouse position in the window

### `Clock` (Class)
* **`tick(fps: int) -> float`**
  Controls the game frame rate and returns `dt` (Delta Time in seconds).

---

## ECS & Entity System (`qgame.ecs`) (New)

### `Entity` (Class)
Inherit `Entity` to build custom game actors. Under rendering structures, it supports layered sorting indices.
* **Properties**: `x`, `y`, `size` (for Size-Sorting).
* **Methods**: `update(dt)`, `draw(canvas)`.

### `EntityManager` (Class)
Managers your main world lists.
* **`add(entity: Entity)`**
* **`remove(entity: Entity)`**
* **`clear()`**
* **`update(dt)`**: Updates all components.
* **`draw(canvas)`**: Evaluates camera coordinates and renders with automatic layer sorting.
* **`auto_layer_y = True`**: Resolves classic Y-Sorting relationships.
* **`auto_layer_s = True`**: Sorts by structural scale sizes (size depth).

---

## Particle System (`qgame.particles`) (New)

### `ParticleEmitter` (Class)
Uses flat arrays in memory to optimize particles computation and drawings.
* **`create_rain(width)`**: Spawns rainfall particles.
* **`create_fire(x, y)`**: Spawns campfire floating embers.
* **`create_explosion(x, y)`**: Spawns one-shot cluster particles that auto-dispose.

---

## Input Module (`qgame.keyboard`, `qgame.mouse`)

### `keys` (Key Mapping Constants)
Contains PySide6 key code constants, e.g., `keys.W`, `keys.ESCAPE`, `keys.UP`, `keys.SPACE`, `keys.SHIFT`, etc.

### `keyboard` (Keyboard Detection)
* **`is_pressed(key_code: int) -> bool`**
  Returns `True` if the specified key is currently down.

### `mouse` (Mouse Detection)
* **`get_pos() -> tuple[int, int]`**
  Returns virtual canvas coordinates `(x, y)` of the mouse.
* **`is_pressed(button: int) -> bool`**
  Returns `True` if the specified mouse button is down (`mouseButtons.LEFT`, `mouseButtons.RIGHT`, `mouseButtons.MIDDLE`).

---

## Graphics Module (`qgame.graphics`)

### `Color` (Class Constant - `qgame.color`)
A collection of preset color tuples for rendering:
* **Standard**: `WHITE`, `BLACK`, `RED`, `GREEN`, `BLUE`, `YELLOW`, `ORANGE`, `PURPLE`, `PINK`, `CYAN`, `BROWN`, `GRAY`.
* **Dark Variants**: `DARK_RED`, `DARK_GREEN`, `DARK_BLUE`, `DARK_GRAY` (Iron/Stone block).
* **Vibrant & Special**: `LIGHT_GREEN` (Healing), `LIGHT_BLUE` (Frost), `LIGHT_YELLOW`, `GOLD`.
* **FX & Environment**: `WOOD_BG` (Wood tiles), `NIGHT_MASK` (Darkness layer, RGBA: `10, 10, 25, 248`), `PLAYER_GLOW` (Warm lamp), `TARGET_GREEN` (Crosshair).
* **Translucent (RGBA)**: `TRANSPARENT`, `SHADOW_50`, `SHADOW_80` (Pause mask), `WHITE_GLOW`.

### `Align` (Use - `qgame.align`)
UI position calculation presets:
* **Debug Line Y-coordinators**: `LINE_1` (Y=20), `LINE_2` (Y=50), `LINE_3` (Y=80).
* **`top_left(offset_x, offset_y) -> tuple[int, int]`**
* **`center(canvas) -> tuple[int, int]`**

### `Image` (Class)
Represents a source image cached in memory.
* **`__init__(source: str | Image | QImage)`**
  Wraps a path, another image instance, or QImage. Performs zero-IO memory copy when using an existing image.
* **`resize(width: int, height: int, keep_aspect: bool = False)`**
  Rescaless the active image.
* **`scale(factor_x: float, factor_y: float = None, keep_aspect: bool = True)`**
  Scales by percentage multipliers.
* **`rotate(angle: float)`**
  Rotates the image (degrees, clockwise).
* **`flip(horizontal: bool = True, vertical: bool = False)`**
  Flips the image.
* **`reset()`**
  Reverts the image to its original clean state.
* **`width` / `height`**
  Properties returning active resolution.

### `Rect` (Class)
* **`__init__(x, y, width, height)`**
  A float-precision 2D rectangle container.
* **`center` / `centerx` / `centery`**
  Properties to read/write center coordinates.
* **`collidepoint(pos: tuple) -> bool`**
  Returns `True` if a coordinate is inside the boundary.

### `draw` (Draw Utility)
* **`fill(canvas, color)`**
  Clears the canvas with a solid color `(r, g, b)`.
* **`rect(canvas, color, rect, width=0)`**
  Draws a rectangle. `width=0` fills it.
* **`rounded_rect(canvas, color, rect, radius, width=0)`**
  Draws an antialiased rounded rectangle.
* **`circle(canvas, color, center, radius, width=0)`**
  Draws an antialiased circle.
* **`ellipse(canvas, color, rect, width=0)`**
  Draws an ellipse inside a bounding box.
* **`line(canvas, color, start, end, width=1)`**
  Draws an antialiased segment line.
* **`text(canvas, text, coords, size=16, color=(255,255,255), font_name="")`**
  Draws a high-fidelity antialiased text.
* **`image(canvas, img, coords, center=False, src_rect=None, opacity=1.0)`**
  Draws a fast-blended image, supports center tracking, sub-rect cropping, and transparency.

---

## Collision Module (`qgame.collision`)

### Methods
* **`check_rect(rect1: tuple, rect2: tuple) -> bool`**
  Rect-to-Rect AABB intersection.
* **`check_circle(pos1, r1, pos2, r2) -> bool`**
  Circle-to-Circle intersection.
* **`check_rect_circle(rect, center, radius) -> bool`**
  Rect-to-Circle intersection.
* **`check_point_rect(point, rect) -> bool`**
  Point-in-Rect containment.
* **`check_point_circle(point, center, radius) -> bool`**
  Point-in-Circle containment.

---

## Physics Module (`qgame.physics`)

### `PhysicsWorld` (Class)
Manages the simulation of dynamic rigid bodies and gravity.
* **`__init__(gravity_x: float = 0.0, gravity_y: float = 9.8)`**
  Creates a simulation world. Default standard gravity: `600.0` pixels/s² down.
* **`add_body(body: RigidBody)`**
  Registers a rigid body to the simulation solver.
* **`remove_body(body: RigidBody)`**
  Removes a body from the simulation.
* **`step(dt: float)`**
  Iterates the physics clock. Automatically runs multiple sub-steps to resolve constraints and avoid clipping.

### `RigidBody` (Class)
A material dynamic entity in the physics solver.
* **`__init__(shape_type: str, x: float, y: float, width_or_radius: float, height: float = 0, is_static: bool = False, mass: float = 1.0, friction: float = 0.5, restitution: float = 0.0)`**
  `shape_type` can be `"circle"` or `"rect"`. Set `is_static=True` for ground/walls. `restitution` controls bounciness.
* **`apply_impulse(impulse_x: float, impulse_y: float, offset: tuple[float, float] = (0, 0))`**
  Applies an instantaneous force vector to push the object (e.g. jumping).

---

## Audio Module (`qgame.audio`)

### `Sound` (Class)
For rapid playback of short sound effects (`.wav`).
* **`play()`, `stop()`**
* **`set_volume(volume: float)`** (0.0 to 1.0)
* **`set_loop(loop: bool)`**

### `Music` (Class)
For streaming long background music tracks (`.mp3`).
* **`play(loop: bool = True)`, `pause()`, `unpause()`, `stop()`**
* **`set_volume(volume: float)`** (0.0 to 1.0)

---

## UI Components (`qgame.ui`)

### `TextBox` (Class)
An advanced GUI input box fully supporting system IME, cursor focus, select all, copy-paste, and scale adaptation.
* **`__init__(x, y, w, h, placeholder="", multi_line=True)`**
* **`set_theme(bg_color, text_color, border_color, border_radius=6, font_size=14)`**
* **`get_text() -> str`, `set_text(text: str)`, `clear()`**
* **`set_focus()`, `set_visible(visible: bool)`**
* **`set_position(x, y)`, `set_size(w, h)`**
* **`destroy()`**
  Completely unmounts and gets garbage-collected.

---

## Scene Management (`qgame.scene`)

### `Scene` (Base Class)
Extend this to organize game states (e.g. MenuScene, LevelScene).
* **`on_enter(*args, **kwargs)`**
  Triggered when switching *into* this scene.
* **`on_exit()`**
  Triggered when switching *out of* this scene. UI children registered via `add_ui()` are automatically destroyed.
* **`handle_event(event)`, `update(dt)`, `draw(canvas)`**
* **`add_ui(widget)`**
  Registers and auto-binds UI components to the lifecycle of this scene.

### `scene_manager`
* **`switch(new_scene_instance, *args, **kwargs)`**
* **`handle_event(event)`, `update(dt)`, `draw(canvas)`**

---

## Advanced Render Accessories

### `Camera` (`qgame.Camera`)
* **`follow(target, lerp_speed)`, **`update(dt)`**
  Smoothly interpolates camera positioning. Default recommended `lerp_speed` is `5.0` to `8.0`.
* **`set_deadzone(w, h)`**
  Enforces a static delay window.
* **`set_bounds(min_x, min_y, max_x, max_y)`**
  Locks camera bounding boxes to prevent displaying black edges.
* **`shake(intensity, duration)`**
  Creates screen shake impulses.
* **`apply(coord_or_rect) -> tuple`**
  Transforms world coordinates to screen coordinate outputs.

### `Spritesheet` (`qgame.Spritesheet`)
* **`get_image(x, y, w, h) -> Image`**
  Crops segment coordinate.
* **`parse_grid(tile_width, tile_height, margin=0, spacing=0) -> list[Image]`**
  Slices uniform sheets.
* **`parse_atlas(json_path) -> dict[str, Image]`**
  Loads TexturePacker configuration sheets.

---
---

# 中文参考文档

## 安装与运行演示
如果通过 setuptools 安装了库，可以在终端直接运行演示：
```bash
run-qgame-examples
```
或作为模块运行：
```bash
python -m qgame
```

---

## 地图编辑器启动指令 (新)
内置的关卡拼装器，快速在电脑端直观拼装地图：
```bash
python -m editor
```
创建多瓦片图层、配置每一格的红色碰撞信息，点击“保存”即可生成加密格式的 `.qmap` 数据文件。

---

## 核心模块 (`qgame`)

### 全局函数
* **`init()`**
  初始化 PySide6 的 Application 上下文。在一切绘制开始前必须最先调用。
* **`set_settings(*, width: int, height: int, title: str = "QGame") -> QImage`**
  设定游戏的分辨率和主窗口标题。返回渲染使用的主画布（`QImage` 实例）。

### `window` (窗口实例)
* **`update()`**
  刷新渲染画面并接收系统事件，在游戏主循环中每帧调用一次。
* **`set_title(title: str)`**
  动态更改窗口标题。
* **`set_icon(icon_path: str)`**
  加载并应用窗口图标。
* **`set_size(width: int, height: int) -> QImage`**
  动态调整画面虚拟画布尺寸。
* **`toggle_fullscreen()`**
  在全屏模式与窗口模式之间无缝切换。
* **`show_cursor(visible: bool)`**
  显示或隐藏系统鼠标光标。

### `events` (事件获取)
* **`get() -> List[Event]`**
  取出事件队列中所有的挂起事件。
* **`get_mouse_pos() -> tuple`**
  获取鼠标位置

### `Clock` (时钟类)
* **`tick(fps: int) -> float`**
  锁定帧率并返回两帧之间的间隔时长 `dt`（单位：秒）。

---

## ECS 实体框架 (`qgame.ecs`) (新)

### `Entity` (实体类)
游戏角色的底层父类，支持结构分层坐标渲染。
* **物理属性**：`x`, `y`, `size`（大小系数，影响 Size 深度层次）。
* **生命周期**：`update(dt)`, `draw(canvas)`.

### `EntityManager` (实体管理类)
管理大世界场景中的所有可见对象。
* **`add(entity: Entity)`**
* **`remove(entity: Entity)`**
* **`clear()`**
* **`update(dt)`**：更新包内注册的每一个动作帧。
* **`draw(canvas)`**：智能过滤并裁剪视框，最后根据层级绘制。
* **`auto_layer_y = True`**：启动 Y 轴前后景遮挡策略。
* **`auto_layer_s = True`**：启动物象大小缩放层次。

---

## 粒子系统 (`qgame.particles`) (新)

### `ParticleEmitter` (粒子类)
基于底层一维线性内存渲染的轻量粒子发生器。
* **`create_rain(width)`**：雨夜倾盆下坠效果。
* **`create_fire(x, y)`**：火把升空呼吸微粒。
* **`create_explosion(x, y)`**：产生一个定点向外爆开并自动消除的集群离子。

---

## 输入处理 (`qgame.keyboard`, `qgame.mouse`)

### `keys` (按键常量映射)
封装了 PySide6 常用的按键码，如 `keys.W`、`keys.ESCAPE`、`keys.UP`、`keys.SPACE`、`keys.SHIFT` 等。

### `keyboard` (键盘状态侦测)
* **`is_pressed(key_code: int) -> bool`**
  检测某按键当前是否正被按住。

### `mouse` (鼠标状态侦测)
* **`get_pos() -> tuple[int, int]`**
  获取鼠标在虚拟画布分辨率上的相对坐标点 `(x, y)`。
* **`is_pressed(button: int) -> bool`**
  检测某鼠标键当前是否被按住（传参例如 `mouseButtons.LEFT`、`mouseButtons.RIGHT` 等）。

---

## 2D 绘图与渲染 (`qgame.graphics`)

### `Color` (预设色彩类 - `qgame.color`)
集成了渲染常用的色彩定义：
* **标准基础色**：`WHITE`, `BLACK`, `RED`, `GREEN`, `BLUE`, `YELLOW`, `ORANGE`, `PURPLE`, `PINK`, `CYAN`, `BROWN`, `GRAY`。
* **暗度变体**：`DARK_RED`, `DARK_GREEN`, `DARK_BLUE`, `DARK_GRAY` (铁板/基础砖墙)。
* **亮度与发光**：`LIGHT_GREEN` (治愈光环), `LIGHT_BLUE` (冰霜), `LIGHT_YELLOW`, `GOLD` (金币)。
* **特效预设色**：`WOOD_BG` (木地底色), `NIGHT_MASK` (极限黑夜滤镜, RGBA: `10, 10, 25, 248`), `PLAYER_GLOW` (玩家灯具微光), `TARGET_GREEN` (鼠标准星)。
* **Alpha半透明**：`TRANSPARENT`, `SHADOW_50`, `SHADOW_80` (暂停弹窗底幕), `WHITE_GLOW` (微白高亮)。

### `Align` (布局辅助类 - `qgame.align`)
UI 快速坐标换算与排版辅助：
* **文字 debug 默认行高**：`LINE_1` (Y=20), `LINE_2` (Y=50), `LINE_3` (Y=80)。
* **`top_left(offset_x, offset_y) -> tuple[int, int]`**：生成偏离视口左上角的定位参数。
* **`center(canvas) -> tuple[int, int]`**：计算画布中心坐标。

### `Image` (图像类)
代表一份缓存在内存中的图片资源。
* **`__init__(source: str | Image | QImage)`**
  接收文件路径、其他图片实例或原生 QImage。在克隆已有的图片时为 0 IO 机制。
* **`resize(width: int, height: int, keep_aspect: bool = False)`**
  重置本张图片分辨率。
* **`scale(factor_x: float, factor_y: float = None, keep_aspect: bool = True)`**
  缩放图片比例。
* **`rotate(angle: float)`**
  旋转图片（单位度，顺时针）。
* **`flip(horizontal: bool = True, vertical: bool = False)`**
  翻转（支持左右、上下镜像翻转）。
* **`reset()`**
  重置图像为没有缩放和旋转前的最初原始数据。
* **`width` / `height`**
  返回当前最新长宽数值的属性。

### `Rect` (矩形容器)
* **`__init__(x, y, width, height)`**
  高精度浮点数矩形存储容器。
* **`center` / `centerx` / `centery`**
  可快速读取和对齐的中心点属性。
* **`collidepoint(pos: tuple) -> bool`**
  判断坐标点是否在该矩形内。

### `draw` (渲染静态方法集合)
* **`fill(canvas, color)`**
  以指定颜色 `(r, g, b)` 填充重刷画布背景。
* **`rect(canvas, color, rect, width=0)`**
  绘制空心/实心矩形（`width=0` 时为实心填充）。
* **`rounded_rect(canvas, color, rect, radius, width=0)`**
  绘制高画质抗锯齿圆角矩形。
* **`circle(canvas, color, center, radius, width=0)`**
  绘制抗锯齿空心/实心圆形。
* **`ellipse(canvas, color, rect, width=0)`**
  绘制包围圈内的椭圆形。
* **`line(canvas, color, start, end, width=1)`**
  绘制抗锯齿直线。
* **`text(canvas, text, coords, size=16, color=(255,255,255), font_name="")`**
  高渲染帧率下的抗锯齿文本绘制。
* **`image(canvas, img, coords, center=False, src_rect=None, opacity=1.0)`**
  快速渲染图面，支持居中校对、局部区域裁剪（`src_rect`）以及透明度叠加。

---

## 碰撞检测系统 (`qgame.collision`)

### 函数方法
* **`check_rect(rect1: tuple, rect2: tuple) -> bool`**
  检测两个矩形是否相交。
* **`check_circle(pos1, r1, pos2, r2) -> bool`**
  检测两圆碰撞冲突。
* **`check_rect_circle(rect, center, radius) -> bool`**
  检测圆与矩形是否相碰。
* **`check_point_rect(point, rect) -> bool`**
  检测点是否在矩形内。
* **`check_point_circle(point, center, radius) -> bool`**
  检测点是否在圆形内。

---

## 物理引擎系统 (`qgame.physics`)

### `PhysicsWorld` (物理世界类)
管理刚体的受力情况及发生碰撞后的物理解算。
* **`__init__(gravity_x: float = 0.0, gravity_y: float = 600.0)`**
  配置重力加速度。默认为 Y 轴向下 `600.0` 像素/秒平方。
* **`add_body(body: RigidBody)`**
  向物理环境里注册一个刚体。
* **`remove_body(body: RigidBody)`**
  将指定刚体移出物理模拟。
* **`step(dt: float)`**
  物理时钟微步前进。自动处理多个子时间步叠影，防止物体卡死穿墙。

### `RigidBody` (刚体类)
受力学约束控制 of 物理对象。
* **`__init__(shape_type: str, x: float, y: float, width_or_radius: float, height: float = 0, is_static: bool = False, mass: float = 1.0, friction: float = 0.5, restitution: float = 0.0)`**
  `shape_type` 可选 `"circle"` 或 `"rect"`。静态地面或不动墙体参数设 `is_static=True`。`restitution` 代表绝对弹性指数（0为像面团无弹力，1为完美钢弹）。
* **`apply_impulse(impulse_x: float, impulse_y: float, offset: tuple[float, float] = (0, 0))`**
  施加瞬时冲量力矢量，用于产生初速度或跳跃运动。

---

## 音频控制系统 (`qgame.audio`)

### `Sound` (音效类)
用于快速播放时间短、反复调用的音效（支持扩展如 `.wav`）。
* **`play()`, `stop()`**
* **`set_volume(volume: float)`** (范围 0.0 - 1.0)
* **`set_loop(loop: bool)`**

### `Music` (背景音乐类)
用于低资源播发大型的背景音乐文件（支持机制如 `.mp3`）。
* **`play(loop: bool = True)`, `pause()`, `unpause()`, `stop()`**
* **`set_volume(volume: float)`** (范围 0.0 - 1.0)

---

## UI 输入控件 (`qgame.ui`)

### `TextBox` (可自适应输入类)
提供游戏内置的多行或单行输入控制。完美支持系统的拼音输入法、光标闪烁、全选、复制粘贴，并支持全屏窗口尺寸改变时的相对比例缩放。
* **`__init__(x, y, w, h, placeholder="", multi_line=True)`**
* **`set_theme(bg_color, text_color, border_color, border_radius=6, font_size=14)`**
* **`get_text() -> str`, `set_text(text: str)`, `clear()`**
* **`set_focus()`, `set_visible(visible: bool)`**
* **`set_position(x, y)`, `set_size(w, h)`**
* **`destroy()`**
  将输入组件彻底从画布卸载销毁并自动回收内存，杜绝视觉残留问题。

---

## 游戏场景结构 (`qgame.scene`)

### `Scene` (场景基类)
实现各种游戏阶段（如 `MenuScene` 菜单场景、`PlayScene` 核心玩法场景）。
* **`on_enter(*args, **kwargs)`**
  进入场景时调用。
* **`on_exit()`**
  退出场景时调用。由 `add_ui()` 挂载的所有组件，在此阶段都会顺便全自动销毁。
* **`handle_event(event)`, `update(dt)`, `draw(canvas)`**
* **`add_ui(widget)`**
  绑定一个 UI 控件到当前的场景生命周期中。

### `scene_manager` (管理器)
* **`switch(new_scene_instance, *args, **kwargs)`**
* **`handle_event(event)`, `update(dt)`, `draw(canvas)`**

---

## 进阶引擎工具

### `Camera` 摄像机对象
* **`follow(target, lerp_speed)`, `update(dt)`**
  平滑追踪绑定物体。推荐将缓动系数 `lerp_speed` 设在 `5.0` 到 `8.0` 之间。
* **`set_deadzone(w, h)`**
  设置相机死区，使其在此长宽区域移动时背景不平移。
* **`set_bounds(min_x, min_y, max_x, max_y)`**
  配置大地图边界限制。防止镜头滑出地图产生黑色虚空。
* **`shake(intensity, duration)`**
  对相机触发一定强度和时长的抖动效果（震屏）。
* **`apply(coord_or_rect)`**
  将游戏内世界坐标在渲染时映射成屏幕的最终像素点配置。

### `Spritesheet` 雪碧图包分析器
* **`get_image(x, y, w, h) -> Image`**
  抓取大图中的单个位置物体图像。
* **`parse_grid(tile_width, tile_height, margin=0, spacing=0) -> list[Image]`**
  规则网格划分图层（适合帧动画等）。
* **`parse_atlas(json_path) -> dict[str, Image]`**
  解析来自 TexturePacker 的 JSON 配置文件字典。
```
