@debuffjp/core

中文文档
0.33.0发布于 2026/11/11MITTypeScriptES Module构建来源已验证近 30 天下载 9680

Game loop, fixed-step clock, scenes, camera, sprites and typed creative parameters for debuff

原始使用文档
文档目录6 节
  1. API
  2. Finding what's near
  3. Smooth motion between steps
  4. Pixel fonts
  5. Scale modes
  6. Start-up splash

@debuffjp/core

Game loop, fixed-step clock, scenes, camera, sprites and typed creative parameters. Rendering is spryte, a batched WebGL2 renderer with automatic Canvas 2D fallback, re-exported here so Draw, BitmapFont and friends import from @debuffjp/core as before. One dependency (spryte), no others.

npm install @debuffjp/core
import { Game } from "@debuffjp/core";

const game = new Game({ canvas, width: 320, height: 180, scale: "integer", pixelArt: true });

const tuning = game.params.define("player", {
  speed: { type: "number", default: 140, min: 0, max: 600, units: "px/s" },
});

game
  .add({
    id: "play",
    update(dt) {
      /* simulation at a fixed step */
    },
    render(draw, alpha) {
      /* draw in logical units */
    },
    inspect: () => ({
      /* JSON snapshot for tools and tests */
    }),
  })
  .go("play");
game.start();

API

ExportPurpose
GameLoop, scenes, scaling, camera, random, params, stats, freeze(), timeScale, step(n), emit(name, detail?) (mark a game event, such as a coin or a death, for tests and agents)
game.use(plugin), PluginInstall runtime plugins. See docs/plugins.md
game.hooksbeforeUpdate, afterUpdate, beforeRender, afterRender, sceneChange, splashEnd (0.31.1). Each returns an unsubscribe function
game.inspectregister(name, () => json) for dev tools and scenarios
Scene{ id, enter?, update?, render?, exit?, inspect? }. game.go(id) runs the old scene's exit, then the new one's enter, then sceneChange. A go() called from inside those runs once the current switch is done (from 0.31.1; before, it ran at once, so sceneChange came out of order and a go() in exit could recurse)
CameraSmoothed follow, deadzone, bounds, trauma shake, culling, toWorld()
smoothMotion(game, objects)Draw moving objects between fixed steps without keeping prevX/prevY yourself; see Smooth motion. Added in 0.26
Sprite, sliceGridFrames, named animations, origin, flip, impact flash
draw.text, draw.measureText in debuff sans (the built-in pixel font), a BitmapFont or a CSS font; measure returns the box text fills
debuffSans()The built-in pixel font: printable ASCII, 5x7 capitals with descenders, proportional, white so color tints it
BitmapFontPixel font from a sprite-sheet grid. Widths are measured from the glyph pixels; crisp at any integer scale
ParamRegistry, ParamGroupTyped, ranged, unit-annotated values; describe() is JSON
RandomSeeded PRNG: next, range, int, pick
FixedClockFixed-step accumulator with render interpolation. budgetMs (added in 0.28) keeps a heavy simulation from collapsing the frame rate
StoragelocalStorage wrapper that never throws. From 0.28, set and reset return whether the write reached storage
FrameStatsAllocation-free frame interval / work timings
clamp, lerp, damp, approach, overlaps, circlesOverlapMath helpers
SpatialHashA grid for "what's near this" queries (near, nearest), rebuilt each step; see Finding what's near. Added in 0.26

Finding what's near

Checking every enemy against every shot is fine for a few dozen. For hundreds, put them in a SpatialHash once per step and ask only about the cells around a point. Added in 0.26:

import { SpatialHash } from "@debuffjp/core";

const grid = new SpatialHash<Enemy>(24); // cell size: about the radius you query most

// in update, after things moved:
grid.rebuild(enemies);
for (const shot of shots)
  grid.near(shot.x, shot.y, 12, (e) => {
    hit(e, shot);
    return true; // stop at the first
  });
const target = grid.nearest(player.x, player.y, 200, (e) => !e.dead);

near visits every item whose centre is within the radius, with the squared distance; nearest returns the closest one accept allows. Items are points, so for large ones query with the radius plus their size. Results come in a fixed order, so replays stay deterministic, and after the first steps it allocates nothing. Rebuilding while a query runs isn't allowed; a query inside another query's callback is fine. On a crowd-separation workload (every enemy querying 16 px around itself) it measured about 4 to 15 times faster than checking every pair, for 500 to 2,000 enemies.

Smooth motion between steps

The simulation runs at a fixed 60 Hz, and render(draw, alpha) gets how far the frame is between the last step and the next (0 to 1). Drawn at their positions, moving objects jump on displays faster than 60 Hz. The camera already blends by alpha; smoothMotion does it for your objects, added in 0.26:

