npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

samengine

v1.11.0

Published

A TypeScript game library to make HTML Games

Readme

Samengine 🎮

Build Packages Test Tauri Release (Webtools Desktop) Release Samtool

A lightweight, TypeScript-first web game engine framework for building 2D games and maybe 3D Games in the Future.

Index

Features

  • 🎯 Simple game loop management
  • 🎨 Rendering system with text and sprite support
  • ⌨️ Input handling (keyboard & mouse)
  • 📦 TypeScript support out of the box
  • 🛠️ Build tools included
  • 📝 Logging utilities
  • 💾 Save/Load system

Info

For better Infos read the Docs

Quick Start

# Make sure both of them have the same Version

npm init
npm install samengine
npm install samengine-build
npx samengine-build --new
npx samengine-build

Basic Game Loop

import { startEngine, setupInput, dlog, renderText
} from 'samengine';

const { canvas, ctx, applyScaling, virtualWidth, virtualHeight

} = createCanvas({ fullscreen: true, scaling: "fit",
virtualWidth: 1920, virtualHeight: 1080 });
setupInput(canvas, virtualWidth, virtualHeight);

function init() {
  dlog('🎮 Game initialized!');
}

function gameLoop(dt: number) {
  // Clear canvas
  ctx.fillStyle = 'black';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // Your game logic here
  renderText(ctx, `FPS: ${(1 / dt).toFixed(0)}`, 10, 20);
}

startEngine(init, gameLoop);

Development & Building

Using Bun (local development)

npx samengine-build                       # Start Dev Server
npx samengine-build --release             # Production build
npx samengine-build --new (newproject)    # Create a new project with a
                                          # simple Snake Clone as Template
npx samengine-build --new-empty (new)     # Create a new empty project

Config

// Project File for the Game

import { type buildconfig, new_buildconfig
} from "samengine-build";

export function defineConfig(): buildconfig {
    let config: buildconfig = new_buildconfig();
    return config;
}

Svelte Adapter

SamEngine can be used directly inside Svelte/SvelteKit projects via the samengine/svelte entry point, without depending on generated HTML or window.__GAMESETTINGS__.

<script lang="ts">
    import { onMount } from "svelte";
    import { SamEngine, getGameSetting, setGameSetting } from "samengine/svelte";

    let canvas: HTMLCanvasElement;
    let cards = "8";

    onMount(() => {
        const engine = new SamEngine({
            canvas,
            settings: { cards },
            update: (dt) => {
                const cardCount = Number(getGameSetting("cards", "8"));
                // ... draw the frame using engine.ctx ...
            },
        });

        engine.start();

        // Runs on unmount - stops the game loop and removes every
        // keyboard/mouse/wheel/resize listener the engine installed.
        return () => engine.destroy();
    });

    function changeCards(value: string) {
        cards = value;
        setGameSetting("cards", value);
    }
</script>

<select value={cards} onchange={(e) => changeCards(e.currentTarget.value)}>
    <option value="4">4</option>
    <option value="8">8</option>
    <option value="16">16</option>
    <option value="32">32</option>
</select>

<canvas bind:this={canvas}></canvas>

Notes:

  • Always construct SamEngine inside onMount() (or after mount). It throws if created during server-side rendering, so SvelteKit stays safe.
  • svelte is an optional peer dependency - projects that only use the HTML build do not need to install it.
  • Settings read through getGameSetting/getGameSettings work the same way in the HTML build and in Svelte; only Svelte needs SamEngine, the Settings Runtime itself is framework-agnostic Core API.
  • engine.destroy() is idempotent and safe to call from cleanup functions even if the component unmounts before start() was ever called.

Svelte Adapter: matching the generated HTML UI

samengine/svelte/ui ships drop-in Svelte components that reproduce the start screen, settings menu, and fullscreen button samengine-build generates - same layout, same colors, same behavior, driven by the exact same buildconfig you already pass to the CLI/HTML build. They read config directly (config.htmlMenu.style, config.htmlMenu.settings, config.title, ...) via the shared theme functions in samengine/config, so there is a single source of truth for the look of both hosts - the HTML build and these Svelte components literally call the same CSS-generating functions, they never drift apart on their own.

Easiest path - one component that wires up all three plus the audio-unlock flow, matching the generated page exactly:

