Skip to main content

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.27] Version 1.2.1

English:

  • Added Declarative Tween Animation Controller (qgame.tween): Introducing fluid physical polish ("Juice") to games and UI systems without manual timer calculations.
    • Supports 17 standard easing equations (e.g., elastic_out, bounce_out, sine_in_out, etc.).
    • Allows chaining parameters like delay, duration, and on_complete callbacks.
    • Dynamically recalculates screen geometries during UI tweens to prevent clipping.
  • Added Application Custom Font Registry (qgame.Font): Load local .ttf or .otf font file resources on the fly, allowing consistent typography across different OS platforms without system font pre-installation.
  • Upgraded 2D Layout Engine (qgame.Align): Enhanced geometric space partitions.
    • Added grid positioning calculators (.grid(), .row(), .column()) for inventory slots and menu arrangements.
    • Added Flexbox divisions (.fit_row(), .fit_column()) to adaptively stretch and partition canvas space.
  • Added 9-Slice (Nine-Slice) UI Image Skinning: Panel and Button now support set_image_bg(path, top, right, bottom, left). Under window resizing, the margins and 4 corners remain crisp and distortion-free.
  • Robust set_theme() Parameter Fallback: Fixed a TypeError crash when passing partial elements as None. Configured robust keyword-argument protection across Button, Panel, ProgressBar and TextBox. Developers can now customize styles on-demand (e.g. button.set_theme(text_color=...)) without typing redundant None parameters.
  • Rect Iterator Unpacking: Overloaded python's unpacking mechanism (via __iter__) on graphics.Rect. Rect containers can now be destructured directly as coordinate tuples (e.g., x, y, w, h = rect) for drawings.

中文:

  • 新增声明式缓动动画控制器 (qgame.tween):无需在主循环中累加时延计时,实现高水准的游戏与 UI 弹性过渡拟真物理效果。
    • 支持 elastic_out(果冻弹性)、bounce_out(重力降落反弹)、back_out 等 17 种经典插值坐标算法。
    • 支持延迟等待(delay)、运行周期时长和缓动终点的完成回调(on_complete)。
    • 缓动更新会自动触发视口尺寸计算,保证运行平滑顺畅。
  • 新增自定义字体动态加载器 (qgame.Font):提供运行时 Font.load() 机制,支持把包内本地的 .ttf.otf 字体加载注入到游戏引擎,解决跨平台打包字体不一致的宿疾。
  • 升级 2D 矢量画盘布局引擎 (qgame.Align):大幅扩充自适应排版定位计算:
    • 提供批量网格生成器(.grid().row().column()),轻而易举排列背包位和按键行。
    • 引入 CSS Flex 均分思想工具(.fit_row().fit_column()),输入指定范围即可完美均分、拉伸切割矩形空间。
  • 新增点九图(9-Slice、九宫格)UI 贴图背景PanelButton 增加 set_image_bg 支持,保证全屏或拖拽自适应形变时,贴图四角不变形、不模糊。
  • 防御性非空 set_theme() 属性更新:消除了由于部分传入 None 导致获取下标崩溃的缺陷。对 ButtonPanelProgressBarTextBox 的样式更新重构,支持关键字按需更新(例如:button.set_theme(text_color=(0, 255, 0))),免去了传递一长串无用 None 的麻烦。
  • 支持原生迭代解包的 Rect:为矩形容器重载了迭代解构魔法函数(__iter__),允许开发者直接将 Rect 实例当做解包坐标传参(x, y, w, h = rect)给 Draw 绘图函数,开发体验大大精简。

[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):生命周期托管的场景切替管理器。
  • 工具支持:带死区限制的 CameraSpritesheet 雪碧图/合图解析器。

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 会默认开启虚拟像素缩放,这会导致裁剪像素图时计算错误。

  • qgameSpritesheetTilemap 内部已强制指定 DevicePixelRatio1.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:
    dt = clock.tick(60)
    dt = min(dt, 0.03)  # Clamp delta time to maximum 30ms step!
    

