pdgo

package module
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 18, 2026 License: MIT Imports: 2 Imported by: 0

README

Gopher on Playdate

Menu


Quick Install

curl -fsSL https://raw.githubusercontent.com/playdate-go/pdgo/main/install.sh | bash
# test 
chmod +x examples/build_all.sh 
chmod +x examples/*/build.sh
./examples/build_all.sh

This installs everything you need:

  • pdgoc - the build tool
  • Custom TinyGo with Playdate support (for device builds)
  • Configures your PATH automatically

Build Times

Platform With System LLVM Without (build from source)
Linux ~1 minute ~25-30 minutes
macOS N/A (must build) ~25-30 minutes

[!IMPORTANT] macOS users: Homebrew LLVM does not include static LLD libraries required to build TinyGo. The install script will automatically compile LLVM from source (~25-30 minutes, only needed once).

Pre-install LLVM (Linux only - speeds up build)

Ubuntu/Debian
wget https://apt.llvm.org/llvm.sh
chmod +x llvm.sh
sudo ./llvm.sh 20
sudo apt install clang-20 llvm-20-dev lld-20 libclang-20-dev
Fedora
sudo dnf install llvm20-devel clang20-devel lld20-devel
Arch Linux
sudo pacman -S llvm clang lld

ARM Toolchain

  • macOS: Included with Playdate SDK - no separate installation needed
  • Linux: Install via package manager: sudo apt install gcc-arm-none-eabi

Options

# Skip TinyGo build (simulator-only, instant install)
SKIP_TINYGO=1 curl -fsSL https://raw.githubusercontent.com/playdate-go/pdgo/main/install.sh | bash

# Custom parallel jobs
JOBS=8 curl -fsSL https://raw.githubusercontent.com/playdate-go/pdgo/main/install.sh | bash

What the installer does

  1. Installs pdgoc - go install github.com/playdate-go/pdgo/cmd/pdgoc@latest
  2. Clones TinyGo - downloads TinyGo v0.40.1 to ~/tinygo-playdate
  3. Sets up LLVM - uses system LLVM (Linux) or builds from source (macOS)
  4. Adds Playdate support - injects custom files into TinyGo:
    • playdate.json - target config (Cortex-M7, custom GC, no scheduler)
    • playdate.ld - linker script (memory layout, entry point)
    • runtime_playdate.go - platform runtime (time, console output via SDK)
    • gc_playdate.go - custom GC that delegates to Playdate SDK's realloc
  5. Builds TinyGo - compiles with Playdate support
  6. Configures PATH - adds pdgoc and tinygo to your shell

Result: ~/tinygo-playdate/build/tinygo - a TinyGo compiler that accepts -target=playdate

[!WARNING] Windows is not currently supported. Linux and macOS only.


Overview

[!NOTE]
This project is currently under active development, all API covered but not all features have been fully tested or implemented yet, PRs are always welcome.
Tested on macOS, tinygo 0.40.1 darwin/arm64, go1.25.6, LLVM 20.1.1, Playdate OS 3.0.2.

[!NOTE]
Playdate SDK >= 3.0.2 is required
Golang >= 1.21 is requred

Hi, my name is Roman Bielyi, and I'm developing this project in my spare time as a personal initiative. This project is an independent effort and is neither endorsed by nor affiliated with Panic Inc.

As a Go developer, I immediately wanted to bring Go to the Playdate. It wasn’t straightforward, but I got it working -- hope you’ll enjoy experimenting with it.

[!IMPORTANT]
The main objective now is to release a stable 1.0.x version. To achieve this, we need to rewrite all official Playdate SDK examples from C/Lua into Go and ensure that the Go API bindings are mature, stable, and provide complete coverage of all subsystems.

Usage

pdgoc is a command-line tool that handles everything for building Go apps for Playdate, both Simulator and Device builds.

[!IMPORTANT]
Always use pdgoc for building. Do not try to run go build or tinygo build directly because pdgoc handles all the complexity: SDK paths, CGO flags, temporary files, etc.

[!TIP]
The sim and device flags can be combined to build for both Simulator and Device simultaneously.

Flag Description
sim Builds project for the Playdate Simulator only
device Builds project for the Playdate console only
run Builds and runs project in the Playdate Simulator
deploy Deploys and runs on connected Playdate device (requires -device)
Flag Description
name Sets the name property for pdxinfo
author Sets the author property for pdxinfo
desc Sets the description property for pdxinfo
bundle-id Sets the bundleID property for pdxinfo
version Sets the version property for pdxinfo
build-number Sets the buildNumber property for pdxinfo
image-path Sets the imagePath property for pdxinfo
launch-sound-path Sets the launchSoundPath property for pdxinfo
content-warn Sets the contentWarning property for pdxinfo
content-warn2 Sets the contentWarning2 property for pdxinfo

[!NOTE]
To use the pdgoc CLI tool, navigate to the project root directory -- the one containing the Source folder with your .go source files, go.mod, go.sum, and any assets.
Simply execute pdgoc from there. It will detect the 'Source' directory automatically.

Example:
If your structure looks like this:

your-project/
├── Source/
│   ├── main.go
│   ├── go.mod
│   ├── go.sum
│   └── assets/ (images, sounds, etc.)
└──

Then cd your-project/ and run pdgoc.

Example:

pdgoc -device -sim \
  -name=MyApp \
  -author=YourName \
  -desc="My App" \
  -bundle-id=com.yourname.myapp \
  -version=1.0 \
  -build-number=1

The main.go:

package main

import (
	"github.com/playdate-go/pdgo"
)

// A global pointer to the Playdate API. 
//Initialized automatically when the game starts. 
//All SDK calls go through this variable: pd.Graphics.DrawText(...), pd.System.DrawFPS(...), etc.
var pd *pdgo.PlaydateAPI


// Called once when the game launches (during kEventInit).
// Use this to load images, sounds, fonts, and initialize your game state. The Playdate API (pd) is fully available here.
func initGame() {
	
}

// The main game loop. Called every frame (~30 FPS by default). Here you:
// Handle input (pd.System.GetButtonState())
// Update game logic
// Draw graphics (pd.Graphics.DrawText(), pd.Graphics.DrawBitmap())
// Return value: 1 to tell Playdate the display was updated and needs refresh. Return 0 if nothing changed (saves battery).
func update() int {
	
}

// Must exist but remains empty. 
//Playdate doesn't use Go's normal main() entry point, instead, the SDK calls eventHandler which is generated by pdgoc
func main() {}

Internals

Device:

For Playdate hardware pdgoc uses a custom TinyGo build with full Playdate hardware support instead of standard Go build tools.

Custom GC:
Custom TinyGo build for Playdate achieves minimal binary sizes through custom Playdate GC: Instead of including traditional garbage collection logic (mark, sweep, write barriers), we delegate all allocations to the Playdate SDK's realloc function. This results in minimal GC wrapper code in the final binary. The Playdate OS already provides a robust allocator optimized for the hardware, and we simply use it!

click to see: gc_playdate.go
//go:noinline
func alloc(size uintptr, layout unsafe.Pointer) unsafe.Pointer {
    size = align(size)
    gcTotalAlloc += uint64(size)
    gcMallocs++

    ptr := _cgo_pd_realloc(nil, size)
    if ptr == nil {
        runtimePanic("out of memory")
    }

    // Zero the allocated memory
    memzero(ptr, size)
    return ptr
}

func GC() {
    // No-op - Playdate SDK manages memory
}

func SetFinalizer(obj interface{}, finalizer interface{}) {
    // No-op
}

No Static Heap:
Standard TinyGo embedded targets reserve heap space in BSS section. Our runtime configuration eliminates this by setting needsStaticHeap = false. As a result, BSS is reduced from approx. 1MB to approx. 300 bytes.

click to see: gc_playdate.go
const needsStaticHeap = false

func initHeap() {
    // No initialization needed - Playdate SDK handles it
}

Minimal Runtime Configuration:
No scheduler, no threading, no dynamic stack management. A fixed stack size of ~60KB is used instead of Go's traditional growable stacks.

click to see: playdate.json
{
    "inherits": ["cortex-m"],
    "llvm-target": "thumbv7em-unknown-unknown-eabihf",
    "cpu": "cortex-m7",
    "features": "+armv7e-m,+dsp,+hwdiv,+thumb-mode,+fp-armv8d16sp,+vfp4d16sp",
    "build-tags": ["playdate", "tinygo", "gc.playdate"],
    "gc": "playdate",
    "scheduler": "none",
    "serial": "none",
    "automatic-stack-size": false,
    "default-stack-size": 61800,
    "cflags": ["-DTARGET_PLAYDATE=1", "-mfloat-abi=hard", "-mfpu=fpv5-sp-d16"]
}

LLVM Optimization:

  • Target: thumbv7em-unknown-unknown-eabihf
  • CPU: cortex-m7 with FPU (-mfpu=fpv5-sp-d16, -mfloat-abi=hard)
  • Features: Thumb-2, DSP, hardware divide, VFP4
  • Dead Code Elimination: Unused functions stripped via linker script
  • Link-Time Optimization: Cross-module inlining via LLVM
click to see: playdate.json & playdate.ld

Target configuration:

{
    "llvm-target": "thumbv7em-unknown-unknown-eabihf",
    "cpu": "cortex-m7",
    "features": "+armv7e-m,+dsp,+hwdiv,+thumb-mode,+fp-armv8d16sp,+vfp4d16sp",
    "cflags": ["-DTARGET_PLAYDATE=1", "-mfloat-abi=hard", "-mfpu=fpv5-sp-d16"]
}

Linker script (dead code elimination):

ENTRY(eventHandlerShim)

SECTIONS
{
    .text : ALIGN(4) {
        KEEP(*(.text.eventHandlerShim))
        KEEP(*(.text.eventHandler))
        KEEP(*(.text.updateCallback))
        KEEP(*(.text.runtime_init))
        *(.text) *(.text.*) *(.rodata) *(.rodata.*)
        KEEP(*(.init)) KEEP(*(.fini))
        . = ALIGN(4);
    }
    ...
    /DISCARD/ : { *(.ARM.exidx*) *(.ARM.extab*) }
}

/DISCARD/ removes unused ARM exception sections, KEEP() preserves only critical entry points.

Simulator:

pdgoc uses Go's native build tools to compile apps for the Playdate Simulator.

Under the hood, it automatically runs:

go build -ldflags="-w -s" -gcflags="all=-l" \
  -trimpath -buildvcs=false -race=false \
  -buildmode=c-shared \
  -o "some/output" "some/input"

All flags are optimized: stripping debug info (-w -s), disabling race detector, and producing a C-shared library with -buildmode=c-shared needed for Simulator instead of binary executable. In Unix systems it's .so and in macOS it's .dylib

Flag Purpose
-ldflags="-w -s" -w: Strip debug info (DWARF). -s: Strip symbol table. Shrinks binary ~30-50%
-gcflags="all=-l" Disable function inlining & optimizations for simulator compatibility
-trimpath Remove local filesystem paths from binaries (security/portability)
-buildvcs=false Skip embedding VCS data (git info) - faster builds
-race=false Explicitly disable race detector (already off by default)
-buildmode=c-shared Key: Build as C-shared library (.dylib/.so) for Playdate Simulator

Why Not Go But TinyGo

No Bare-Metal ARM Support:
Standard Go compiler (gc) only supports these targets:

Flag Purpose
linux amd64, arm64, arm, 386, ...
darwin amd64, arm64
windows amd64, arm64, 386

Playdate requires: thumbv7em-none-eabihf (ARM Cortex-M7, no OS), and this is simply impossible:
GOOS=none GOARCH=thumbv7em go build # not supported

Size:
Standard Go runtime includes Garbage Collector, Goroutine Scheduler, Stack Management and Reflection, binary size approx. 2-5 MB minimum. Playdate constraints are 16 MB total RAM (shared with game data, graphics, sound), games typically 50 KB - 2 MB.

Feature Standard Go TinyGo
Bare-metal support No Yes
GOOS= not required No Yes
ARM Cortex-M No Yes thumbv7em target
Minimal runtime No approx. 2MB Yes approx. 1-4 KB
Custom GC No Yes pluggable (gc.playdate)
No OS required No Yes
Relocatable code No Yes via LLVM
CGO on bare-metal No Yes (with custom runtime)

In short:

Go Source -> TinyGo Frontend -> LLVM IR -> LLVM Backend -> ARM Thumb-2 ELF
                                              |
                              Cortex-M7 optimizations
                              Position-independent code
                              Dead code elimination

Summary: Standard Go is designed for desktop/server environments, full operating systems, abundant memory (GB). Playdate requires: bare-metal ARM Cortex-M7, no operating system, tiny runtime, SDK-managed memory.

TinyGo bridges this gap by reimplementing Go compilation targeting embedded systems with LLVM backend. Our custom TinyGo build supports CGO on bare-metal Playdate hardware through a unified C wrapper layer (pd_cgo.c).

Flow:

Device Build

┌─────────────────────────────────────────────────────────────┐
│  pdgoc -device                                              │
├─────────────────────────────────────────────────────────────┤
│  1. Copy pd_cgo.c from pdgo module to build/pd_runtime.c    │
│  2. Create Source/main_tinygo.go                            │
│  3. Run go mod tidy                                         │
│  4. Create /tmp/device-build-*.sh                           │
│  5. Execute build script:                                   │
│     ├── Compile pd_runtime.c -> pd_runtime.o -> libpd.a     │
│     ├── Create build/playdate.ld                            │
│     ├── Create ~/tinygo-playdate/targets/playdate.json      │
│     ├── TinyGo build -> pdex.elf                            │
│     ├── pdc -> GameName.pdx/                                │
│     └── Delete build/ directory                             │
│  6. Delete Source/main_tinygo.go                            │
│  7. Delete Source/pdxinfo                                   │
└─────────────────────────────────────────────────────────────┘

Simulator Build

┌─────────────────────────────────────────────────────────────┐
│  pdgoc -sim                                                 │
├─────────────────────────────────────────────────────────────┤
│  1. Create Source/main_cgo.go                               │
│  2. go build -buildmode=c-shared -> pdex.dylib + pdex.h     │
│  3. Delete Source/pdex.h                                    │
│  4. Delete Source/main_cgo.go                               │
│  5. pdc -> GameName_sim.pdx/                                │
│  6. Delete Source/pdex.dylib                                │
│  7. Delete Source/pdxinfo                                   │
└─────────────────────────────────────────────────────────────┘

Temporary files created by pdgoc during build:

Device Build Files

pd_runtime.c - Copied from pd_cgo.c in the pdgo module. This C file provides all Playdate SDK wrappers that Go code calls via CGO. It includes TinyGo runtime support functions (_cgo_pd_realloc, _cgo_pd_logToConsole, _cgo_pd_getCurrentTimeMS) and the eventHandler entry point. Compiled with -DTARGET_PLAYDATE=1 to enable device-specific code.

main_tinygo.go - Contains the //export go_init and //export go_update directives that tell TinyGo to expose these functions as C-callable symbols. The C runtime calls these functions to initialize the game and run the update loop. This file is separate from the user's main.go to avoid polluting their code with build-specific exports.

playdate.ld - The linker script tells the ARM linker how to arrange code and data in memory. It defines the entry point (eventHandlerShim), ensures critical functions appear at the beginning of the binary, and sets up BSS/data sections.

playdate.json - TinyGo's target configuration file. It specifies the CPU architecture (Cortex-M7), compiler flags, which garbage collector to use (gc.playdate), and links to the linker script. This file tells TinyGo exactly how to compile for Playdate hardware.

libpd.a - A static library compiled from pd_runtime.c. TinyGo links against this library to resolve the C function references. Static linking ensures all SDK wrapper code is embedded directly in the final binary.

File Location Purpose Cleanup
pd_runtime.c build/ C wrappers (copy of pd_cgo.c) Deleted with build/ dir
main_tinygo.go Source/ TinyGo entry points (//export) Deleted after build
device-build-*.sh /tmp/ Embedded build script Deleted after build
playdate.ld build/ Linker script Deleted with build/ dir
playdate.json ~/tinygo-playdate/targets/ TinyGo target config Overwritten each build
pdex.elf build/ Compiled ELF binary Deleted with build/ dir
pd_runtime.o build/ Compiled C object Deleted with build/ dir
libpd.a build/ Static C library Deleted with build/ dir
pdxinfo Source/ Game metadata Deleted after build

Simulator Build Files

The simulator build uses the same pd_cgo.c from the pdgo module as the device build, but compiled for the host architecture. The C wrappers are linked directly into the shared library via standard Go CGO.

main_cgo.go - Contains import "C" and //export eventHandler directive that tells the standard Go compiler to generate a C-callable entry point. The simulator runs on your host machine (macOS/Linux), where CGO is fully supported.

pdex.h - Automatically generated by go build -buildmode=c-shared. This header file contains C function declarations for all exported Go functions. We immediately delete it since Playdate doesn't need it - the SDK already knows the expected function signatures.

pdex.dylib / pdex.so - The compiled shared library containing your Go game code and the C wrappers. The Playdate Simulator dynamically loads this library at runtime and calls eventHandler when your game starts. This file is moved into the .pdx bundle by pdc.

File Location Purpose Cleanup
main_cgo.go Source/ CGO entry points (//export) Deleted after build
pdex.h Source/ CGO header (auto-generated) Deleted after build
pdex.dylib / pdex.so Source/ Compiled shared library Deleted after build
pdxinfo Source/ Game metadata Deleted after build

API Bindings

The latest full documentation for API bindings is hosted here: https://pkg.go.dev/github.com/playdate-go/pdgo#section-documentation

Examples

[!NOTE] We will add more complex examples as the project progresses

To build all examples please do this:

# in project repo root
chmod +x examples/build_all.sh 
chmod +x examples/*/build.sh
./examples/build_all.sh

