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.29] Version 1.6.0

English:

  • Debug-window

    • Cross-Window Monitor Panel (DebugInspector)
    • Eliminates messy console terminal print() spam and game loop freezing caused by code breakpoints.
    • Launches a secondary debug window. It does not require any drawing logic in the main loop; rendering is automatically piped through qgame.window.update().
    • *Lifecycle Segregation (is_debug Flag)
    • Introduces a dedicated debug window identifier. Evaluated windows are excluded from get_all_windows() by default.
    • The application exits cleanly when the main game window is closed. Closing the debugger independently will not affect the main game execution.
    • *Lambda Dynamic Binding & Defensive Sandboxing
    • Variables are registered using lambda functions. The inspector queries objects at render time, remaining resilient even if variables are re-instantiated.
    • Built-in exception handling captures runtime issues (e.g., AttributeError or ZeroDivisionError) and renders them in highlighted red instead of crashing the window.
    • Viewport Clipping & Smooth Scroll Engine
    • Tracks wheel events combined with viewport clipping (QPainter.setClipRect) to make data rows slide smoothly within a restricted region without overlaying the header.
    • Slim VS Code-style vertical scrollbar on the right. Height dynamically scales based on the quantity of monitored items.
    • *Adaptive Layout & Scalable Typography
    • Supports customization via a font_size argument in debugger.init. Proportionally converts line height, padding gaps, char-cut limits, and scroll steps on-the-fly.
  • Multi-window update: QGame now supports multiple windows 😄!

    • Use the qgame.window.get_all_windows() function to retrieve all windows; returns a list.
  • Full-screen update: Added a new parameter scaling_mode in the initialization function set_settings to specify the full-screen scaling behavior:

    • letterbox: (Classic default mode) Maintains the design aspect ratio; fills the remaining areas with black bars.
    • crop: (Aspect fill masking mode) The view fills the entire screen without stretching, but automatically and symmetrically crops any overflowing content (e.g., left/right or top/bottom edges).
    • stretch: (Forced stretch mode) The view is forcibly stretched to match the full-screen aspect ratio, ignoring visual quality loss.
    • adaptive: (Viewport-responsive mode, similar to a browser) The canvas resolution dynamically adjusts with window resizing (including full-screen). For example, when the physical resolution becomes 2560×1440, the canvas also becomes 2560×1440 with a 1:1 responsive coordinate mapping.

中文:

  • 调试窗口
    • 跨窗口监视面板 (DebugInspector)
    • 彻底告别繁琐的控制台 print() 刷屏以及断点调试对游戏帧率的打断。
    • 独立多开一个调试窗口,无需在游戏循环中写任何绘制语句,全程由底层 qgame.window.update() 自动驱动渲染。
    • 生命周期隔离机制 (is_debug Flag)
    • 引入调试窗口标识,并在物理窗口管理器 get_all_windows() 中默认隐式滤除。
    • 当玩家关闭游戏主窗口时,程序会立即干净地终止;而单独关闭调试窗口不会对主游戏运行产生干扰。
    • *Lambda 动态绑定与安全沙盒
    • 推荐使用 lambda 匿名函数注册观察变量。调试器在渲染时会动态拉取最新内存指向。
    • 内部集成异常捕获,即使监控的目标变量在游戏中因销毁而引发 AttributeErrorZeroDivisionError,调试器窗口也不会崩溃,而是高亮爆红显示异常类型。
    • *视口裁剪与平滑滚动系统
    • 捕获鼠标滚轮事件,配合视口剪裁技术(QPainter.setClipRect),确保数据行在中间活动区平滑平移,不会溢出盖住顶部的标题栏。
    • VS Code 风格的右侧指示滑动游块,高度随挂载变量的数量自动缩放。
    • *动态排版与自适应字号
    • debugger.init 支持传入自定义字号 font_size,内部会对页眉高度、行高、文字截断字符数和滚动步距进行比例换算,解决大字号重叠溢出的问题。
  • 多窗口更新,QGame支持多窗口啦😄!
    • 使用qgame.window.get_all_windows()函数获取所有窗口,返回一个list
  • 全屏更新,在初始化函数set_settings中新增参数scaling_mode,用于指定全屏的模式:
    • letterbox: (经典默认模式):保持设计比例,不足区域补充黑色填充条。
    • crop: (画幅剪裁遮罩模式,即 Aspect Fill):画面铺满整个屏幕不被拉伸,但自动对称裁切掉超出屏幕的多余部分(如左右或上下)。
    • stretch: (强行拉伸模式):画面无视画质损失,强行贴合全屏比例。
    • adaptive: (视口自适应响应模式,类似浏览器):画布分辨率随窗口改变(包括全屏)而动态扩增/缩小(例如:物理分辨率变成 2560x1440 时,画布变成 2560x1440,坐标系统为 1:1 响应)。