在玩家拖拽窗口标题栏、缩放或者桌面弹出系统对话框时,Qt 主线程会被挂起。松开鼠标后瞬时传回的 Delta Time ($dt$) 会发生累积暴涨。一旦 $dt$ 激增,角色单帧的位移增量就会超出普通阻挡物强度的厚度,直接发生穿模隧穿。

  • 规避手段:请在更新角色的物理判定前强行写入单帧变化量限幅限制,截住时延信号:
    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 指令明确断开引用指针:
    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 批量打包刷图,以此节省创建/消解状态机的上下文消耗。

Installation & Running Demo

If installed via setuptools, run the demo directly in the terminal:

run-qgame-examples

Or run as a module:

python -m qgame

Editor Mode

Launch the built-in tilemap maker:

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.
  • wait_for_event(event_type: int, timeout: float = None) -> Event | None Blocks execution to wait for a specific event type.
  • get_key_state(key_code: int) -> bool Smooth keyboard query that bypasses system repeats.

Clock (Class)

  • tick(fps: int) -> float Controls the game frame rate and returns dt (Delta Time in seconds).

Tween System (qgame.tween) (New)

tween (TweenManager Instance)

Used to construct smooth declarative animations.

  • to(target, duration: float, ease: str = "linear", delay: float = 0.0, on_complete: Callable = None, **properties) Creates an active tween.
    • target: Target object or dictionary.
    • duration: Animation duration in seconds.
    • ease: Math interpolation key word (e.g. "elastic_out", "bounce_out", "quad_in_out", "sine_out").
    • properties: Parameters to modify, like x=500 or alpha=1.0.
  • update(dt: float) Ticks all running tween calculations. Call once per frame in your main loop.
  • clear() Flushes all animations.

ECS & Entity System (qgame.ecs)

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)

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.layout)

UI position calculation presets and automatic 2D grid partitions:

  • 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]
  • top_right(canvas, offset_x, offset_y, width) -> tuple[int, int]
  • bottom_left(canvas, offset_x, offset_y, height) -> tuple[int, int]
  • bottom_right(canvas, offset_x, offset_y, width, height) -> tuple[int, int]
  • center(canvas, width, height) -> tuple[int, int]
  • grid(x, y, rows, cols, cell_width, cell_height, spacing_x=0, spacing_y=0) -> list[Rect] Returns an array of Rect structures representing grid slots.
  • row(x, y, count, cell_width, cell_height, spacing=0) -> list[Rect] Horizontal一维 row partitioning.
  • column(x, y, count, cell_width, cell_height, spacing=0) -> list[Rect] Vertical一维 column partitioning.
  • fit_row(parent_rect: Rect, count, spacing=0) -> list[Rect] Divides a parent Rect horizontally into count sections.
  • fit_column(parent_rect: Rect, count, spacing=0) -> list[Rect] Divides a parent Rect vertically into count sections.

Font (Class) (New)

  • load(font_path: str) -> str Loads local .ttf or .otf file and registers it. Returns the registered font family name.

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. Supports packing unpack iterates (e.g. x,y,w,h = rect).
  • 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 gravity is 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) (Updated)

  • Custom Styling: All theme methods support keyword arguments (e.g., set_theme(text_color=(0, 255, 0))). You only need to pass properties you wish to modify.

Button (Class)

  • __init__(x, y, w, h, text="")
  • set_theme(normal_bg=None, hover_bg=None, pressed_bg=None, border_color=None, text_color=None, border_radius=None, font_size=None)
  • set_image_bg(image_path: str, top=12, right=12, bottom=12, left=12) Applies 9-Slice layout stretch styles.

Panel (Class)

  • __init__(x, y, w, h, title="Window")
  • set_theme(header_bg=None, content_bg=None, border_color=None, border_radius=None, font_size=None)
  • set_image_bg(image_path: str, top=24, right=24, bottom=24, left=24) Applies 9-Slice layout stretch styles.
  • add_widget(obj): Nest UI elements dynamically.

Label (Class)

  • set_theme(text_color=None, bg_color=None, font_size=None)