<script lang="ts">
    import { onMount } from "svelte";
    import { SamEngine } from "samengine/svelte";
    import { SamEngineGameUI } from "samengine/svelte/ui";
    import { config } from "./samengine.config.js"; // same config as samengine-build

    let canvas: HTMLCanvasElement;
    let engine: SamEngine;

    onMount(() => {
        engine = new SamEngine({
            canvas,
            update: (dt) => {
                // ... draw the frame using engine.ctx ...
            },
        });

        return () => engine.destroy();
    });
</script>

<canvas bind:this={canvas}></canvas>

{#if canvas}
    <SamEngineGameUI {config} {canvas} onstart={() => engine.start()} />
{/if}

Or use the pieces individually if you want more control over layout:

<script lang="ts">
    import { SamEngineStartScreen, SamEngineSettingsMenu, SamEngineFullscreenButton } from "samengine/svelte/ui";
</script>

<SamEngineStartScreen {config} onstart={() => engine.start()} />
<SamEngineSettingsMenu {config} />
<SamEngineFullscreenButton {config} {canvas} />

Notes:

  • SamEngineSettingsMenu writes through the Settings Runtime (setGameSetting) instead of window.__GAMESETTINGS__, and seeds each setting's default_value on mount unless you already set one yourself (e.g. via new SamEngine({ settings })).
  • The start screen renders as a position: fixed overlay covering the viewport (a .samengine-stage wrapper) instead of styling <body> directly the way the generated HTML page does - a component dropped into an existing SvelteKit app shouldn't reach out and restyle the whole app's <body>. Everything else (colors, spacing, the settings popup, the fullscreen button) is generated by the identical functions the HTML build uses, unchanged.
  • These components are entirely optional. If you'd rather build your own UI in Svelte from scratch, see the section above - SamEngine alone doesn't require any of this.

API Reference

Core Engine

  • startEngine(init, gameLoop) - Initialize game loop
  • stopEngine() - Stop the currently running game loop
  • isEngineRunning() - Whether a game loop is currently running

Settings Runtime

  • setGameSettings(settings) / getGameSettings() - Replace/read all settings
  • setGameSetting(id, value) / getGameSetting(id, fallback?) - Read/write a single setting
  • onGameSettingsChange(listener) - Subscribe to settings changes
  • Replaces direct reads of window.__GAMESETTINGS__ in game code; the HTML adapter's bridgeLegacyGameSettings() keeps the legacy global in sync for existing single-file builds

Svelte Adapter (samengine/svelte)

  • new SamEngine({ canvas, update, setup?, settings?, ... }) - Binds an existing canvas and wires up input
  • engine.start() / engine.stop() / engine.destroy() - Lifecycle, matching onMount/cleanup
  • engine.requestFullscreen() - Toggle fullscreen for the bound canvas
  • engine.input - getMouse, isKeyPressed, isKeyJustPressed, isKeyJustReleased
  • Re-exports the Settings Runtime and Key enum for convenience

Svelte UI Components (samengine/svelte/ui)

  • SamEngineGameUI - Start screen + settings menu + fullscreen button + audio unlock, combined
  • SamEngineStartScreen - Title/version/author/description/start button/Markdown notes
  • SamEngineSettingsMenu - Settings popup, wired to the Settings Runtime
  • SamEngineFullscreenButton - Fullscreen toggle button
  • All read the same buildconfig as samengine-build, styled via the shared functions in samengine/config (getStageCSS, getSettingsButtonCSS, getFullscreenButtonCSS, getMDNotesCSS)

Core Engine

  • startEngine(init, gameLoop) - Initialize game loop
  • stopEngine() - Stop the currently running game loop
  • isEngineRunning() - Whether a game loop is currently running

Settings Runtime

  • setGameSettings(settings) / getGameSettings() - Replace/read all settings
  • setGameSetting(id, value) / getGameSetting(id, fallback?) - Read/write a single setting
  • onGameSettingsChange(listener) - Subscribe to settings changes
  • Replaces direct reads of window.__GAMESETTINGS__ in game code; the HTML adapter's bridgeLegacyGameSettings() keeps the legacy global in sync for existing single-file builds

Svelte Adapter (samengine/svelte)

  • new SamEngine({ canvas, update, setup?, settings?, ... }) - Binds an existing canvas and wires up input
  • engine.start() / engine.stop() / engine.destroy() - Lifecycle, matching onMount/cleanup
  • engine.requestFullscreen() - Toggle fullscreen for the bound canvas
  • engine.input - getMouse, isKeyPressed, isKeyJustPressed, isKeyJustReleased
  • Re-exports the Settings Runtime and Key enum for convenience

Rendering

  • renderText(ctx, text, x, y, color?, font?) - Render text
  • renderBitmapText() - Render bitmap font text

Input System

  • setupInput(canvas, width?, height?) - Initialize input
  • getKeyState(key) - Check key state
  • Mouse state available via input module

Types

  • Vector2D / Vector3D - Vector mathematics
  • Color - Color management
  • Rect - Rectangle collision
  • Math utilities for game logic

Utilities

  • startEngine() - Manage game loop

License

MIT

More Addons in the Game Library

  • a Full Markdown Parser (maybe for notes or easy docs, feel free to use)
  • a JSON with Comments Parser

(I dont now why i added this)

More Tools for samengine and Game Making by me lol

Commit Tags

The tags which are ending with -build are for the samengine-build Tool and the which end with -cli are for the samengine-cli package.

Samengine CLI Tools

Build, export, and development-server tooling for games built with samengine.

The package provides the samengine-build CLI. It bundles the code from the game folder, generates a playable index.html, copies or embeds assets from resources, and starts a local development server with automatic rebuilds in development mode.

What This Package Does

  • Creates new game projects with --new or --new-empty.
  • Loads samengine.config.ts and uses it as the source of truth for build options.
  • Bundles the game entry from game/<entryname> with esbuild.
  • Generates the HTML start page with title, description, author, version, optional fullscreen button, optional settings menu, and Markdown notes.
  • Copies resources from resources to dist/resources in normal multi-file builds.
  • Can embed used resources directly into the generated HTML as Data URIs in single-file mode.
  • Minifies release builds.
  • Starts a local HTTP server in development mode and rebuilds when files in game, resources, or samengine.config.ts change.

Installation

npm install samengine

Add these scripts to the package.json of your game project:

{
  "scripts": {
    "dev": "samengine",
    "build": "samengine --release"
  }
}

You can also run the CLI directly with npx samengine.

Project Structure

game/
  main.ts              Game entry point
resources/
  ...                  Images, audio, JSON, and other assets
samengine.config.ts    Build configuration
dist/
  index.html           Generated build output
  main.js              Bundled game, except in single-file mode

CLI

samengine

Runs a development build, writes dist/index.html, starts the development server, and watches project files.

samengine --release

Runs a release build. The output directory is recreated, JavaScript and HTML are minified, and no development server is started.

samengine --new MyGame

Creates a new project with an example game.

samengine --new-empty MyGame

Creates a new project with an empty starter game.

Configuration

A typical samengine.config.ts looks like this:

import type { buildconfig } from "samengine/config";
import { new_buildconfig } from "samengine/config";

export default function defineConfig(): buildconfig {
  const config = new_buildconfig();
  config.title = "My Game";
  config.description = "Short game description";
  config.gameauthor = "Your Name";
  return config;
}

Important options:

  • title: Browser title and start-screen title.
  • description: Description shown on the start screen.
  • version: Game version shown on the start screen.
  • entryname: Entry file inside the game folder, defaults to main.
  • outdir: Build output folder, defaults to dist.
  • show_fullscreen_button: Adds a fullscreen button to the generated page.
  • enable_audio: Unlocks the browser AudioContext after the start click.
  • markdown_notes: Shows collapsible Markdown notes before the game starts.
  • htmlMenu: Configures an optional settings menu.
  • devMode.singlefile: Generates a single HTML file in development mode.
  • releaseMode.singlefile: Generates a single HTML file in release mode.
  • dev_server_port: Initial port for the local development server.

Single-File Builds

When devMode.singlefile or releaseMode.singlefile is enabled, the tool reads the bundled JavaScript and scans the resources folder. Assets whose filename or relative path appears in the bundle are written into the HTML file as Base64 Data URIs. In the browser, they are available through window.__getResource(path) and window.__loadResource(path).

Code Exports

The main package entry exports build types and factory functions:

import {
  new_buildconfig,
  newHTMLMenu,
  newMarkdownStyle,
  type buildconfig,
} from "samengine/config";

Additional utilities are available from samengine/nonbrowser:

import { compressHTML } from "samengine/nonbrowser";

Learn more about samengine on GitHub or NPM.

Project Templates

Project Templates can be found here

Webtools

  • releases are made on tags which are starting with webtools-v*

IGN

Git ignore Adder Infos are here