[2026.07.28] Version 1.5.1

English

  • Fixed the level editor, now you can use: run-qgame-editor

中文:

  • 修复关卡编辑器,现在使用:run-qgame-editor即可

[2026.07.28] Version 1.5.0

English:

  • Refactored Collision Module (qgame.collision): Integrated multi-track collider registers: add_active_collider (collidable & block pathfinding nodes), and add_collider (bounds only, ignored by search algorithm).
  • Added Game AI & Automation Module (qgame.ai):
    • PathFinder: Self-adapting pixel-to-grid grid coordinates search utilizing A* logic.
    • TrajectoryPredictor: Solves future positions based on user velocity & quadratic acceleration estimation logs.
    • InputPredictor: Probability forecasting next action keys based on Markov n-gram transition matrix.

中文:

  • 经典碰撞模块重构重设计 (qgame.collision):细化加入了多轨碰撞容器结构。其中 add_active_collider 增加参与碰撞箱(强制避障),add_collider 增加普通碰撞箱(事件与限位,不扰乱 AI 路线)。
  • 新增人工智能控制套件 (qgame.ai)
    • PathFinder (寻路机):集成 A* 格栅搜寻,支持 8 方向平滑移动及高画质像素与网格自适应算法。
    • TrajectoryPredictor (运动预判器):通过二阶物理差分方程,基于历史坐标实时外推未来位置以作包夹拦截。
    • InputPredictor (键鼠预判器):自带有状态转移矩阵,能对连续的操作连招逻辑做出提前防空与预警判定。

[2026.07.28] Version 1.4.0 English:

  • Added Anti-Freeze Task Loader (ProgressBar.load_tasks):
    • Designed for complex task loading processes (e.g. slicing asset decryption or network sync).
    • Accepts a batch array of functions, automatically processing and ticking Qt event queues after executing each task block, ensuring game windows will never throw windows freeze / OS "Not Responding" alerts.
  • Added Engine Splash Screen Controller (qgame.show_splash): Easily show high-fidelity fade transitions for studio logos before loading.
    • Parameters: show_splash(image_path=None, duration=2.0, echo_error=True).
    • No-Image-Safety: If the specified image path does not exist, QGame will dynamically draw a technology-blue fallback studio logo and save it to qgame/images/QGameOnStartingImage.png to avoid crashes.
    • Embedded QEventLoop: Fades transparent masks dynamically without halting win desktop resizing.
  • Added Game Video Playback Component (VideoPlayer):
    • Designed for processing full-screen opening CG movies, dynamic cutscenes, or loopable video-driven UI backgrounds.
    • Features: play(), pause(), stop(), set_volume(volume: float), set_loop(loop: bool), and finished scene transitions connect_finished(callback).
    • Failsafe Mode: If the host lacks media source decoding packages, it falls back smoothly to avoid fatal engine crashes.
  • Added Non-Blocking Network Component Framework (qgame.network):
    • Designed for processing multiplayer synchronization without spawning tricky system Python loops.
    • Provides event-driven callback hooks for easy packet parsing.
    • Submodules:
      • network.UDPNetworkServer & network.UDPNetworkClient for real-time game positioning.
      • network.WSNetworkServer & network.WSNetworkClient for lobby chatting and state alignment.