ProgressBar (Class)

  • set_theme(bg_color=None, fill_color=None, border_color=None, text_color=None, border_radius=None, border_width=None, font_size=None)

TextBox (Class)

  • set_theme(bg_color=None, text_color=None, border_color=None, border_radius=None, font_size=None)

Scene Management (qgame.scene)

Scene (Base Class)

Extend this to organize game states.

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

QGame: So good, even the British won‘t go back home. Because they are learning Chinese — and coding with QGame. 😉

安装与运行演示

如果通过 setuptools 安装了库,可以在终端直接运行演示:

run-qgame-examples

或作为模块运行:

python -m qgame

地图编辑器启动指令

内置的关卡拼装器,快速在电脑端直观拼装地图:

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 获取鼠标位置。
  • wait_for_event(event_type: int, timeout: float = None) -> Event | None 局部阻塞当前线程,直到指定的系统事件发生或达到超时秒数。
  • get_key_state(key_code: int) -> bool 键盘状态侦测。绕过系统按键重频延迟。

Clock (时钟类)

  • tick(fps: int) -> float 锁定帧率并返回两帧之间的间隔时长 dt(单位:秒)。

Tween 缓动插值系统 (qgame.tween) (新)

tween (它的全局单例实例)

通过声明式编程快速构建平滑渐变动效。

  • to(target, duration: float, ease: str = "linear", delay: float = 0.0, on_complete: Callable = None, **properties) 分派注册一个缓动效果。
    • target: 渐变的目标 Python 对象或字典容器。
    • duration: 缓动执行总时长(秒)。
    • ease: 缓动插值计算的数学函数关键字(如 "elastic_out""bounce_out""sine_out" 等)。
    • properties: 要变换的目标值健值对,例如 x=300, alpha=1.0
  • update(dt: float) 微步驱动正在进行的全部缓动插值。每帧在主循环中tick调用更新。
  • clear() 清除销毁所有的缓动记录。

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.Wkeys.ESCAPEkeys.UPkeys.SPACEkeys.SHIFT 等。

keyboard (键盘状态侦测)

  • is_pressed(key_code: int) -> bool 检测某按键当前是否正被按住。

mouse (鼠标状态侦测)

  • get_pos() -> tuple[int, int] 获取鼠标在虚拟画布分辨率上的相对坐标点 (x, y)
  • is_pressed(button: int) -> bool 检测某鼠标键当前是否被按住(传参例如 mouseButtons.LEFTmouseButtons.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.layout)

UI 快速换算与自适应网格均分布局器:

  • 文字 debug 默认行高LINE_1 (Y=20), LINE_2 (Y=50), LINE_3 (Y=80)。
  • top_left(offset_x, offset_y) -> tuple[int, int]
  • top_right(canvas, offset_x, offset_y, width) -> tuple[int, int]
  • bottom_left(canvas, offset_x, offset_y, height) -> tuple[int, int]
  • bottom_right(canvas, offset_x, offset_y, width, height) -> tuple[int, int]
  • center(canvas, width, height) -> tuple[int, int]
  • grid(x, y, rows, cols, cell_width, cell_height, spacing_x=0, spacing_y=0) -> list[Rect] 平面网格计算,返回一个扁平化的 Rect 数组,代表所有的排列位置。
  • row(x, y, count, cell_width, cell_height, spacing=0) -> list[Rect] 横向一维列兵排部。
  • column(x, y, count, cell_width, cell_height, spacing=0) -> list[Rect] 纵向一维竖向菜单条排部。
  • fit_row(parent_rect: Rect, count, spacing=0) -> list[Rect] 模仿 Flex 横向排版。在父 Rect 区域深度等比均分切片出 count 个横排单元。
  • fit_column(parent_rect: Rect, count, spacing=0) -> list[Rect] 在父 Rect 区域等比均分切片出 count 个纵排单元。

Font (字体管理类) (新)

  • load(font_path: str) -> str 提取加载本地的 .ttf.otf 字体文件,成功后返回字体所属的 Font Family 名称。

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) 高精度浮点数矩形存储容器。支持原生的迭代解包机制,通过 x, y, w, h = rect 即可解包传入绘图方法。
  • 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=Truerestitution 代表绝对弹性指数(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) (已更新)

  • 按需修改属性风格:所有 UI 控件的 set_theme() 均支持可选的关键字参数传入(如 set_theme(text_color=(255, 0, 0))),无需写多余的 None