Each example includes a build.sh script that runs pdgoc with all necessary flags.

Particles -- examples/particles

Sprite Collisions -- examples/sprite_collisions

Tilemap -- examples/tilemap

JSON High and Low Level Encoding and Decoding -- examples/json | examples/json_lowlevel

Bach MIDI -- examples/bach_midi

3D Library -- examples/3d_library

Sprite Game -- examples/spritegame

Conway's Game of Life -- examples/life

Bouncing Square -- examples/bouncing_square

Go Logo -- examples/go_logo

Hello World -- examples/hello_world

Roadmap

  • Add more own complex code examples to cover and test all API subsystems
  • Rewrite to Go all official examples from SDK
    • Hello World
    • Life
    • Tilemap
    • Sprite Game
    • Sprite Collisions
    • Particles
    • Networking
    • JSON
    • Exposure
    • Bach.mid
    • Array
    • 3D Library
    • 2020
    • Accelerometer Test
    • Asteroids
    • ControllerTest
    • Drum Machine
    • Flippy Fish
    • Game Template
    • Hammer Down
    • Level 1-1
    • MIDI Player
    • Node7Driver
    • Networking
    • Pathfinder
    • Single File Examples
    • Sprite Collisions Masks
  • Make sure Lua interoperability works
  • Make sure C interoperability works
  • Write documentation for API bindings
  • Create unit tests for pdgoc and API bindings
  • Add support for Windows OS