中文:

  • 新增防死挂起加载器 (ProgressBar.load_tasks)
    • 针对复杂资产读取、切图或数据解密等高开销初始化关卡。
    • 接收无参函数组成的加载列表,核心在执行单个任务间隙全自动重刷系统事件、刷新进度,彻底排除客户端“未响应”沙漏警报。
  • 新增游戏引擎启动闪屏控制 (qgame.show_splash):在游戏启动前展示带动态淡入淡出滤镜的工作室大片 Logo。
    • 参数支持形式:show_splash(image_path=None, duration=2.0, echo_error=True)
    • 文件缺失卫士:若无指定路径,将自动读取内置闪屏图;当内置资源也不存在时,会自动在画布上矢手高密绘制一张 QGame 蓝色圆形极简 Logo 存至磁盘(qgame/images 下),保护引擎逻辑稳定不倒。
    • 无锁心跳:在不中断事件队列获取的条件下,流畅地处理淡入淡出遮罩。
  • 新增剧情与转场视频播放器芯片 (VideoPlayer)
    • 针对开场大片 CG、关卡剧情重塑、动态背景视频 UI 的专业原生多媒体封装。
    • 核心指令:play() (播放)、pause() (暂停)、stop() (停止归零)、set_volume(float) (音量,0.0~1.0)、set_loop(bool) (配置循环状态)、connect_finished(callback) (完结跳过事件槽)。
    • 智能减震:运行环境或缺失 ffmpeg/多媒体驱动时自动做平滑捕获不闪退,避免影响主游戏编译。
  • 新增低耦合事件网络骨架库 (qgame.network)
    • 基于 Qt 事件系统封装的无锁非阻塞局域网及公网联机方案。
    • 剥离了繁琐的多线程和同步死锁,将复杂的网络连接重塑为极简回调式交互。
    • 核心大类:
      • network.UDPNetworkServer / network.UDPNetworkClient:对应高速帧同步、大弹幕交互场景。
      • network.WSNetworkServer / network.WSNetworkClient:对应回合制决策、聊天大厅与云备份接入场景。

[2026.07.27] Version 1.3.0

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", icon_path: str = None, scaling_mode: Literal["letterbox", "crop", "stretch", "adaptive"] = "letterbox") -> QImage Sets the game window resolution and title. Returns the primary QImage canvas for rendering.
  • show_splash(image_path: str = None, duration: float = 2.0, *, echo_error: bool = True) Display the game launch splash screen with smooth semi-transparent transitions of fade in and fade out. If no parameter is passed, use the QGame logo. If the path does not exist and echo_error is True, raise FileNotFoundError; otherwise, print the error.

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.
  • get_all_windows() -> list Return all window instances

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 (Progress Bar Class)

  • load_tasks(tasks: list, on_progress: Callable = None, on_complete: Callable = None) Sequentially execute the list of time-consuming step functions passed in, forcibly refresh the event loop between tasks to prevent white screen and freezing issues.
  • tasks: List of functions with no parameters.
  • on_progress: Stage update callback, returns (current index, total task count, return value of that task).
  • on_complete: No-parameter callback called after all work is ready.

TextBox (Class)

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

VideoPlayer (Native Video Viewport Player)

  • __init__(x: int, y: int, width: int, height: int, loop: bool = False) Creates an independent video rendering layer in the viewport with absolute width and height coordinates.
  • load(file_path: str) Binds a local audio and video stream media file.
  • play() / pause() / stop() Basic video playback control.
  • set_volume(volume: float) Sets the channel volume ratio (0.0 is completely silent, 1.0 is full volume).
  • set_loop(loop: bool) Sets whether to loop playback of the current track.
  • connect_finished(callback: Callable) Binds a no-argument callback to be triggered when the video naturally reaches the end (used for automatically fading into the level after the story finishes).
  • destroy() Destroys the multimedia window and completely frees the memory and audio decoding channel usage.

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.