Button (按键类)

  • __init__(x, y, w, h, text="")
  • set_theme(normal_bg=None, hover_bg=None, pressed_bg=None, border_color=None, text_color=None, border_radius=None, font_size=None)
  • set_image_bg(image_path: str, top=12, right=12, bottom=12, left=12) 设置点九图背景,四边参数为像素切片距离。

Panel (拖拽容器类)

  • __init__(x, y, w, h, title="Window")
  • set_theme(header_bg=None, content_bg=None, border_color=None, border_radius=None, font_size=None)
  • set_image_bg(image_path: str, top=24, right=24, bottom=24, left=24) 设置点九图背景,支持无损全屏拉伸。
  • add_widget(obj):塞入 UI 控件实现递归级联自适应缩放。

Label (标签类)

  • set_theme(text_color=None, bg_color=None, font_size=None)

ProgressBar (进度条类)

  • set_theme(bg_color=None, fill_color=None, border_color=None, text_color=None, border_radius=None, border_width=None, font_size=None)

TextBox (文本框类)

  • set_theme(bg_color=None, text_color=None, border_color=None, border_radius=None, font_size=None)

游戏场景结构 (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.08.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 配置文件字典。

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

qgame-1.3.0.tar.gz (3.1 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

qgame-1.3.0-py3-none-any.whl (3.1 MB view details)

Uploaded Python 3

File details

Details for the file qgame-1.3.0.tar.gz.

File metadata

  • Download URL: qgame-1.3.0.tar.gz
  • Upload date:
  • Size: 3.1 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for qgame-1.3.0.tar.gz
Algorithm Hash digest
SHA256 b3c616411f94ac1e401686224e156e5cce94ffb388ea6c79ddc1ad4369f210da
MD5 d0064741c53bdfe735fdf09cc899a3fd
BLAKE2b-256 a1b66e67dc35bf3bece9d4b4a631dfabf8bb3493898b1a458dd1b7f1a3ad063b

See more details on using hashes here.

File details

Details for the file qgame-1.3.0-py3-none-any.whl.

File metadata

  • Download URL: qgame-1.3.0-py3-none-any.whl
  • Upload date:
  • Size: 3.1 MB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.6

File hashes

Hashes for qgame-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f795ec318162c21fbc5b5ec6ad4605b51fb2cb6bf9168d494238c193a0e0a057
MD5 3da4ced6edf3afd8da3b8b4764cfc6bb
BLAKE2b-256 4872c7a027d9d5d79b7a7fc199ccc5a943b4a2f7dff42b48dbb94ffc22070c9b

See more details on using hashes here.

Release history Release notifications | RSS feed

1.27.0

2 files

1.26.0

2 files

1.25.2

2 files

1.25.1

2 files

1.25.0

2 files

1.24.0

2 files

1.23.2

2 files

1.23.1

2 files

1.23.0

2 files

1.22.0

2 files

1.21.0

2 files

1.20.0

2 files

1.19.1

2 files

1.19.0

2 files

1.18.0

2 files

1.17.0

2 files

1.16.0

2 files

1.15.1

2 files

1.15.0

2 files

1.14.1

2 files

1.14.0

2 files

1.13.0

2 files

1.12.0

2 files

1.11.2

2 files

1.11.1

2 files

1.11.0

2 files

1.10.2

2 files

1.10.1

2 files

1.10.0

2 files

1.9.0

2 files

1.8.0

2 files

1.7.0

2 files

1.6.1

2 files

1.6.0

2 files

1.5.3

2 files

1.5.2

2 files

1.5.1

2 files

1.5.0

2 files

1.4.0

2 files

This release

1.3.0 This release

2 files

1.2.1

2 files

1.2.0

2 files

1.1.3

2 files

1.1.2

2 files

1.1.1

2 files

1.1.0

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page