This library assists developers with graphics programming.
Every draw method, rendered by graphik itself (scripts/make_readme_images.py).
graphik is released as git tags, not on PyPI. Install a release from its tag's
archive (no git needed):
pip install "graphik @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.1.zip"In a requirements.txt, use the same line without the quotes. See
RELEASING.md for how releases are cut.
These games use graphik. When a release goes out, each one gets a pull request
that bumps the tag in its requirements.txt:
| Game | Repository |
|---|---|
| Roam | Preponderous-Software/roam |
| Ophidian | Preponderous-Software/ophidian |
| Apex | Preponderous-Software/apex |
| Rock Paper Scissors 2D | Stephenson-Software/Rock-Paper-Scissors-2D |
| Tic Tak Toe | Stephenson-Software/Tic-Tak-Toe |
import pygame
from preponderous.graphik import Graphik
pygame.init()
gameDisplay = pygame.display.set_mode((900, 600))
graphik = Graphik(gameDisplay)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
graphik.beginFrame() # optional: buttons fire once per click instead of while held
gameDisplay.fill(Graphik.black)
graphik.drawRectangle(100, 100, 200, 50, Graphik.blue)
graphik.drawText("Hello, world!", 200, 125, 24, Graphik.white)
graphik.drawButton(100, 200, 200, 50, Graphik.green, Graphik.black, 24, "Click me", lambda: print("clicked"))
graphik.drawImage("path/to/image.png", 100, 300, 200, 200) # replace with a real image file
pygame.display.update()
graphik.endFrame()
pygame.quit()Graphik only paints the surface: nothing appears in the window until pygame.display.update() (or pygame.display.flip()) is called, and no Graphik method calls either. drawButton reads the mouse state, which pygame refreshes only while events are being processed, so it belongs in a loop that handles them, as above.
Public Graphik methods:
-
Graphik(gameDisplay=None)— construct a helper bound to a pygame display surface (creates a default 900x600 window if none is given — replacing, not reusing, any display mode already set, so an existing window is resized to 900x600). -
getGameDisplay()— returns the bound display surface. -
getVersion()— returns the installed graphik version string. -
drawRectangle(xpos, ypos, width, height, color)—xpos/yposare the rectangle's top-left corner. -
drawText(text, xpos, ypos, size, color)—xpos/yposare the center of the rendered text, not its top-left corner. This differs fromdrawRectangle,drawButtonanddrawImage, which all position their top-left corner at the given coordinates. Glyph edges are antialiased, blending with whatever is already on the surface. The text is always rendered as a single line — a"\n"is not a line break, so multi-line text needs one call per line — and a null character ("\0") raisesValueErrorbefore anything is painted. -
beginFrame()— call once at the top of each frame to makedrawButtonfire once per click instead of while held. Calling it again in the same frame does nothing, so nested screens can each call it. A press that is already held when the firstbeginFrame()runs, or that slides onto a button while held, doesn't count, and each press fires at most one button. -
endFrame()— call once at the end of each frame started withbeginFrame(). A frame that misses it (an exception, an early return) doesn't leave clicks stuck: the nextbeginFrame()notices the mouse button changed and takes a new snapshot. -
drawButton(xpos, ypos, width, height, colorBox, colorText, sizeText, text, function)— draws a rectangle and centered text, and callsfunction()when the button is clicked. By default it fires on every call where the mouse is held inside the button with button 1 down (once per call, not once per click), as earlier versions did. After the firstbeginFrame()call on the instance, it fires once per click instead: only in the frame where button 1 goes down inside the button. While the mouse is over the box, the box is drawn in a lifted color (light colors darken by 25, dark ones lighten by 35, per channel, clamped; the label color is unchanged), so it reads as clickable. The clickable region is exactly the drawn box —xposthroughxpos + width - 1, andyposthroughypos + height - 1— so buttons laid out edge to edge share no clickable coordinate. The hit test usespygame.mouse.get_pos(), which is in window coordinates, so this only holds when theGraphikis bound to the display itself (or another surface whose top-left sits at the window's origin): bound to a subsurface or an off-screen surface blitted elsewhere, the box is painted at that surface's position but stays clickable atxpos/yposrelative to the window. The label is not clipped to the box: one too large for it overflows past the box edges, and that overflow is painted but not clickable. Reading the mouse needs the video system, so unlikedrawRectangleanddrawTextit raisespygame.error(after painting) when neitherpygame.init()norpygame.display.init()has been called, even for an off-screen surface; no display mode is needed.The hover lift, rendered by
scripts/make_readme_images.py. -
drawImage(filePath, xpos, ypos, width, height)— caches the loaded and scaled surface byfilePath, so an image edited on disk mid-run will not be picked up until the process restarts.filePathmay be astror apathlib.Path, and is used as the key exactly as given: two spellings of one file (relative and absolute, or astrand aPath) are cached, and loaded, separately. Only the most recently requested size is kept per path, so drawing the same file at two alternating sizes rescales it on every call. Unlike the other draw methods, it raisespygame.errorunless a display mode has been set withpygame.display.set_mode, even when theGraphikis bound to an off-screen surface. Only the first load of a path needs one: a path already in the cache keeps drawing to an off-screen surface with no display mode set.
Positions passed to the draw methods need not lie on the surface: anything drawn across its edge (including at negative coordinates) is clipped to it, with the part that falls off simply not painted — nothing raises, and nothing is shifted to fit.
A zero width or height draws no shape and raises nothing, and a drawButton sized that way has no clickable region (its label, if non-empty, is still painted, centered on xpos + width // 2, ypos + height // 2). A negative size is not mirrored into a normal rectangle: drawRectangle and drawButton likewise draw no shape (with no clickable region), but drawImage raises ValueError.
Fractional positions and sizes are accepted: drawRectangle, drawButton and drawImage truncate each of xpos, ypos, width and height toward zero on its own, so a box at 10.7 with a width of 5.9 covers pixels 10 through 14, and a size below one pixel draws nothing. drawText accepts a fractional center, but its size, like drawButton's sizeText, must be an int (a float raises TypeError, unless it is a whole number whose font is already cached, in which case the cached font is used). drawButton's hit test compares the mouse against the unrounded values, so with fractional arguments its clickable region can be up to a pixel off from the drawn box on each edge; pass integers where the two must line up exactly.
pygame.quit() destroys the display surface and any subsurface of it, so a Graphik bound to either must not draw again until a live surface is assigned to its gameDisplay attribute (or a new Graphik is built). The failure depends on the pygame version and need not be an exception: on pygame 2.1.2 drawRectangle segfaults the process. A Graphik bound to an ordinary off-screen surface keeps working across a restart.
Color constants: Graphik.black, Graphik.white, Graphik.red, Graphik.green, Graphik.blue.
An alpha component in a fill color ((r, g, b, a)) does not make drawRectangle or drawButton's box translucent: on the display the shape is painted opaquely whatever a is, and on a surface with per-pixel alpha (pygame.SRCALPHA) the color's alpha replaces the pixels' own rather than blending over them. drawText's color and drawButton's colorText ignore an alpha component altogether: the text is painted as if a were 255, on the display and on a per-pixel alpha surface alike (only the antialiased glyph edges blend with what is underneath).
preponderous.graphik.grid3d draws a grid game's board in 3D with
Strata: tiles, a frame, and
pieces standing on cells that slide smoothly between cells from one game tick
to the next. A game describes its board once and reports what is on each cell
every tick; the look lives in a Theme. It needs the optional Strata binding
and runs on Linux and Windows desktops, and in the browser under pygbag
(see In the browser):
pip install "graphik[strata] @ https://github.com/Stephenson-Software/graphik/archive/refs/tags/v0.5.1.zip"from preponderous.graphik.grid3d import (
SPHERE, Grid3DView, GridBoard, Label, Piece, PieceStyle, Theme, Unavailable,
)
theme = Theme(pieces={"pawn": PieceStyle(SPHERE, (0.9, 0.25, 0.2))})
try:
view = Grid3DView.open(900, 700, "My game")
except Unavailable as reason:
print("No 3D here:", reason) # keep the 2D game
else:
view.setBoard(GridBoard(8, 8, theme))
view.setPieces([Piece("p1", 3, 4, "pawn")], tickSeconds=0.15) # once per tick
view.setLabels([Label("Score: 0", 18, 16, 24)]) # when it changes
view.frame() # once per framePiece(id, column, row, style): keepidstable so the piece slides;chain/linkjoin neighbouring pieces (a snake's body);interpolate=Falsemakes it jump;scale,colorandfacingvary one piece.PieceStyle(kind, color, height, size, lift, glow, tones, extras):glowadds a point light;extrasdraws decorations such as eyes.Grid3DView.open(..., headless=True)renders off-screen for tests and screenshots (savePng);reducedMotion=Truemakes pieces jump instead of slide.Unavailablesays in plain words why 3D can't run (no binding, no library for the system, no window); the game should fall back to its 2D view.- Everything except
Grid3DView.openis plain Python, so scene code can be unit-tested without a GPU. Importinggrid3dloads neither Strata nor pygame. PieceStyle.extras(piece, x, z, baseY)returns shapes placed relative to the piece: x and z measured from the given(x, z), so moving the piece moves them all the same way. The browser backend sends them as offsets from the piece and relies on this.
So that games stop hand-building the same pieces:
- Picking.
view.pickCell(x, y)(orpickCell(camera, board, x, y, width, height)) gives the(column, row)under a pointer, orNone; the whole cell counts, gaps between tiles included.projectToScreen(camera, point, width, height)andcellScreenPosition(camera, board, column, row, width, height, y)go the other way, for aiming a tap at a piece or putting a note beside a tile. They use the same look-at and perspective the view asks Strata for. - Text. Strata's built-in font is an 8 x 8 bitmap font in which every character is exactly
pixelSizewide.measureText(text, pixelSize),fitText(text, width, pixelSize)(cut with...),wrapText(text, maxWidth, pixelSize)(greedy word wrap) andcentredLabel(text, x, y, pixelSize, color, rise=0.5)build on that. - Screen buttons.
Button(x, y, width, height, text, color, textColor, pixelSize, function)draws a panel and a centred label (button.draw(pointer)), hit-tests withdrawButton's edges (contains,click), and lifts under the pointer asdrawButtondoes (hoverColor). Colours are 0-255, as fordrawButton;paddingwidens a button whose label doesn't fit. - 2D screens under a 3D view.
ScreenRecorderstands in forGraphik: a game's 2D screens draw into it as usual (drawText,drawRectangle,drawButton), the 3D view shows what they drew, andrecorder.click(pos)runs the 2D button's own function. - Bigger boards.
GridBoard(columns, rows, theme, tiles=..., mergeTiles=True, viewport=...):tilesmaps a cell to its ownTile(color, raised);mergeTilesdraws each row's neighbouring tiles that look the same as one box (a 64 x 64 board of one colour is 64 boxes, not 4096);viewport=Viewport.around(column, row, reach)draws only a window of the board, framed and fitted as if it were the whole board, with pieces and picking still in whole-board cells. - Hover.
board.scene(..., highlight=(column, row))lays a thin slab inTheme.highlighton the tile under the pointer. - Chains.
board.bridgePairs(pieces)names the joined pieces andboard.bridgeShape(a, b, aAt, bAt)draws one bridge.
Under pygbag (sys.platform == "emscripten"), Grid3DView.open() returns a grid3d.web.Grid3DWebView: the same calls, drawn by Strata's grid relay, a small Strata web-kit scene in the page (Strata's web/kit/grid-relay, whose WIRE.md specifies the messages). Python sends the board, each tick's pieces, the HUD and the camera as small versioned binary messages; the page slides the pieces between ticks itself, so nothing is sent per display frame. A game that builds whole Scenes can keep calling drawScene() every frame; only what changed is sent.
view.readyturns true once the page has loaded the 3D view;view.failure()says why it couldn't.open()raisesUnavailableon a page without the relay.view.pollEvents()returns Strata-style events (keys with desktop Strata's scancodes, mouse, wheel, resize, andFINGER_*for touch), andgrid3d.web.toPygameEvents(events, pygame)turns them into pygame events, so a game's 2D input code runs unchanged. It converts desktop Strata events too.- The page: build with
pygbag --template <grid3d.web.templatePath()> ..., a copy of pygbag 0.9.3's default template with the relay's canvas and a 2D/3D button. The relay has to be served with the game (a browser can't fetch GitHub release assets cross-origin):python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest <pygbag output>downloads Strata'sstrata-<version>-wasm32-emscripten.tar.gz, checks it against the release'sSHA256SUMSand copies its prebuiltkit/grid-relay/dist/next to the page, leaving files already there (pygbag'sindex.html) alone. - Since 0.5.1 the page starts in 3D, as a desktop
Grid3DViewgame does: the relay's scripts and engine load at once, alongside pygbag, and the 2D canvas stays on screen until the 3D view is drawing the game. If 3D can't start (no WebGL 2, a file missing, too big, the engine failed), the 2D view stays, the button reads 3D unavailable and a note under it says why in plain words. Which view a page starts in:?view=2dor?view=3din the address (for testing and sharing; not remembered), else the player's last choice on the button (kept inlocalStorage; a stored 2D wins over the default), else the game's default, whichtemplatePath(defaultView="2d")makes 2D. A page that starts in 2D downloads nothing of the 3D view (not even the relay's three small scripts) until the button is pressed.grid3d.web.wants3D()tells the game 3D is on and the relay's scripts are in, soGrid3DWebView.open()can begin, andset3D(False, reason)turns it off. - The button sits in the page's top right corner.
grid3d.web.buttonArea()gives its(x, y, width, height)in CSS pixels, the units of the web view's labels and panels, so a HUD can keep text out from under it (Noneoutside a browser). The page never scrolls (overflow: hidden), so a phone's browser can't widen it to fit pygbag's 50000-pixel measuring element and push the button off screen, and its one viewport tag setswidth=device-width(pygbag 0.9.3's default page has a second one that overrides it). Strata's own loading and failure overlay is hidden, so it never covers the 2D game.
In a game's browser.yml, where graphik is installed into src/ for pygbag:
- name: Build with pygbag, on graphik's 3D page template
run: |
TEMPLATE="$(PYTHONPATH=src python -c 'from preponderous.graphik.grid3d.web import templatePath; print(templatePath())')"
python -m pygbag --build --template "$TEMPLATE" --title "My game" src
- name: Add Strata's grid relay next to the page
run: PYTHONPATH=src python -m preponderous.graphik.grid3d.relay --strata 0.9.0 --dest src/build/web- pygame
- optional:
strata-engine0.8.0 for the 3D grid view on the desktop (thestrataextra)
Python 3.9 or newer is required (requires-python in pyproject.toml). The test suite is run against 3.9 through 3.13; see .github/workflows/test.yml for why 3.13 is the ceiling.
python -m venv .venv
source .venv/bin/activate
pip install -e ".[test]"
pytestThe suite is headless: src/test/python/conftest.py sets SDL_VIDEODRIVER/SDL_AUDIODRIVER to dummy before pygame touches a display, so no window is created and the tests run on a machine with no display attached. pytest alone works from the repo root because [tool.pytest.ini_options] in pyproject.toml points testpaths at src/test/python and pythonpath at src/main/python. .github/workflows/test.yml runs the same pip install -e ".[test]" + pytest sequence — preceded by a compile check and an import smoke test, across the supported Python versions — on every pull request and on every push to main. A second job, Install from a release archive, packs the commit the way GitHub serves a tag's archive, installs it into a fresh venv as a consumer would, and draws with it. A push to a branch with no open pull request is not covered, so run pytest locally before opening one.
The README images are generated, not hand-made. After changing how something draws, regenerate them with
SDL_VIDEODRIVER=dummy python scripts/make_readme_images.py and commit the updated docs/images/*.png.
The games that use graphik are listed under Dependents above.
graphik is licensed under the MIT License.
Copyright © 2022–2025 Daniel McCoy Stephenson. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The MIT License offers maximum freedom for developers to integrate graphik into their projects, whether for games, simulation tools, or research applications. This permissive approach is intended to boost adoption, encourage experimentation, and position graphik as a widely used rendering and visualization library.
There are no plans to move away from open source for graphik. The project will remain freely available under an OSI-approved license, with active encouragement for community use and contributions.