Community

Using these links and places, you can discuss the PdGo project with each other:

Slack

  1. https://gophers.slack.com/archives/C029RQSEE/p1769119174451979
  2. https://gophers.slack.com/archives/CDJD3SUP6/p1769119574841489

Reddit:

  1. https://www.reddit.com/r/golang/comments/1qk1ec9/golang_support_for_playdate_handheld_compiler_sdk/
  2. https://www.reddit.com/r/PlaydateDeveloper/comments/1qk0r60/golang_support_for_playdate_handheld_compiler_sdk/
  3. https://www.reddit.com/r/programming/comments/1qk19kb/playdate_supports_go_language_compiler_sdk/
  4. https://www.reddit.com/r/PlaydateConsole/comments/1qk0wy0/golang_support_for_playdate_handheld_compiler_sdk/

Discord:

  1. https://discord.com/channels/118456055842734083/1464001888243548181
  2. https://discord.com/channels/675983554655551509/1464004567476867247

Playdate Development Forum (this is the main place to discuss): https://devforum.play.date/t/golang-support-for-playdate-compiler-sdk-bindings-tools-and-examples/24919

Attribution

The Go Gopher was designed by Renee French and is licensed under Creative Commons 4.0 Attribution License.

License

MIT License

Copyright (c) 2026 Roman Bielyi and PdGo contributors

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.

Documentation

Index

Constants

View Source
const (
	LCDColumns = 400
	LCDRows    = 240
	LCDRowSize = 52 // bytes per row (400 / 8 = 50, rounded up to 52)
)

Display constants

Variables

This section is empty.

Functions

func CallUpdateCallback added in v0.2.0

func CallUpdateCallback() int

CallUpdateCallback is called from C trampoline

func SetUpdateCallback added in v0.2.0

func SetUpdateCallback(callback func() int)

Types

type AudioSample

type AudioSample struct {
	// contains filtered or unexported fields
}

AudioSample represents an audio sample

type BitmapData

type BitmapData struct {
	Width    int
	Height   int
	RowBytes int
	Mask     []byte
	Data     []byte
}

BitmapData contains bitmap information

type ChannelAPI

type ChannelAPI struct{}

ChannelAPI wraps channel functions

func (*ChannelAPI) AddInstrumentAsSource added in v0.1.5

func (c *ChannelAPI) AddInstrumentAsSource(channel *SoundChannel, inst *PDSynthInstrument) bool

AddInstrumentAsSource adds an instrument as a source to a channel

type CollisionPoint

type CollisionPoint struct {
	X float32
	Y float32
}

CollisionPoint represents a point in collision detection

type CollisionVector

type CollisionVector struct {
	X int
	Y int
}

CollisionVector represents a vector in collision detection

type ControlSignal

type ControlSignal struct {
	// contains filtered or unexported fields
}

ControlSignal represents a control signal

type Display

type Display struct{}

Display provides access to display settings

func (*Display) GetHeight

func (d *Display) GetHeight() int

GetHeight returns display height

func (*Display) GetRefreshRate

func (d *Display) GetRefreshRate() float32

GetRefreshRate returns current refresh rate

func (*Display) GetWidth

func (d *Display) GetWidth() int

GetWidth returns display width

func (*Display) SetFlipped

func (d *Display) SetFlipped(x, y bool)

SetFlipped sets whether display is flipped

func (*Display) SetInverted

func (d *Display) SetInverted(inverted bool)

SetInverted sets whether display colors are inverted

func (*Display) SetMosaic

func (d *Display) SetMosaic(x, y uint)

SetMosaic sets mosaic effect

func (*Display) SetOffset

func (d *Display) SetOffset(x, y int)

SetOffset sets display offset

func (*Display) SetRefreshRate

func (d *Display) SetRefreshRate(rate float32)

SetRefreshRate sets the display refresh rate (20-50 fps)

func (*Display) SetScale

func (d *Display) SetScale(scale uint)

SetScale sets display scale (1, 2, 4, or 8)

type File

type File struct{}

File provides access to file system functions

func (*File) Close added in v0.2.0

func (f *File) Close(file *SDFile) error

Close closes a file

func (*File) Flush added in v0.2.0

func (f *File) Flush(file *SDFile) error

Flush flushes file buffers

func (*File) Mkdir

func (f *File) Mkdir(path string) error

Mkdir creates a directory

func (*File) Open

func (f *File) Open(path string, mode FileOptions) (*SDFile, error)

Open opens a file

func (*File) Read added in v0.2.0

func (f *File) Read(file *SDFile, buf []byte) (int, error)

Read reads from a file

func (*File) Rename

func (f *File) Rename(from, to string) error

Rename renames a file

func (*File) Seek added in v0.2.0

func (f *File) Seek(file *SDFile, pos int, whence int) error

Seek seeks to position in file

func (*File) Stat

func (f *File) Stat(path string) (*FileStat, error)

Stat returns file statistics

func (*File) Tell added in v0.2.0

func (f *File) Tell(file *SDFile) (int, error)

Tell returns current position in file

func (f *File) Unlink(path string, recursive bool) error

Unlink deletes a file

func (*File) Write added in v0.2.0

func (f *File) Write(file *SDFile, buf []byte) (int, error)

Write writes to a file

type FileOptions

type FileOptions int32

FileOptions for opening files

const (
	FileRead     FileOptions = 1 << 0
	FileReadData FileOptions = 1 << 1
	FileWrite    FileOptions = 1 << 2
	FileAppend   FileOptions = 1 << 3
)

type FilePlayer added in v0.2.0

type FilePlayer struct {
	// contains filtered or unexported fields
}

FilePlayer plays audio files

type FileStat

type FileStat struct {
	IsDir bool
	Size  uint32
	MTime uint32
}

FileStat contains file statistics

type Graphics

type Graphics struct{}

Graphics provides access to Playdate graphics functions

func (*Graphics) Clear

func (g *Graphics) Clear(color LCDColor)

Clear clears the display with the given color

func (*Graphics) ClearBitmap

func (g *Graphics) ClearBitmap(bitmap *LCDBitmap, bgcolor LCDColor)

ClearBitmap clears a bitmap

func (*Graphics) ClearClipRect

func (g *Graphics) ClearClipRect()

ClearClipRect clears the clipping rectangle

func (*Graphics) CopyBitmap

func (g *Graphics) CopyBitmap(bitmap *LCDBitmap) *LCDBitmap

CopyBitmap copies a bitmap

func (*Graphics) Display

func (g *Graphics) Display()

Display flushes the frame buffer to screen

func (*Graphics) DrawBitmap

func (g *Graphics) DrawBitmap(bitmap *LCDBitmap, x, y int, flip LCDBitmapFlip)

DrawBitmap draws a bitmap

func (*Graphics) DrawEllipse

func (g *Graphics) DrawEllipse(x, y, width, height, lineWidth int, startAngle, endAngle float32, color LCDColor)

DrawEllipse draws an ellipse outline

func (*Graphics) DrawLine

func (g *Graphics) DrawLine(x1, y1, x2, y2, width int, color LCDColor)

DrawLine draws a line

func (*Graphics) DrawRect

func (g *Graphics) DrawRect(x, y, width, height int, color LCDColor)

DrawRect draws a rectangle outline

func (*Graphics) DrawRotatedBitmap

func (g *Graphics) DrawRotatedBitmap(bitmap *LCDBitmap, x, y int, rotation, centerX, centerY, xscale, yscale float32)

DrawRotatedBitmap draws a rotated bitmap

func (*Graphics) DrawScaledBitmap

func (g *Graphics) DrawScaledBitmap(bitmap *LCDBitmap, x, y int, xscale, yscale float32)

DrawScaledBitmap draws a scaled bitmap

func (*Graphics) DrawText

func (g *Graphics) DrawText(text string, x, y int) int

DrawText draws text at the given position

func (*Graphics) FillEllipse

func (g *Graphics) FillEllipse(x, y, width, height int, startAngle, endAngle float32, color LCDColor)

FillEllipse fills an ellipse

func (*Graphics) FillRect

func (g *Graphics) FillRect(x, y, width, height int, color LCDColor)

FillRect fills a rectangle

func (*Graphics) FillTriangle

func (g *Graphics) FillTriangle(x1, y1, x2, y2, x3, y3 int, color LCDColor)

FillTriangle fills a triangle

func (*Graphics) FreeBitmap

func (g *Graphics) FreeBitmap(bitmap *LCDBitmap)

FreeBitmap frees a bitmap

func (*Graphics) FreeBitmapTable

func (g *Graphics) FreeBitmapTable(table *LCDBitmapTable)

FreeBitmapTable frees a bitmap table

