Metadata-Version: 2.4
Name: qgame
Version: 1.0.0
Summary: A professional game library based on PySide6
Author: WatermelonCode
License: MIT
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PySide6>=6.0.0
Dynamic: author
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.

# 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
```

---

## 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.

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

---

## 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`)

### `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)`**
  Rescales 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.

---

## 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.
* **`set_deadzone(w, h)`**
  Enforces a static delay window.
* **`set_bounds(min_x, min_y, max_x, max_y)`**
  Locks camera bounding boxes.
* **`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
```

---

## 核心模块 (`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]`**
  取出事件队列中所有的挂起事件。

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

---

## 输入处理 (`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`)

### `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.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)`**
  平滑追踪绑定物体。
* **`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 配置文件字典。
```