🌐 Network Skeleton Interface Reference (qgame.network)

Network communication is based on QtNetwork's non-blocking mechanism. You may directly override the logic or bind to the connect data slots.

📡 1. UDP Packet Network Component

UDPNetworkServer (UDP Server Listener)

  • __init__(port: int) - Sets the target port for network listening on the local machine.
  • start() -> bool - Starts listening; returns whether the binding was successful.
  • send_to(data: bytes, host: str, port: int) - Broadcasts the byte packet to the specified network address.
  • connect_receive(callback: Callable) - Connects to the receive signal slot. Callback signature: callback(data: bytes, ip: str, port: int).
  • close() - Unregisters the socket.

UDPNetworkClient (UDP Client)

  • start(local_port: int = 0) -> bool - Opens a local socket for communication.
  • send(data: bytes, host: str, port: int) - Sends a network packet.
  • connect_receive(callback: Callable) - Connects to the response receive signal.

🕸️ 2. WebSocket Lobby Component

It has already been placed in qgame/examples/Web/UPD

WSNetworkServer (WebSocket Server)

  • __init__(port: int, server_name: str = "QGame") - Initializes the server.
  • start() -> bool - Starts WebSocket listening.
  • broadcast(message: str) - Broadcasts a message to all connected clients.
  • send_to(client_socket, message: str) - Sends a text message to a specific client channel.
  • connect_client(callback) / connect_disconnect(callback) - Callback slots for client connection and disconnection events.
  • connect_message(callback) - Parses messages from a client. Callback signature: callback(client_socket, message: str).

WSNetworkClient (WebSocket Client)

  • connect_to(url: str) - Connects to the target endpoint, e.g., ws://127.0.0.1:80.
  • send(message: str) - Sends a text command packet.
  • connect_open(callback) / connect_close(callback) - Callbacks for successful connection and disconnection.
  • connect_message(callback) - Listens for messages from the server. Callback signature: callback(message: str).

🤖 3. Game AI Reference (qgame.ai)

🧭 1. A* Smart Pathfinding Component (PathFinder)

  • find_path_on_screen(start_pos: tuple, end_pos: tuple, screen_w: int, screen_h: int, grid_size: int = 32) -> list (Core Recommendation) Input the start screen coordinates and the target pixel coordinates. The algorithm will automatically pull the currently active physics collision boxes stored in collision.active_colliders as grid obstacles and perform 8-direction A* pathfinding. Returns a smoothed array of screen pixel target waypoints.

🔮 2. Behavior Predictor Class (TrajectoryPredictor)

  • __init__(history_len: int = 15) - Initializes the prediction queue depth.
  • update(pos: tuple) - Inputs the current position coordinates (x, y) of the target character being followed.
  • predict_future(steps_ahead: int = 10) -> tuple - Based on velocity and first-order/second-order inertial acceleration trends, predicts the target's screen pixel position several frames ahead.

⌨️ 3. Input Predictor Class (InputPredictor)

  • __init__(n_gram: int = 3) - Defines the minimum record length for prediction.
  • record_action(action) - Inputs the player's pressed command.
  • predict_next() -> Any - Based on the player's continuous input patterns, intelligently predicts which key is most likely to be pressed next, returning the key object.