func (*Graphics) GetBitmapData

func (g *Graphics) GetBitmapData(bitmap *LCDBitmap) *BitmapData

GetBitmapData returns bitmap data information

func (*Graphics) GetDisplayBufferBitmap

func (g *Graphics) GetDisplayBufferBitmap() *LCDBitmap

GetDisplayBufferBitmap returns the display buffer as a bitmap

func (*Graphics) GetDisplayFrame

func (g *Graphics) GetDisplayFrame() []byte

GetDisplayFrame returns the actual display buffer

func (*Graphics) GetFrame

func (g *Graphics) GetFrame() []byte

GetFrame returns the display framebuffer

func (*Graphics) GetTableBitmap

func (g *Graphics) GetTableBitmap(table *LCDBitmapTable, idx int) *LCDBitmap

GetTableBitmap gets a bitmap from a table

func (*Graphics) GetTextWidth

func (g *Graphics) GetTextWidth(font *LCDFont, text string, tracking int) int

GetTextWidth returns the width of text

func (*Graphics) LoadBitmap

func (g *Graphics) LoadBitmap(path string) (*LCDBitmap, error)

LoadBitmap loads a bitmap from file

func (*Graphics) LoadBitmapTable

func (g *Graphics) LoadBitmapTable(path string) (*LCDBitmapTable, error)

LoadBitmapTable loads a bitmap table from file

func (*Graphics) LoadFont

func (g *Graphics) LoadFont(path string) (*LCDFont, error)

LoadFont loads a font from file

func (*Graphics) MarkUpdatedRows

func (g *Graphics) MarkUpdatedRows(start, end int)

MarkUpdatedRows marks rows as needing update

func (*Graphics) NewBitmap

func (g *Graphics) NewBitmap(width, height int, bgcolor LCDColor) *LCDBitmap

NewBitmap creates a new bitmap

func (*Graphics) NewBitmapTable

func (g *Graphics) NewBitmapTable(count, width, height int) *LCDBitmapTable

NewBitmapTable creates a new bitmap table

func (*Graphics) NewTilemap added in v0.5.0

func (g *Graphics) NewTilemap() *LCDTileMap

NewTilemap creates a new tilemap

func (*Graphics) PopContext

func (g *Graphics) PopContext()

PopContext pops the current drawing context

func (*Graphics) PushContext

func (g *Graphics) PushContext(target *LCDBitmap)

PushContext pushes a new drawing context

func (*Graphics) SetBackgroundColor

func (g *Graphics) SetBackgroundColor(color LCDSolidColor)

SetBackgroundColor sets the background color

func (*Graphics) SetClipRect

func (g *Graphics) SetClipRect(x, y, width, height int)

SetClipRect sets the clipping rectangle

func (*Graphics) SetDrawMode

func (g *Graphics) SetDrawMode(mode LCDBitmapDrawMode) LCDBitmapDrawMode

SetDrawMode sets the drawing mode

func (*Graphics) SetDrawOffset

func (g *Graphics) SetDrawOffset(dx, dy int)

SetDrawOffset sets the drawing offset

func (*Graphics) SetFont

func (g *Graphics) SetFont(font *LCDFont)

SetFont sets the current font

func (*Graphics) SetLineCapStyle

func (g *Graphics) SetLineCapStyle(style LCDLineCapStyle)

SetLineCapStyle sets line cap style

func (*Graphics) SetTextTracking

func (g *Graphics) SetTextTracking(tracking int)

SetTextTracking sets text tracking

func (*Graphics) TileBitmap

func (g *Graphics) TileBitmap(bitmap *LCDBitmap, x, y, width, height int, flip LCDBitmapFlip)

TileBitmap tiles a bitmap

type HTTPRequest added in v0.2.0

type HTTPRequest struct {
	// contains filtered or unexported fields
}

HTTPRequest represents an HTTP request

type HTTPResponse added in v0.2.0

type HTTPResponse struct {
	StatusCode int
	Headers    map[string]string
	Body       []byte
}

HTTPResponse represents an HTTP response

type InstrumentAPI

type InstrumentAPI struct{}

InstrumentAPI wraps instrument functions

func (*InstrumentAPI) AddVoice

func (i *InstrumentAPI) AddVoice(inst *PDSynthInstrument, synth *PDSynth, rangeStart, rangeEnd MIDINote, transpose float32) bool

AddVoice adds a voice to the instrument

func (*InstrumentAPI) NewInstrument

func (i *InstrumentAPI) NewInstrument() *PDSynthInstrument

NewInstrument creates a new instrument

func (*InstrumentAPI) SetVolume

func (i *InstrumentAPI) SetVolume(inst *PDSynthInstrument, left, right float32)

SetVolume sets the instrument volume

type JSON

type JSON struct{}

JSON provides access to Playdate JSON parsing

func (*JSON) DecodeFile added in v0.4.0

func (j *JSON) DecodeFile(file *SDFile, handler JSONDecodeHandler) error

DecodeFile decodes JSON from an open file using the provided handler

func (*JSON) DecodeString

func (j *JSON) DecodeString(jsonStr string, handler JSONDecodeHandler) error

DecodeString decodes a JSON string using the provided handler

func (*JSON) NewEncoder

func (j *JSON) NewEncoder(pretty bool) *JSONEncoder

NewEncoder creates a new JSON encoder If pretty is true, output will be formatted with indentation

func (*JSON) Parse added in v0.4.0

func (j *JSON) Parse(jsonStr string) (*JSONNode, error)

Parse parses JSON string and returns tree

func (*JSON) ParseFile added in v0.4.0

func (j *JSON) ParseFile(file *SDFile) (*JSONNode, error)

ParseFile parses JSON from file and returns tree

type JSONDecodeHandler added in v0.4.0

type JSONDecodeHandler interface {
	// DecodeError is called when a parse error occurs
	DecodeError(error string, lineNum int)

	// WillDecodeSublist is called before decoding an array or table
	WillDecodeSublist(name string, valueType JSONValueType)

	// ShouldDecodeTableValueForKey returns true to decode this key's value
	ShouldDecodeTableValueForKey(key string) bool

	// DidDecodeTableValue is called after decoding a table value
	DidDecodeTableValue(key string, value JSONValue)

	// ShouldDecodeArrayValueAtIndex returns true to decode this index's value
	ShouldDecodeArrayValueAtIndex(pos int) bool

	// DidDecodeArrayValue is called after decoding an array value
	DidDecodeArrayValue(pos int, value JSONValue)

	// DidDecodeSublist is called after finishing an array or table
	DidDecodeSublist(name string, valueType JSONValueType)
}

JSONDecodeHandler handles JSON decode events

type JSONEncoder

type JSONEncoder struct {
	// contains filtered or unexported fields
}

JSONEncoder encodes data to JSON format

func (*JSONEncoder) AddArrayElement added in v0.4.0

func (e *JSONEncoder) AddArrayElement()

AddArrayElement prepares for next array element

func (*JSONEncoder) Bytes added in v0.4.0

func (e *JSONEncoder) Bytes() []byte

Bytes returns the encoded JSON as bytes

func (*JSONEncoder) EndArray

func (e *JSONEncoder) EndArray()

EndArray ends a JSON array

func (*JSONEncoder) EndObject added in v0.4.0

func (e *JSONEncoder) EndObject()

EndObject ends a JSON object

func (*JSONEncoder) Free

func (e *JSONEncoder) Free()

Free releases encoder resources

func (*JSONEncoder) StartArray

func (e *JSONEncoder) StartArray()

StartArray starts a JSON array [...]

func (*JSONEncoder) StartObject added in v0.4.0

func (e *JSONEncoder) StartObject()

StartObject starts a JSON object {...}

func (*JSONEncoder) String added in v0.4.0

func (e *JSONEncoder) String() string

String returns the encoded JSON string

func (*JSONEncoder) WriteBool

func (e *JSONEncoder) WriteBool(v bool)

WriteBool writes boolean value

func (*JSONEncoder) WriteFloat

func (e *JSONEncoder) WriteFloat(v float64)

WriteFloat writes float value

func (*JSONEncoder) WriteInt

func (e *JSONEncoder) WriteInt(v int)

WriteInt writes integer value

func (*JSONEncoder) WriteKey added in v0.4.0

func (e *JSONEncoder) WriteKey(key string)

WriteKey writes an object key (call before writing value)

func (*JSONEncoder) WriteNull

func (e *JSONEncoder) WriteNull()

WriteNull writes null value

func (*JSONEncoder) WriteString

func (e *JSONEncoder) WriteString(s string)

WriteString writes string value

type JSONNode added in v0.4.0

type JSONNode struct {
	Type     JSONValueType
	IntVal   int
	FloatVal float32
	StrVal   string
	Array    []*JSONNode
	Object   map[string]*JSONNode
}

JSONNode represents a JSON value in a tree structure

func (*JSONNode) At added in v0.4.0

func (n *JSONNode) At(index int) *JSONNode

At returns child node by index (for arrays)

func (*JSONNode) Get added in v0.4.0

func (n *JSONNode) Get(key string) *JSONNode

Get returns child node by key (for objects)

func (*JSONNode) GetBool added in v0.4.0

func (n *JSONNode) GetBool() bool

GetBool returns boolean value

func (*JSONNode) GetFloat added in v0.4.0

func (n *JSONNode) GetFloat() float32