import { smoothMotion } from "@debuffjp/core";

const smooth = smoothMotion(game, () => [player, enemies, shots]); // objects, or arrays of them

// in render:
draw.sprite(heroImg, smooth.x(player), smooth.y(player));
for (const e of enemies) draw.sprite(enemyImg, smooth.x(e), smooth.y(e));

// after moving something instantly (respawn, warp), so it doesn't streak for a step:
smooth.snap(player);

It saves each object's position before every step, so new objects need no registering and removed ones no clean-up. Something it hasn't saved yet (just created, or after snap) is drawn where it is. It only reads positions, so replays and tests are unaffected, and only x and y blend.

While the game is frozen (game.freeze()), nothing moves between steps, so from 0.26 render and the render hooks get alpha 1 and the camera draws where it is. Before 0.26 they got the leftover time, so the camera and anything blended by alpha wobbled on every frame of a hitstop.

Pixel fonts

draw.text uses debuff sans unless you pass a font, so text is crisp pixel art out of the box. Before 0.6 the default was the browser's 8px monospace; pass font: "8px monospace" to keep that look. Its source and a PNG sheet for other engines are in fonts/debuff-sans. To use your own:

Draw glyphs on a grid in Aseprite (or any editor), one cell per character in BitmapFont.ASCII order (space to ~, left to right), and save the sheet as assets/[email protected] with your cell size. Draw each glyph from its cell's left edge; the advance is measured from the rightmost opaque column.

const font = new BitmapFont({ frames: assets.frames("font"), chars: BitmapFont.ASCII });
draw.text("coins 3", 4, 4, { font, color: "#fbbf24" });

With the aseprite() CLI plugin you can keep the source as assets/[email protected] and skip exporting; @debuffjp/cli's aseprite/new-font.lua creates a blank sheet with the grid set up. See the CLI README.

Scale modes

  • fit (default): fill the container, keep the aspect ratio.
  • integer: whole device-pixel scales for crisp pixel art.
  • expand: like fit, but the logical size grows along the spare axis instead of letterboxing.
  • pixel: each logical unit is pixelSize CSS pixels (default 3, snapped to whole device pixels), and the logical size grows with the container, so a bigger window or monitor shows more of the game instead of bigger pixels. width/height are the minimum: a smaller container scales down by whole device pixels, and below one device pixel per unit by a fraction to fit, like fit. Before 0.29.3 it stopped at one device pixel per unit and the canvas overflowed the container.
  • none: logical size in CSS pixels.

With expand and pixel, game.width and game.height change on resize (game.hooks.resize), so lay out from them each frame.

Game code always uses logical units. The backing store follows devicePixelRatio.

Start-up splash

Production builds open with a short "made with debuff" card. It lasts 1.6 seconds and any key skips it. A click or tap skips it too (before 0.5, a click opened debuff.jp and the card showed its URL). It has no links or URLs, so games stay within portal rules (Poki, CrazyGames and others forbid links out of the game). Publishing on Poki? Poki requires games to have no splash screens at all, so turn it off with splash: false. It never shows in dev, or when time is driven by step() (scenarios and agents). To remove it:

new Game({ canvas, width, height, splash: false });

You can also set its length with splash: { duration: 1 }, or end it from code with game.skipSplash().

The key or tap that skips the splash doesn't also count as a press in the game: @debuffjp/input drops presses made during the splash when game.hooks.splashEnd fires, so the same tap can't skip a title screen too. Keys still held stay held. Before 0.31.1, that tap was seen as pressed in the first step.

版本与发布记录

@debuffjp/core 共发布 56 个版本,首次发布于 2026/10/16;过去 12 个月发布了 56 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.33.0latest2026/11/11今天
0.32.02026/11/074 天前
0.31.12026/11/065 天前
0.31.02026/11/065 天前
0.30.02026/11/056 天前
0.29.22026/11/056 天前

关于 @debuffjp/core 的常见问题

@debuffjp/core 是什么?

Game loop, fixed-step clock, scenes, camera, sprites and typed creative parameters for debuff

如何安装 @debuffjp/core?

在项目目录运行 npm install @debuffjp/core,或使用 pnpm add / yarn add / bun add。

@debuffjp/core 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@debuffjp/core 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@debuffjp/core 可以商用吗?

@debuffjp/core 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@debuffjp/core 的下载量有多少?

根据 npm 官方下载统计,@debuffjp/core 在 2026/10/12 – 2026/11/10 这 30 天内被下载 9,680 次,日均约 323 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@debuffjp/core 还在维护吗?

最新版本 0.33.0 发布于 2026/11/11(今天);至今共发布 56 个版本,其中过去 12 个月发布了 56 个;首次发布于 2026/10/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。