Debug window

  • qgame.debugger.init(width=360, height=600, title="Debugger", font_size=11) Builds and renders the floating debugger window.
    • width / height: Geometry constraints of the workspace.
    • title: Branding string printed centered on the top bar.
    • font_size: Nominal size of Console font. Heights and text boundaries automatically align accordingly.
  • qgame.debugger.watch(name: str, value_func) Establishes or updates a monitored item record.
    • name: Text label drawn on the left column in baby blue.
    • value_func: Given as a lambda expression (like lambda: obj.health) or a plain value. Pass callables as much as possible for dynamic values.
  • qgame.debugger.unwatch(name: str) Instructs the panel to stop querying and printing the specified item.
  • Scroll Navigation Hover your mouse pointer on top of the debug pane and use your mouse wheel to navigate down if there are more parameters registered than the screen height can fit.

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", icon_path: str = None, scaling_mode: Literal["letterbox", "crop", "stretch", "adaptive"] = "letterbox") -> QImage 设定游戏的分辨率和主窗口标题。返回渲染使用的主画布(QImage 实例)。
  • show_splash(image_path: str = None, duration: float = 2.0, *, echo_error: bool = True) 展示游戏启动闪屏,附带淡入与淡出的平滑半透明过度。如果未传参数,则使用QGame的logo。如果路径不存在且echo_error为True,报FileNotFoundError,反之打印错误

window (窗口实例)

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

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 (进度条类)

  • load_tasks(tasks: list, on_progress: Callable = None, on_complete: Callable = None) 顺次执行传入的耗时步骤函数列表,在任务间隙强制刷新事件泵防白屏假死。
    • tasks: 无参函数列表。
    • on_progress: 阶段更新回调,返回 (当前序号, 总任务数, 该任务返回值)
    • on_complete: 整体工作就绪后的无参结束回调。

TextBox (文本框类)

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

VideoPlayer (原生视频视口播放器)

  • __init__(x: int, y: int, width: int, height: int, loop: bool = False) 在视区上按绝对宽高坐标创建独立的视频渲染图层。
  • load(file_path: str) 绑定本地音视频流媒体文件。
  • play() / pause() / stop() 视频基本播放动作控制。
  • set_volume(volume: float) 设置声道音量比例(0.0 为完全静音,1.0 为满响音度)。
  • set_loop(loop: bool) 是否死循环回放当前轨道。
  • connect_finished(callback: Callable) 绑定视频播放到结尾自然脱落时的无参回调处理槽(用于剧情播完自动淡入关卡)。
  • 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.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 配置文件字典。

🌐 网络骨架接口参考 (qgame.network)

网络通讯基于 QtNetwork 非阻塞机制。请直接覆写逻辑或绑定 connect 数据槽。

📡 1. UDP 分包网络组件

UDPNetworkServer (UDP 服务端监听器)

  • __init__(port: int) - 设定网络侦听本机的目标端口。
  • start() -> bool - 启动监听,返回绑定是否成功。
  • send_to(data: bytes, host: str, port: int) - 给特定的网络地址广播该字节报文。
  • connect_receive(callback: Callable) - 连接接收信号槽,回调结构:callback(data: bytes, ip: str, port: int)
  • close() - 注销套接字。

UDPNetworkClient (UDP 客户端)

  • start(local_port: int = 0) -> bool - 本地开启套接字防线。
  • send(data: bytes, host: str, port: int) - 发送网络数据包。
  • connect_receive(callback: Callable) - 接通回包信号。

🕸️ 2. WebSocket 大厅组件

已经放在qgame/examples/Web/UPD

WSNetworkServer (WebSocket 服务端)

  • __init__(port: int, server_name: str = "QGame") - 声明服务端。
  • start() -> bool - 开启 WebSocket 侦听。
  • broadcast(message: str) - 给旗下所有连入的玩家广播消息。
  • send_to(client_socket, message: str) - 给特定网络通道发送文本。
  • connect_client(callback) / connect_disconnect(callback) - 玩家接入与断开的回调监听槽。
  • connect_message(callback) - 解析某个客户端消息回调:callback(client_socket, message: str)

WSNetworkClient (WebSocket 客户端)

  • connect_to(url: str) - 连接目标节点,如 ws://127.0.0.1:80
  • send(message: str) - 发送文本指令包。
  • connect_open(callback) / connect_close(callback) - 连接成功及断线的回调。
  • connect_message(callback) - 监听服务器发来的报文接收:callback(message: str)

🤖 3. 游戏人工智能参考 (qgame.ai)

🧭 1. A* 智能寻路组件 (PathFinder)

  • find_path_on_screen(start_pos: tuple, end_pos: tuple, screen_w: int, screen_h: int, grid_size: int = 32) -> list (核心推荐) 输入起点屏幕坐标与终点像素坐标,算法将全自动拉取当前 collision.active_colliders 中存放的活动物理碰撞箱作为格栅阻碍进行 8 方向 A* 寻径,最终返回平滑的屏幕像素目标点折线数组。

🔮 2. 行为预判器类 (TrajectoryPredictor)

  • __init__(history_len: int = 15) - 初始化预判队列深度。
  • update(pos: tuple) - 输入跟随角色的当前位置坐标 (x, y)。
  • predict_future(steps_ahead: int = 10) -> tuple - 根据速度和一阶/二阶惯性变化加速度趋势,预判目标在几帧后的屏幕像素点位置。

⌨️ 3. 输入预判器类 (InputPredictor)

  • __init__(n_gram: int = 3) - 定义用于判定的最短记录长度。
  • record_action(action) - 输入玩家按压指令内容。
  • predict_next() -> Any - 根据玩家连续按下规律,智能断言下一时刻最有可能会去点击哪个按键,返回按键对象。

QGame: Welcome AI module to QGame Library😁 This will become a very good module, Bro🤔 Ha ha ha, bro, do you know? This is "Rainbow Egg"!😜 Don`t forget me, I`m 🍉

调试窗口

  • qgame.debugger.init(width=360, height=600, title="调试器", font_size=11) 打开并启动调试窗口。
    • width / height:调试窗口的高宽尺寸。
    • title:调试窗口顶部的装饰性文案。
    • font_size:面板中英文字型的字号大小(建议在 10 ~ 16 之间,行高会自动扩展适配)。
  • qgame.debugger.watch(name: str, value_func) 注册或更新一个被观察变量。
    • name:在左侧高亮显示的白蓝色键名。
    • value_func:**匿名 Lambda 表达式(例如 lambda: hero.hp)**或一个固定常量。Lambda 表达式能防止悬空指针错误,保证每次绘图抓取到的是堆内存中的最新值。
  • qgame.debugger.unwatch(name: str) 从调试视图中取消对该变量名的追踪展示。
  • 鼠标滚轮支持 当观测数据量比较大并超出窗口可视区域时,将鼠标悬停在调试窗口内进行滚轮滚动即可上下滑动翻页,按住不松即可顺滑查阅。

QGame: Oh! What that?

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.6.1.tar.gz (4.0 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.6.1-py3-none-any.whl (4.0 MB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for qgame-1.6.1.tar.gz
Algorithm Hash digest
SHA256 39a690d98ab3839d9188d75dd43bc67deee26e161ac2cd208cee79e0dbe94f01
MD5 b5670e06a0ae4abe50fe3712130c6e93
BLAKE2b-256 be018103f94ce8128ee8e6fc047e2326155a7f1926802e72e16fadfa5b7bf64a

See more details on using hashes here.

File details

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

File metadata

  • Download URL: qgame-1.6.1-py3-none-any.whl
  • Upload date:
  • Size: 4.0 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.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 01aeebff32fab8cc5f40152362c0d17337140f16651a534bdc86fd63421054b7
MD5 df81c62bfdeeaa543ef81a9693e46999
BLAKE2b-256 1e2ade48593eabd79d80bb36f9584dc1bc86cba1a0b31c9be88f9b5567eb14ee

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

This release

1.6.1 This release

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

1.3.0

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