GetFloat returns float value

func (*JSONNode) GetInt added in v0.4.0

func (n *JSONNode) GetInt() int

GetInt returns integer value

func (*JSONNode) GetString added in v0.4.0

func (n *JSONNode) GetString() string

GetString returns string value

func (*JSONNode) IsNull added in v0.4.0

func (n *JSONNode) IsNull() bool

IsNull returns true if node is null

func (*JSONNode) Len added in v0.4.0

func (n *JSONNode) Len() int

Len returns length of array or object

type JSONValue

type JSONValue struct {
	Type   JSONValueType
	Int    int
	Float  float32
	String string
}

JSONValue represents a decoded JSON value

type JSONValueType

type JSONValueType int

JSONValueType represents JSON value types (matches Playdate SDK)

const (
	JSONNull    JSONValueType = 0
	JSONTrue    JSONValueType = 1
	JSONFalse   JSONValueType = 2
	JSONInteger JSONValueType = 3
	JSONFloat   JSONValueType = 4
	JSONString  JSONValueType = 5
	JSONArray   JSONValueType = 6
	JSONTable   JSONValueType = 7
)

type LCDBitmap

type LCDBitmap struct {
	// contains filtered or unexported fields
}

LCDBitmap represents a bitmap image

type LCDBitmapDrawMode

type LCDBitmapDrawMode int32

LCDBitmapDrawMode represents bitmap draw modes

const (
	DrawModeCopy        LCDBitmapDrawMode = 0
	DrawModeWhiteTransp LCDBitmapDrawMode = 1
	DrawModeBlackTransp LCDBitmapDrawMode = 2
	DrawModeFillWhite   LCDBitmapDrawMode = 3
	DrawModeFillBlack   LCDBitmapDrawMode = 4
	DrawModeXOR         LCDBitmapDrawMode = 5
	DrawModeNXOR        LCDBitmapDrawMode = 6
	DrawModeInverted    LCDBitmapDrawMode = 7
)

type LCDBitmapFlip

type LCDBitmapFlip int32

LCDBitmapFlip represents bitmap flip options

const (
	BitmapUnflipped LCDBitmapFlip = 0
	BitmapFlippedX  LCDBitmapFlip = 1
	BitmapFlippedY  LCDBitmapFlip = 2
	BitmapFlippedXY LCDBitmapFlip = 3
)

type LCDBitmapTable

type LCDBitmapTable struct {
	// contains filtered or unexported fields
}

LCDBitmapTable represents a table of bitmaps

type LCDColor

type LCDColor uint32

LCDColor represents a color value

const (
	SolidBlack LCDColor = 0
	SolidWhite LCDColor = 1
)

Convenience color values

type LCDFont

type LCDFont struct {
	// contains filtered or unexported fields
}

LCDFont represents a font

type LCDLineCapStyle

type LCDLineCapStyle int32

LCDLineCapStyle represents line cap styles

const (
	LineCapStyleButt   LCDLineCapStyle = 0
	LineCapStyleSquare LCDLineCapStyle = 1
	LineCapStyleRound  LCDLineCapStyle = 2
)

type LCDSolidColor

type LCDSolidColor int32

LCDSolidColor represents solid colors

const (
	ColorBlack LCDSolidColor = 0
	ColorWhite LCDSolidColor = 1
	ColorClear LCDSolidColor = 2
	ColorXOR   LCDSolidColor = 3
)

type LCDSprite

type LCDSprite = Sprite

LCDSprite is an alias for Sprite (for API compatibility)

type LCDTileMap

type LCDTileMap struct {
	// contains filtered or unexported fields
}

LCDTileMap represents a tilemap

func (*LCDTileMap) DrawAtPoint added in v0.5.0

func (t *LCDTileMap) DrawAtPoint(x, y float32)

DrawAtPoint draws the tilemap at the given position

func (*LCDTileMap) Free added in v0.5.0

func (t *LCDTileMap) Free()

Free frees the tilemap

func (*LCDTileMap) GetImageTable added in v0.5.0

func (t *LCDTileMap) GetImageTable() *LCDBitmapTable

GetImageTable gets the image table from the tilemap

func (*LCDTileMap) GetSize added in v0.5.0

func (t *LCDTileMap) GetSize() (tilesWide, tilesHigh int)

GetSize returns the size of the tilemap in tiles

func (*LCDTileMap) GetTileAtPosition added in v0.5.0

func (t *LCDTileMap) GetTileAtPosition(x, y int) int

GetTileAtPosition gets the tile index at the given position

func (*LCDTileMap) SetImageTable added in v0.5.0

func (t *LCDTileMap) SetImageTable(table *LCDBitmapTable)

SetImageTable sets the image table for the tilemap

func (*LCDTileMap) SetSize added in v0.5.0

func (t *LCDTileMap) SetSize(tilesWide, tilesHigh int)

SetSize sets the size of the tilemap in tiles

func (*LCDTileMap) SetTileAtPosition added in v0.5.0

func (t *LCDTileMap) SetTileAtPosition(x, y int, idx uint16)

SetTileAtPosition sets the tile index at the given position

type Lua

type Lua struct{}

Lua provides access to Lua scripting

func (*Lua) AddFunction added in v0.2.0

func (l *Lua) AddFunction(name string, callback func(args []interface{}) interface{}) error

AddFunction adds a Go function callable from Lua

func (*Lua) ArgIsNil

func (l *Lua) ArgIsNil(pos int) bool

ArgIsNil checks if argument is nil

func (*Lua) GetArgBool

func (l *Lua) GetArgBool(pos int) bool

GetArgBool gets boolean argument

func (*Lua) GetArgCount

func (l *Lua) GetArgCount() int

GetArgCount returns number of Lua arguments

func (*Lua) GetArgFloat

func (l *Lua) GetArgFloat(pos int) float32

GetArgFloat gets float argument

func (*Lua) GetArgInt

func (l *Lua) GetArgInt(pos int) int

GetArgInt gets integer argument

func (*Lua) GetArgString

func (l *Lua) GetArgString(pos int) string

GetArgString gets string argument

func (*Lua) GetArgType

func (l *Lua) GetArgType(pos int) (LuaType, string)

GetArgType returns type of argument at index and class name

func (*Lua) PushBool

func (l *Lua) PushBool(val bool)

PushBool pushes bool to Lua stack

func (*Lua) PushFloat

func (l *Lua) PushFloat(val float32)

PushFloat pushes float to Lua stack

func (*Lua) PushInt

func (l *Lua) PushInt(val int)

PushInt pushes int to Lua stack

func (*Lua) PushNil

func (l *Lua) PushNil()

PushNil pushes nil to Lua stack

func (*Lua) PushString

func (l *Lua) PushString(val string)

PushString pushes string to Lua stack

type LuaType

type LuaType int32

LuaType represents Lua value types

const (
	LuaTypeNil      LuaType = 0
	LuaTypeBool     LuaType = 1
	LuaTypeInt      LuaType = 2
	LuaTypeFloat    LuaType = 3
	LuaTypeString   LuaType = 4
	LuaTypeTable    LuaType = 5
	LuaTypeFunction LuaType = 6
	LuaTypeThread   LuaType = 7
	LuaTypeObject   LuaType = 8
)

type MIDINote

type MIDINote float32

MIDINote represents a MIDI note number

type Network

type Network struct{}

Network provides access to network functions (Simulator only)

func (*Network) Cancel added in v0.2.0

func (n *Network) Cancel(request *HTTPRequest)

Cancel cancels a pending request

func (*Network) Get added in v0.2.0

func (n *Network) Get(url string, callback NetworkCallback) *HTTPRequest

Get performs an HTTP GET request (Simulator only)

func (*Network) Post added in v0.2.0

func (n *Network) Post(url string, body []byte, contentType string, callback NetworkCallback) *HTTPRequest

Post performs an HTTP POST request (Simulator only)

type NetworkCallback added in v0.2.0

type NetworkCallback func(response *HTTPResponse, err error)

NetworkCallback is called when a request completes

type PDBoard

type PDBoard struct {
	BoardID string
	Name    string
}

PDBoard represents a scoreboard

type PDButtons

type PDButtons uint32

PDButtons represents button state

const (
	ButtonLeft  PDButtons = 1 << 0
	ButtonRight PDButtons = 1 << 1
	ButtonUp    PDButtons = 1 << 2
	ButtonDown  PDButtons = 1 << 3
	ButtonB     PDButtons = 1 << 4
	ButtonA     PDButtons = 1 << 5
)

type PDLanguage

type PDLanguage int32

PDLanguage represents system language

const (
	LanguageEnglish  PDLanguage = 0
	LanguageJapanese PDLanguage = 1
)

type PDPeripherals

type PDPeripherals uint32

PDPeripherals represents peripheral flags

const (
	PeripheralNone          PDPeripherals = 0
	PeripheralAccelerometer PDPeripherals = 1 << 0
)

type PDPersonalBest added in v0.2.0

type PDPersonalBest struct {
	Rank  uint32
	Value uint32
}

PDPersonalBest represents a personal best score

type PDRect

type PDRect struct {
	X      float32
	Y      float32
	Width  float32
	Height float32
}

PDRect represents a rectangle

type PDScore

type PDScore struct {
	Rank   uint32
	Value  uint32
	Player string
}

PDScore represents a score entry

type PDScoresList

type PDScoresList struct {
	BoardID     string
	LastUpdated uint32
	Scores      []PDScore
}

PDScoresList represents a list of scores

type PDStringEncoding

type PDStringEncoding int32

Text encoding types

const (
	ASCIIEncoding  PDStringEncoding = 0
	UTF8Encoding   PDStringEncoding = 1
	Latin1Encoding PDStringEncoding = 2
)

type PDSynth

type PDSynth struct {
	// contains filtered or unexported fields
}

PDSynth represents a synthesizer

type PDSynthInstrument

type PDSynthInstrument struct {
	// contains filtered or unexported fields
}

PDSynthInstrument represents a synth instrument

type PDSystemEvent

type PDSystemEvent int32

PDSystemEvent represents system events

const (
	EventInit        PDSystemEvent = 0
	EventInitLua     PDSystemEvent = 1
	EventLock        PDSystemEvent = 2
	EventUnlock      PDSystemEvent = 3
	EventPause       PDSystemEvent = 4
	EventResume      PDSystemEvent = 5
	EventTerminate   PDSystemEvent = 6
	EventKeyPressed  PDSystemEvent = 7
	EventKeyReleased PDSystemEvent = 8
	EventLowPower    PDSystemEvent = 9
)

type PlaydateAPI

type PlaydateAPI struct {
	System      *System
	Graphics    *Graphics
	Display     *Display
	Sprite      *SpriteAPI
	File        *File
	Sound       *Sound
	Lua         *Lua
	JSON        *JSON
	Scoreboards *Scoreboards
	Network     *Network
	// contains filtered or unexported fields
}

PlaydateAPI is the main API wrapper

func GetAPI

func GetAPI() *PlaydateAPI

GetAPI returns the current PlaydateAPI instance

func Init

func Init(playdateAPI unsafe.Pointer) *PlaydateAPI

Init initializes the Playdate API with the provided C API pointer. This should be called from your eventHandler function.

type SDFile

type SDFile struct {
	// contains filtered or unexported fields
}

SDFile represents an open file

type SampleAPI

type SampleAPI struct{}

SampleAPI wraps sample functions

func (*SampleAPI) Load

func (sa *SampleAPI) Load(path string) *AudioSample

Load loads an audio sample from file

type SamplePlayer

type SamplePlayer struct {
	// contains filtered or unexported fields
}

SamplePlayer plays audio samples

type Scoreboards

type Scoreboards struct{}

Scoreboards provides access to online scoreboards

func (*Scoreboards) AddScore

func (s *Scoreboards) AddScore(boardID string, value uint32, callback ScoreboardsResult)

AddScore adds a score to a board

func (*Scoreboards) FreeBoardsList

func (s *Scoreboards) FreeBoardsList(boards []PDBoard)

FreeBoardsList frees boards list

func (*Scoreboards) FreeScore

func (s *Scoreboards) FreeScore(score *PDPersonalBest)

FreeScore frees a score result

func (*Scoreboards) FreeScoresList

func (s *Scoreboards) FreeScoresList(scores *PDScoresList)

FreeScoresList frees scores list

func (*Scoreboards) GetPersonalBest

func (s *Scoreboards) GetPersonalBest(boardID string, callback ScoreboardsResult)

GetPersonalBest gets personal best score

func (*Scoreboards) GetScoreboards

func (s *Scoreboards) GetScoreboards(callback ScoreboardsResult)

GetScoreboards gets list of scoreboards

func (*Scoreboards) GetScores

func (s *Scoreboards) GetScores(boardID string, callback ScoreboardsResult)

GetScores gets scores from a board

type ScoreboardsResult added in v0.2.0

type ScoreboardsResult func(result interface{}, errorMsg string)

ScoreboardsResult callback type

type SequenceAPI

type SequenceAPI struct{}

SequenceAPI wraps sequence functions

func (*SequenceAPI) GetCurrentStep added in v0.1.5

func (s *SequenceAPI) GetCurrentStep(seq *SoundSequence) int

GetCurrentStep returns the current step in the sequence

func (*SequenceAPI) GetTrackAtIndex

func (s *SequenceAPI) GetTrackAtIndex(seq *SoundSequence, index uint) *SequenceTrack

GetTrackAtIndex returns a track at an index

func (*SequenceAPI) GetTrackCount

func (s *SequenceAPI) GetTrackCount(seq *SoundSequence) int

GetTrackCount returns the track count

func (*SequenceAPI) LoadMIDIFile

func (s *SequenceAPI) LoadMIDIFile(seq *SoundSequence, path string) error

LoadMIDIFile loads a MIDI file into the sequence

func (*SequenceAPI) NewSequence

func (s *SequenceAPI) NewSequence() *SoundSequence

NewSequence creates a new sequence

func (*SequenceAPI) Play

func (s *SequenceAPI) Play(seq *SoundSequence)

Play plays the sequence

func (*SequenceAPI) Stop

func (s *SequenceAPI) Stop(seq *SoundSequence)

Stop stops the sequence

type SequenceTrack

type SequenceTrack struct {
	// contains filtered or unexported fields
}

SequenceTrack represents a track in a sequence

type Sound

type Sound struct {
	Channel    *ChannelAPI
	Sample     *SampleAPI
	Synth      *SynthAPI
	Sequence   *SequenceAPI
	Track      *TrackAPI
	Instrument *InstrumentAPI
}

Sound provides access to sound functions

func (*Sound) FreeAudioSample added in v0.2.0

func (s *Sound) FreeAudioSample(sample *AudioSample)

FreeAudioSample frees an audio sample

func (*Sound) FreeFilePlayer added in v0.2.0

func (s *Sound) FreeFilePlayer(player *FilePlayer)

FreeFilePlayer frees a file player

func (*Sound) FreeSamplePlayer added in v0.2.0

func (s *Sound) FreeSamplePlayer(player *SamplePlayer)

FreeSamplePlayer frees a sample player

func (*Sound) GetDefaultChannel

func (s *Sound) GetDefaultChannel() *SoundChannel

GetDefaultChannel returns the default sound channel

func (*Sound) GetFilePlayerLength added in v0.2.0

func (s *Sound) GetFilePlayerLength(player *FilePlayer) float32

GetFilePlayerLength returns length in seconds

func (*Sound) GetFilePlayerOffset added in v0.2.0

func (s *Sound) GetFilePlayerOffset(player *FilePlayer) float32

GetFilePlayerOffset gets playback offset

func (*Sound) GetFilePlayerVolume added in v0.2.0

func (s *Sound) GetFilePlayerVolume(player *FilePlayer) (left, right float32)

GetFilePlayerVolume gets volume

func (*Sound) GetHeadphoneState

func (s *Sound) GetHeadphoneState() (headphone, mic bool)

GetHeadphoneState returns headphone state

func (*Sound) IsFilePlayerPlaying added in v0.2.0

func (s *Sound) IsFilePlayerPlaying(player *FilePlayer) bool

IsFilePlayerPlaying returns true if playing

func (*Sound) IsSamplePlayerPlaying added in v0.2.0

func (s *Sound) IsSamplePlayerPlaying(player *SamplePlayer) bool

IsSamplePlayerPlaying returns true if playing

func (*Sound) LoadAudioSample added in v0.2.0

func (s *Sound) LoadAudioSample(path string) *AudioSample

LoadAudioSample loads an audio sample from file

func (*Sound) LoadIntoFilePlayer added in v0.2.0

func (s *Sound) LoadIntoFilePlayer(player *FilePlayer, path string) error

LoadIntoFilePlayer loads audio into file player

func (*Sound) NewAudioSample added in v0.2.0

func (s *Sound) NewAudioSample(length int) *AudioSample

NewAudioSample creates a new audio sample

func (*Sound) NewFilePlayer added in v0.2.0

func (s *Sound) NewFilePlayer() *FilePlayer

NewFilePlayer creates a new file player

func (*Sound) NewSamplePlayer added in v0.2.0

func (s *Sound) NewSamplePlayer() *SamplePlayer

NewSamplePlayer creates a new sample player

func (*Sound) PauseFilePlayer added in v0.2.0

func (s *Sound) PauseFilePlayer(player *FilePlayer)

PauseFilePlayer pauses playback

func (*Sound) PlayFilePlayer added in v0.2.0

func (s *Sound) PlayFilePlayer(player *FilePlayer, repeat int)

PlayFilePlayer plays audio

func (*Sound) PlaySamplePlayer added in v0.2.0

func (s *Sound) PlaySamplePlayer(player *SamplePlayer, repeat int, rate float32)

PlaySamplePlayer plays the sample

func (*Sound) SetFilePlayerOffset added in v0.2.0

func (s *Sound) SetFilePlayerOffset(player *FilePlayer, offset float32)

SetFilePlayerOffset sets playback offset

func (*Sound) SetFilePlayerRate added in v0.2.0

func (s *Sound) SetFilePlayerRate(player *FilePlayer, rate float32)

SetFilePlayerRate sets playback rate

func (*Sound) SetFilePlayerVolume added in v0.2.0

func (s *Sound) SetFilePlayerVolume(player *FilePlayer, left, right float32)

SetFilePlayerVolume sets volume (0.0 - 1.0)

func (*Sound) SetHeadphoneCallback added in v0.2.0

func (s *Sound) SetHeadphoneCallback(callback func(headphone, mic int))

SetHeadphoneCallback sets headphone callback (stub)

func (*Sound) SetOutputsActive

func (s *Sound) SetOutputsActive(headphone, speaker bool)

SetOutputsActive sets which outputs are active

func (*Sound) SetSamplePlayerSample added in v0.2.0

func (s *Sound) SetSamplePlayerSample(player *SamplePlayer, sample *AudioSample)

SetSamplePlayerSample sets the sample to play

func (*Sound) SetSamplePlayerVolume added in v0.2.0

func (s *Sound) SetSamplePlayerVolume(player *SamplePlayer, left, right float32)

SetSamplePlayerVolume sets volume

func (*Sound) StopFilePlayer added in v0.2.0

func (s *Sound) StopFilePlayer(player *FilePlayer)

StopFilePlayer stops playback

func (*Sound) StopSamplePlayer added in v0.2.0

func (s *Sound) StopSamplePlayer(player *SamplePlayer)

StopSamplePlayer stops playback

type SoundChannel

type SoundChannel struct {
	// contains filtered or unexported fields
}

SoundChannel represents a sound channel

type SoundEffect

type SoundEffect struct {
	// contains filtered or unexported fields
}

SoundEffect represents a sound effect

type SoundSequence

type SoundSequence struct {
	// contains filtered or unexported fields
}

SoundSequence represents a sound sequence

type SoundSource

type SoundSource struct {
	// contains filtered or unexported fields
}

SoundSource represents a sound source

type SoundWaveform

type SoundWaveform int32

SoundWaveform represents synth waveforms

const (
	WaveformSquare    SoundWaveform = 0
	WaveformTriangle  SoundWaveform = 1
	WaveformSine      SoundWaveform = 2
	WaveformNoise     SoundWaveform = 3
	WaveformSawtooth  SoundWaveform = 4
	WaveformPOPhase   SoundWaveform = 5
	WaveformPODigital SoundWaveform = 6
	WaveformPOVosim   SoundWaveform = 7
)

type Sprite

type Sprite struct {
	// contains filtered or unexported fields
}

Sprite represents a sprite object

func (*Sprite) Ptr added in v0.7.1

func (s *Sprite) Ptr() unsafe.Pointer

Ptr returns the underlying C pointer for sprite comparison

type SpriteAPI added in v0.2.0

type SpriteAPI struct{}

SpriteAPI provides access to sprite functions

func (*SpriteAPI) AddSprite added in v0.2.0

func (s *SpriteAPI) AddSprite(sprite *LCDSprite)

AddSprite adds a sprite to the display list

func (*SpriteAPI) AllOverlappingSprites added in v0.2.0

func (s *SpriteAPI) AllOverlappingSprites() []*LCDSprite

AllOverlappingSprites returns all overlapping sprites

func (*SpriteAPI) CheckCollisions added in v0.2.0

func (s *SpriteAPI) CheckCollisions(sprite *LCDSprite, goalX, goalY float32) ([]SpriteCollisionInfo, float32, float32)

CheckCollisions checks for collisions without moving

func (*SpriteAPI) ClearCollideRect added in v0.2.0

func (s *SpriteAPI) ClearCollideRect(sprite *LCDSprite)

ClearCollideRect clears collision rectangle

func (*SpriteAPI) DrawSprites added in v0.2.0

func (s *SpriteAPI) DrawSprites()

DrawSprites draws all sprites without updating

func (*SpriteAPI) FreeSprite added in v0.2.0

func (s *SpriteAPI) FreeSprite(sprite *LCDSprite)

FreeSprite frees a sprite

func (*SpriteAPI) GetBounds added in v0.2.0

func (s *SpriteAPI) GetBounds(sprite *LCDSprite) PDRect

GetBounds returns the sprite's bounds

func (*SpriteAPI) GetCollideRect added in v0.2.0

func (s *SpriteAPI) GetCollideRect(sprite *LCDSprite) PDRect

GetCollideRect returns collision rectangle

func (*SpriteAPI) GetImage added in v0.2.0

func (s *SpriteAPI) GetImage(sprite *LCDSprite) *LCDBitmap

GetImage returns the sprite's image

func (*SpriteAPI) GetImageFlip added in v0.2.0

func (s *SpriteAPI) GetImageFlip(sprite *LCDSprite) LCDBitmapFlip

GetImageFlip returns image flip

func (*SpriteAPI) GetPosition added in v0.2.0

func (s *SpriteAPI) GetPosition(sprite *LCDSprite) (x, y float32)

GetPosition returns sprite position

func (*SpriteAPI) GetSpriteCount added in v0.2.0

func (s *SpriteAPI) GetSpriteCount() int

GetSpriteCount returns number of sprites

func (*SpriteAPI) GetTag added in v0.2.0

func (s *SpriteAPI) GetTag(sprite *LCDSprite) uint8

GetTag returns sprite tag

func (*SpriteAPI) GetZIndex added in v0.2.0

func (s *SpriteAPI) GetZIndex(sprite *LCDSprite) int16

GetZIndex returns sprite z-index

func (*SpriteAPI) IsVisible added in v0.2.0

func (s *SpriteAPI) IsVisible(sprite *LCDSprite) bool

IsVisible returns true if sprite is visible

func (*SpriteAPI) MarkDirty added in v0.2.0

func (s *SpriteAPI) MarkDirty(sprite *LCDSprite)

MarkDirty marks the sprite as needing redraw

func (*SpriteAPI) MoveBy added in v0.2.0

func (s *SpriteAPI) MoveBy(sprite *LCDSprite, dx, dy float32)

MoveBy moves the sprite by delta

func (*SpriteAPI) MoveTo added in v0.2.0

func (s *SpriteAPI) MoveTo(sprite *LCDSprite, x, y float32)

MoveTo moves the sprite to position

func (*SpriteAPI) MoveWithCollisions added in v0.2.0

func (s *SpriteAPI) MoveWithCollisions(sprite *LCDSprite, goalX, goalY float32) ([]SpriteCollisionInfo, float32, float32)

MoveWithCollisions moves sprite with collision detection

func (*SpriteAPI) NewSprite added in v0.2.0

func (s *SpriteAPI) NewSprite() *LCDSprite

NewSprite creates a new sprite

func (*SpriteAPI) QuerySpriteInfoAlongLine added in v0.6.0

func (s *SpriteAPI) QuerySpriteInfoAlongLine(x1, y1, x2, y2 float32) []SpriteQueryInfo

QuerySpriteInfoAlongLine returns sprite query info along a line

func (*SpriteAPI) QuerySpritesAlongLine added in v0.2.0

func (s *SpriteAPI) QuerySpritesAlongLine(x1, y1, x2, y2 float32) []*LCDSprite

QuerySpritesAlongLine returns sprites along a line

func (*SpriteAPI) QuerySpritesAtPoint added in v0.2.0

func (s *SpriteAPI) QuerySpritesAtPoint(x, y float32) []*LCDSprite

QuerySpritesAtPoint returns sprites at a point

func (*SpriteAPI) QuerySpritesInRect added in v0.2.0

func (s *SpriteAPI) QuerySpritesInRect(x, y, w, h float32) []*LCDSprite

QuerySpritesInRect returns sprites in a rectangle

func (*SpriteAPI) RemoveAllSprites added in v0.2.0

func (s *SpriteAPI) RemoveAllSprites()

RemoveAllSprites removes all sprites from display

func (*SpriteAPI) RemoveSprite added in v0.2.0

func (s *SpriteAPI) RemoveSprite(sprite *LCDSprite)

RemoveSprite removes a sprite from the display list

func (*SpriteAPI) ResetCollisionWorld added in v0.2.0

func (s *SpriteAPI) ResetCollisionWorld()

ResetCollisionWorld resets the collision world

func (*SpriteAPI) SetAlwaysRedraw added in v0.2.0

func (s *SpriteAPI) SetAlwaysRedraw(flag bool)

SetAlwaysRedraw sets whether sprites always redraw

func (*SpriteAPI) SetBounds added in v0.2.0

func (s *SpriteAPI) SetBounds(sprite *LCDSprite, bounds PDRect)

SetBounds sets the sprite's bounds

func (*SpriteAPI) SetCollideRect added in v0.2.0

func (s *SpriteAPI) SetCollideRect(sprite *LCDSprite, collideRect PDRect)

SetCollideRect sets collision rectangle

func (*SpriteAPI) SetCollisionResponseFunction added in v0.2.0

func (s *SpriteAPI) SetCollisionResponseFunction(sprite *LCDSprite, callback func(*LCDSprite, *LCDSprite) SpriteCollisionResponseType)

SetCollisionResponseFunction sets the sprite's collision response callback

func (*SpriteAPI) SetCollisionsEnabled added in v0.2.0

func (s *SpriteAPI) SetCollisionsEnabled(sprite *LCDSprite, enabled bool)

SetCollisionsEnabled enables/disables collisions

func (*SpriteAPI) SetDrawFunction added in v0.2.0

func (s *SpriteAPI) SetDrawFunction(sprite *LCDSprite, callback func(*LCDSprite, PDRect, PDRect))

SetDrawFunction sets the sprite's draw callback

func (*SpriteAPI) SetDrawMode added in v0.2.0

func (s *SpriteAPI) SetDrawMode(sprite *LCDSprite, mode LCDBitmapDrawMode)

SetDrawMode sets sprite draw mode

func (*SpriteAPI) SetImage added in v0.2.0

func (s *SpriteAPI) SetImage(sprite *LCDSprite, image *LCDBitmap, flip LCDBitmapFlip)

SetImage sets the sprite's image

func (*SpriteAPI) SetImageFlip added in v0.2.0

func (s *SpriteAPI) SetImageFlip(sprite *LCDSprite, flip LCDBitmapFlip)

SetImageFlip sets image flip

func (*SpriteAPI) SetOpaque added in v0.2.0

func (s *SpriteAPI) SetOpaque(sprite *LCDSprite, opaque bool)

SetOpaque sets whether sprite is opaque

func (*SpriteAPI) SetTag added in v0.2.0

func (s *SpriteAPI) SetTag(sprite *LCDSprite, tag uint8)

SetTag sets sprite tag

func (*SpriteAPI) SetUpdateFunction added in v0.2.0

func (s *SpriteAPI) SetUpdateFunction(sprite *LCDSprite, callback func(*LCDSprite))

SetUpdateFunction sets the sprite's update callback

func (*SpriteAPI) SetUpdatesEnabled added in v0.2.0

func (s *SpriteAPI) SetUpdatesEnabled(sprite *LCDSprite, enabled bool)

SetUpdatesEnabled enables/disables sprite updates

func (*SpriteAPI) SetVisible added in v0.2.0

func (s *SpriteAPI) SetVisible(sprite *LCDSprite, visible bool)

SetVisible sets sprite visibility

func (*SpriteAPI) SetZIndex added in v0.2.0

func (s *SpriteAPI) SetZIndex(sprite *LCDSprite, z int16)

SetZIndex sets sprite z-index

func (*SpriteAPI) UpdateAndDrawSprites added in v0.2.0

func (s *SpriteAPI) UpdateAndDrawSprites()

UpdateAndDrawSprites updates and draws all sprites

type SpriteCollisionInfo

type SpriteCollisionInfo struct {
	Sprite       *LCDSprite
	Other        *LCDSprite
	ResponseType SpriteCollisionResponseType
	Overlaps     bool
	Ti           float32
	Move         CollisionPoint
	Normal       CollisionVector
	Touch        CollisionPoint
	SpriteRect   PDRect
	OtherRect    PDRect
}

SpriteCollisionInfo for collision results

type SpriteCollisionResponseType

type SpriteCollisionResponseType int32

SpriteCollisionResponseType represents collision response types

const (
	CollisionTypeSlide   SpriteCollisionResponseType = 0
	CollisionTypeFreeze  SpriteCollisionResponseType = 1
	CollisionTypeOverlap SpriteCollisionResponseType = 2
	CollisionTypeBounce  SpriteCollisionResponseType = 3
)

type SpriteQueryInfo

type SpriteQueryInfo struct {
	Sprite     *LCDSprite
	Ti1        float32
	Ti2        float32
	EntryPoint CollisionPoint
	ExitPoint  CollisionPoint
}

SpriteQueryInfo contains information about a sprite intersection along a line

type SynthAPI

type SynthAPI struct{}

SynthAPI wraps synth functions

func (*SynthAPI) Copy

func (sy *SynthAPI) Copy(synth *PDSynth) *PDSynth

Copy copies a synth

func (*SynthAPI) FreeSynth

func (sy *SynthAPI) FreeSynth(synth *PDSynth)

FreeSynth frees a synth

func (*SynthAPI) GetVolume

func (sy *SynthAPI) GetVolume(synth *PDSynth) (left, right float32)

GetVolume returns the volume

func (*SynthAPI) IsPlaying

func (sy *SynthAPI) IsPlaying(synth *PDSynth) bool

IsPlaying returns whether the synth is playing

func (*SynthAPI) NewSynth

func (sy *SynthAPI) NewSynth() *PDSynth

NewSynth creates a new synth

func (*SynthAPI) NoteOff

func (sy *SynthAPI) NoteOff(synth *PDSynth, when uint32)

NoteOff releases a note

func (*SynthAPI) PlayMIDINote

func (sy *SynthAPI) PlayMIDINote(synth *PDSynth, note MIDINote, vel, length float32, when uint32)

PlayMIDINote plays a MIDI note

func (*SynthAPI) PlayNote

func (sy *SynthAPI) PlayNote(synth *PDSynth, freq, vel, length float32, when uint32)

PlayNote plays a note

func (*SynthAPI) SetAttackTime

func (sy *SynthAPI) SetAttackTime(synth *PDSynth, attack float32)

SetAttackTime sets the attack time

func (*SynthAPI) SetDecayTime

func (sy *SynthAPI) SetDecayTime(synth *PDSynth, decay float32)

SetDecayTime sets the decay time

func (*SynthAPI) SetReleaseTime

func (sy *SynthAPI) SetReleaseTime(synth *PDSynth, release float32)

SetReleaseTime sets the release time

func (*SynthAPI) SetSample

func (sy *SynthAPI) SetSample(synth *PDSynth, sample *AudioSample, sustainStart, sustainEnd uint32)

SetSample sets the sample for the synth

func (*SynthAPI) SetSustainLevel

func (sy *SynthAPI) SetSustainLevel(synth *PDSynth, sustain float32)

SetSustainLevel sets the sustain level

func (*SynthAPI) SetTranspose

func (sy *SynthAPI) SetTranspose(synth *PDSynth, halfSteps float32)

SetTranspose sets the transpose

func (*SynthAPI) SetVolume

func (sy *SynthAPI) SetVolume(synth *PDSynth, left, right float32)

SetVolume sets the volume

func (*SynthAPI) SetWaveform

func (sy *SynthAPI) SetWaveform(synth *PDSynth, wave SoundWaveform)

SetWaveform sets the waveform

func (*SynthAPI) Stop

func (sy *SynthAPI) Stop(synth *PDSynth)

Stop stops the synth

type System

type System struct{}

System provides access to Playdate system functions

func (*System) DrawFPS

func (s *System) DrawFPS(x, y int)

DrawFPS draws the current FPS at the given position

func (*System) Error

func (s *System) Error(msg string)

Error logs an error message

func (*System) GetAccelerometer

func (s *System) GetAccelerometer() (x, y, z float32)

GetAccelerometer returns accelerometer readings

func (*System) GetBatteryPercentage

func (s *System) GetBatteryPercentage() float32

GetBatteryPercentage returns battery percentage (0.0-1.0)

func (*System) GetBatteryVoltage

func (s *System) GetBatteryVoltage() float32

GetBatteryVoltage returns battery voltage

func (*System) GetButtonState

func (s *System) GetButtonState() (current, pushed, released PDButtons)

GetButtonState returns current, pushed, and released button states

func (*System) GetCrankAngle

func (s *System) GetCrankAngle() float32

GetCrankAngle returns current crank angle (0-360)

func (*System) GetCrankChange

func (s *System) GetCrankChange() float32

GetCrankChange returns crank angle change since last call

func (*System) GetCurrentTimeMilliseconds

func (s *System) GetCurrentTimeMilliseconds() uint

GetCurrentTimeMilliseconds returns the current time in milliseconds

func (*System) GetFlipped

func (s *System) GetFlipped() bool

GetFlipped returns true if the device is flipped

func (*System) GetLanguage

func (s *System) GetLanguage() PDLanguage

GetLanguage returns the system language

func (*System) GetSecondsSinceEpoch

func (s *System) GetSecondsSinceEpoch() (seconds uint, milliseconds uint)

GetSecondsSinceEpoch returns seconds and milliseconds since epoch

func (*System) IsCrankDocked

func (s *System) IsCrankDocked() bool

IsCrankDocked returns true if crank is docked

func (*System) LogToConsole

func (s *System) LogToConsole(msg string)

LogToConsole prints a message to the Playdate console

func (*System) SetAutoLockDisabled

func (s *System) SetAutoLockDisabled(disabled bool)

SetAutoLockDisabled disables/enables auto lock

func (*System) SetCrankSoundsDisabled

func (s *System) SetCrankSoundsDisabled(disabled bool) bool

SetCrankSoundsDisabled disables/enables crank sounds

func (*System) SetPeripheralsEnabled

func (s *System) SetPeripheralsEnabled(mask PDPeripherals)

SetPeripheralsEnabled enables or disables peripherals like accelerometer

func (*System) SetUpdateCallback

func (s *System) SetUpdateCallback(callback func() int)

SetUpdateCallback sets the update callback function

type TrackAPI

type TrackAPI struct{}

TrackAPI wraps track functions

func (*TrackAPI) GetIndexForStep added in v0.1.5

func (t *TrackAPI) GetIndexForStep(track *SequenceTrack, step uint32) int

GetIndexForStep returns the internal index for the step

func (*TrackAPI) GetNoteAtIndex added in v0.1.5

func (t *TrackAPI) GetNoteAtIndex(track *SequenceTrack, index int) (step, length uint32, note MIDINote, velocity float32, ok bool)

GetNoteAtIndex returns note information at the given index

func (*TrackAPI) GetPolyphony added in v0.1.5

func (t *TrackAPI) GetPolyphony(track *SequenceTrack) int

GetPolyphony returns the maximum polyphony for the track

func (*TrackAPI) SetInstrument

func (t *TrackAPI) SetInstrument(track *SequenceTrack, inst *PDSynthInstrument)

SetInstrument sets the instrument for a track

Directories

Path Synopsis
cmd
pdgoc module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL