### Lua: Example Font Paths Table for newFamily Source: https://sdk.play.date/2.7.4/index Example Lua code demonstrating the structure of the `fontPaths` table required by `playdate.graphics.font.newFamily()`. It maps font variant constants to their respective file paths, enabling the creation of a comprehensive font family. ```Lua local fontPaths = { [playdate.graphics.font.kVariantNormal] = "path/to/normalFont", [playdate.graphics.font.kVariantBold] = "path/to/boldFont", [playdate.graphics.font.kVariantItalic] = "path/to/italicFont" } ``` -------------------------------- ### Lua: Example of Animating a Sprite with Animator Source: https://sdk.play.date/2.7.4/index Demonstrates how to use `playdate.graphics.animator` to automatically move a sprite along a polygon path. The example initializes a sprite, creates a polygon and an animator with an easing function, and then sets the animator on the sprite. It also shows how to check for animation completion. ```Lua -- You can copy and paste this example directly as your main.lua file to see it in action import "CoreLibs/animator" import "CoreLibs/sprites" -- We'll be demonstrating how to use an animator to animate a sprite local square = playdate.graphics.image.new(20, 20, playdate.graphics.kColorBlack) local squareSprite = playdate.graphics.sprite.new(square) squareSprite:add() -- 4000ms, or 4 seconds local animationDuration = 4000 -- We're animating in a rectangle, around the screen. The animator must be animating along some geometry -- or between two points if used on a sprite - just animating between two values will result in an error local polygon = playdate.geometry.polygon.new(20, 20, 380, 20, 380, 220, 20, 220, 20, 20) -- Setting an easing function to get a nice, smooth movement local easingFunction = playdate.easingFunctions.inOutCubic local animator = playdate.graphics.animator.new(animationDuration, polygon, easingFunction) -- Setting the animator on the sprite to move it squareSprite:setAnimator(animator) function playdate.update() -- Everything is handled automatically, provided you call the sprite update function playdate.graphics.sprite.update() -- Set to and stays true on animation end - will print continuously when the animation finishes if animator:ended() then print("Animation ended!") end end ``` -------------------------------- ### Playdate Timer Bouncing Ball Animation Example Source: https://sdk.play.date/2.7.4/index Provides a comprehensive example of using `playdate.timer` to create a bouncing animation. It demonstrates setting up a timer with start/end values, custom easing functions, and configuring it to reverse and repeat, updating a rectangle's position via an `updateCallback`. ```Lua local r = playdate.geometry.rect.new(100, 10, 40, 40) local t = playdate.timer.new(1000, 10, 150, easingFunctions.inCubic) t.reverses = true t.repeats = true t.reverseEasingFunction = easingFunctions.outQuad t.updateCallback = function(timer) r.y = timer.value end ``` -------------------------------- ### Playdate Localization: English Strings File Example Source: https://sdk.play.date/2.7.4/index Example of an `en.strings` file used for localization in Playdate games. It defines key-value pairs for string lookups, with comments allowed. ```Text "greeting" = "Howdy" "farewell" = "Goodbye" -- comments are allowed "video game" = "video game" ``` -------------------------------- ### Example Key Repeat Timer Usage Source: https://sdk.play.date/2.7.4/index Demonstrates how to use `playdate.timer.keyRepeatTimer` to trigger a callback function on button press and release, and how to update timers in the main loop. ```Lua import "CoreLibs/timer" local keyTimer = nil function playdate.BButtonDown() local function timerCallback() print("key repeat timer fired!") end keyTimer = playdate.timer.keyRepeatTimer(timerCallback) end function playdate.BButtonUp() keyTimer:remove() end function playdate.update() playdate.timer.updateTimers() end ``` -------------------------------- ### Lua: Example Font Family Table for setFontFamily Source: https://sdk.play.date/2.7.4/index Example Lua code demonstrating the structure of the `fontFamily` table used by `playdate.graphics.setFontFamily()`. It maps font variant constants to actual font objects, enabling the simultaneous setting of multiple font styles. ```Lua local fontFamily = { [playdate.graphics.font.kVariantNormal] = normal_font, [playdate.graphics.font.kVariantBold] = bold_font, [playdate.graphics.font.kVariantItalic] = italic_font } ``` -------------------------------- ### Lua Example: Screen Shake Effect with playdate.display.setOffset Source: https://sdk.play.date/2.7.4/index This Lua example demonstrates how to implement a screen shake effect using `playdate.display.setOffset` in the Playdate SDK. It utilizes `playdate.timer` to gradually reduce the shake magnitude over time and triggers the effect when the 'A' button is pressed. The example also includes a simple circle drawing to visualize the shake. ```Lua -- You can copy and paste this example directly as your main.lua file to see it in action import "CoreLibs/graphics" import "CoreLibs/timer" -- This function relies on the use of timers, so the timer core library -- must be imported, and updateTimers() must be called in the update loop local function screenShake(shakeTime, shakeMagnitude) -- Creating a value timer that goes from shakeMagnitude to 0, over -- the course of 'shakeTime' milliseconds local shakeTimer = playdate.timer.new(shakeTime, shakeMagnitude, 0) -- Every frame when the timer is active, we shake the screen shakeTimer.updateCallback = function(timer) -- Using the timer value, so the shaking magnitude -- gradually decreases over time local magnitude = math.floor(timer.value) local shakeX = math.random(-magnitude, magnitude) local shakeY = math.random(-magnitude, magnitude) playdate.display.setOffset(shakeX, shakeY) end -- Resetting the display offset at the end of the screen shake shakeTimer.timerEndedCallback = function() playdate.display.setOffset(0, 0) end end function playdate.update() playdate.timer.updateTimers() if playdate.buttonJustPressed(playdate.kButtonA) then -- Shake the screen for 500ms, with the screen -- shaking around by about 5 pixels on each side screenShake(500, 5) end -- A circle to be able to view what the shaking looks like playdate.graphics.fillCircleAtPoint(200, 120, 10) end ``` -------------------------------- ### Playdate Localization: Japanese Strings File Example Source: https://sdk.play.date/2.7.4/index Example of a `jp.strings` file used for localization in Playdate games. It defines key-value pairs for string lookups, corresponding to the English version. ```Text "greeting" = "こんにちは" "farewell" = "さようなら" -- comments are allowed "video game" = "ビデオゲーム" ``` -------------------------------- ### Lua Example: Simple Ball Rolling with Playdate Accelerometer Source: https://sdk.play.date/2.7.4/index A practical Lua example demonstrating how to use the Playdate accelerometer to control a ball's movement on the screen. It includes functions for clamping values and continuously updates the ball's position based on accelerometer readings. ```Lua -- You can copy and paste this example directly as your main.lua file to see it in action import "CoreLibs/graphics" local function clamp(value, min, max) return math.max(math.min(value, max), min) end local x, y = 200, 120 -- Make sure to start the accelerometer to begin reading! playdate.startAccelerometer() -- A simple example of rolling around a ball on the screen using the accelerometer function playdate.update() playdate.graphics.clear() -- We can get the accelerometer values by storing them in multiple variables local gravityX, gravityY, _gravityZ = playdate.readAccelerometer() -- Try orienting the Playdate flat and tilting it around x = clamp(x + gravityX * 10, 0, 400) y = clamp(y + gravityY * 10, 0, 240) playdate.graphics.fillCircleAtPoint(x, y, 10) end ``` -------------------------------- ### Create List-Style Grid View in Playdate Lua Source: https://sdk.play.date/2.7.4/index This example illustrates setting up a grid view to function as a simple list. It populates the list with menu options and customizes cell drawing to highlight selected items and display text. ```Lua local menuOptions = {"Sword", "Shield", "Arrow", "Sling", "Stone", "Longbow", "MorningStar", "Armour", "Dagger", "Rapier", "Skeggox", "War Hammer", "Battering Ram", "Catapult"} local listview = playdate.ui.gridview.new(0, 10) listview.backgroundImage = playdate.graphics.nineSlice.new('scrollbg', 20, 23, 92, 28) listview:setNumberOfRows(#menuOptions) listview:setCellPadding(0, 0, 13, 10) listview:setContentInset(24, 24, 13, 11) function listview:drawCell(section, row, column, selected, x, y, width, height) if selected then gfx.fillRoundRect(x, y, width, 20, 4) gfx.setImageDrawMode(gfx.kDrawModeFillWhite) else gfx.setImageDrawMode(gfx.kDrawModeCopy) end gfx.drawTextInRect(menuOptions[row], x, y+2, width, height, nil, "...", kTextAlignment.center) end ``` -------------------------------- ### Encode Audio to ADPCM with FFmpeg Source: https://sdk.play.date/2.7.4/index Command-line example for converting audio files to the ADPCM IMA WAV format using FFmpeg, which is recommended for Playdate games due to its balance of file size and CPU efficiency. ```bash ffmpeg -i input.mp3 -acodec adpcm_ima_wav output.wav ``` -------------------------------- ### Create a Simple Lua Tree Class Source: https://sdk.play.date/2.7.4/index Demonstrates how to create a `Tree` class, showing examples both without and with default properties. If no parent class is specified, it defaults to inheriting from the base `Object` class. ```Lua class('Tree').extends() class('Tree', {color = 'Brown'}).extends(Object) ``` -------------------------------- ### Lua: Minimal Video Player Implementation Source: https://sdk.play.date/2.7.4/index Demonstrates how to initialize and use the Playdate video player to render frames from a PDV file. It shows setting up the display context, loading a video, and synchronizing video frames with audio playback using a sample player. ```Lua local disp = playdate.display local gfx = playdate.graphics local snd = playdate.sound disp.setRefreshRate(0) local video = gfx.video.new('movie') video:useScreenContext() video:renderFrame(0) local lastframe = 0 local audio, loaderr = snd.sampleplayer.new('movie') if audio ~= nil then audio:play(0) else print(loaderr) end function playdate.update() local frame = math.floor(audio:getOffset() * video:getFrameRate()) if frame ~= lastframe then video:renderFrame(frame) lastframe = frame end end ``` -------------------------------- ### Get Point On Arc Source: https://sdk.play.date/2.7.4/index Returns a new `point` object located at a specified distance along the arc from its start angle. The `extend` parameter controls whether the point can project beyond the arc's endpoints. ```APIDOC playdate.geometry.arc:pointOnArc(distance, [extend]) distance: number - The distance in pixels from the arc’s start angle. [extend]: boolean - Optional. If true, the returned point can project past the arc’s endpoints. Returns: point - A new point on the arc. ``` -------------------------------- ### Example: Drawing Styled Text with playdate.graphics.drawText Source: https://sdk.play.date/2.7.4/index Demonstrates how to use asterisks for bold and underscores for italic styling within the `drawText` function. Requires appropriate font variants to be set via `setFont()`. ```Lua playdate.graphics.drawText("normal *bold* _italic_", x, y) ``` -------------------------------- ### Get Point on Playdate Geometry Polygon Segment by Distance Source: https://sdk.play.date/2.7.4/index Returns a `playdate.geometry.point` located on one of the polygon's line segments, at a specified `distance` from the start of the polygon. The `extend` parameter controls whether the point can project beyond the polygon's ends, or if it's clamped to the start/end points. ```APIDOC playdate.geometry.polygon:pointOnPolygon(distance, [extend]) Parameters: distance: number: The distance from the start of the polygon along its segments. extend: boolean (optional): If true, allows projection past ends; otherwise, constrains to start/end points. Returns: playdate.geometry.point: A point on the polygon's line segments. ``` -------------------------------- ### Pause a Timer Instance Source: https://sdk.play.date/2.7.4/index Pauses a running timer. Timers start automatically upon instantiation, so `start()` is not needed initially. ```APIDOC playdate.timer:pause() ``` -------------------------------- ### Playdate Launcher Card/Icon Animation Configuration (animation.txt) Source: https://sdk.play.date/2.7.4/index This snippet illustrates the `animation.txt` file format used within `card-highlighted/` or `icon-highlighted/` directories to control launcher animation playback. It allows specifying loop count, frame sequences, and an optional intro sequence, with support for repeating frames. ```Plain Text loopCount = 2 frames = 1, 2, 3x4, 4x2, 5, 5 introFrames = 1, 2x2, 3, 4x2 ``` -------------------------------- ### Create an Instance of a Lua Class Source: https://sdk.play.date/2.7.4/index Demonstrates the straightforward method of instantiating a class by calling the class name as if it were a function, passing any required arguments for its `init` function. ```Lua oakInstance = Oak(age, height) ``` -------------------------------- ### Playdate Game Metadata (pdxinfo) Configuration Sample Source: https://sdk.play.date/2.7.4/index This snippet shows a sample `pdxinfo` file, which defines essential metadata for a Playdate game such as its name, author, description, bundle ID, version, and paths to launcher assets. This file is automatically processed by the `pdc` compiler. ```Plain Text name=b360 author=Panic Inc. description=When all you have is a ton of bricks, everything looks like a paddle. bundleID=com.panic.b360 version=1.0 buildNumber=123 imagePath=path/to/launcher/assets launchSoundPath=path/to/launch/sound/file contentWarning=This game contains mild realistic violence and bloodshed. contentWarning2=This game contains flashing content that may not be suitable for photosensitive epilepsy. ``` -------------------------------- ### Get Playdate Geometry Polygon Bounding Box as Rect Source: https://sdk.play.date/2.7.4/index Calculates and returns the axis-aligned bounding box of the polygon as a `playdate.geometry.rect` object. This is a convenient way to get the bounding box encapsulated in a structured rectangle object. ```APIDOC playdate.geometry.polygon:getBoundsRect() Returns: playdate.geometry.rect: The bounding box as a rect object. ``` -------------------------------- ### Playdate Game Configuration Parameters Source: https://sdk.play.date/2.7.4/index Describes optional configuration parameters for Playdate games, including audio paths and content warnings that display upon game launch. ```APIDOC launchSoundPath: string (Optional) Description: Path to a short audio file to be played as the game launch animation is taking place. contentWarning: string (Optional) Description: A content warning that displays when the user launches your game for the first time. The user will have the option of backing out and not launching your game if they choose. contentWarning2: string (Optional) Description: A second content warning that displays on a second screen when the user launches your game for the first time. Note: Will only display if `contentWarning` is also specified. ``` -------------------------------- ### Playdate Sound Sample API Reference Source: https://sdk.play.date/2.7.4/index Documentation for the `playdate.sound.sample` object, which represents an individual sound sample, allowing for preloading and memory management. It provides methods for creating, loading, manipulating, and playing sound samples. ```APIDOC playdate.sound.sample new(path: string) path: Path to the sound file. Returns: A new playdate.sound.sample object, or nil and an error if loading fails. new(seconds: number, format: playdate.sound.kFormat = playdate.sound.kFormat16bitStereo) seconds: Buffer size in seconds. format: The format of the sample. Defaults to playdate.sound.kFormat16bitStereo. Returns: A new playdate.sound.sample object with a buffer of the specified size and format. getSubsample(startOffset: number, endOffset: number) startOffset: Start offset in frames. endOffset: End offset in frames. Returns: A new subsample containing a subrange of the given sample. load(path: string) path: Path to the sound file. Returns: nil if no file at path, otherwise loads sound data into existing buffer. decompress() Returns: true if successful, or false and an error message if decompression failed. Description: Decompresses ADPCM compressed sample data to 16-bit PCM. Increases memory footprint by 4x and does not affect quality, but is necessary for synth use or reverse playback. getSampleRate() Returns: The sample rate as an integer (e.g., 44100, 22050). getFormat() Returns: The format of the sample, one of: * playdate.sound.kFormat8bitMono * playdate.sound.kFormat8bitStereo * playdate.sound.kFormat16bitMono * playdate.sound.kFormat16bitStereo getLength() Returns: Two values: the length of available sample data and the size of the allocated buffer, both in seconds. play(repeatCount: number = 0, rate: number = 1.0) repeatCount: Number of times to repeat the sample (0 for infinite). rate: Playback rate. Description: Convenience function: Creates a new sampleplayer for the sample and passes the function arguments to its play function. playAt(when: number, vol: number = 1.0, rightvol: number = 1.0, rate: number = 1.0) when: Time to start playback. vol: Left channel volume (0.0 - 1.0). rightvol: Right channel volume (0.0 - 1.0). rate: Playback rate. Description: Convenience function: Creates a new sampleplayer for the sample and passes the function arguments to its playAt function. save(filename: string) filename: The file path to save the sample to. Description: Saves the sample to the given file. If filename has a .wav extension, it will be saved in WAV format (and be unreadable by Playdate sound functions), otherwise it will be saved in the Playdate pda format. ``` -------------------------------- ### Create a New Playdate Frame Timer Source: https://sdk.play.date/2.7.4/index Instantiates a new frame timer that runs for a specified duration. It can be configured with start and end values, and an optional easing function. By default, timers start immediately upon creation. ```APIDOC playdate.frameTimer.new(duration, [startValue, endValue, [easingFunction]]) duration: number - The number of frames for which the timer will run. startValue: number (optional) - The initial value for the timer's calculation. Defaults to 0. endValue: number (optional) - The final value for the timer's calculation. Defaults to 0. easingFunction: function(t, b, c, d) (optional) - A function used to calculate the timer's value. Defaults to a linear easing function. t: elapsed time b: beginning value c: change (endValue - startValue) d: duration Returns: playdate.frameTimer - A new frame timer instance. ``` -------------------------------- ### Basic Playdate Game Structure and Sprite Control in Lua Source: https://sdk.play.date/2.7.4/index This Lua code demonstrates the fundamental structure of a Playdate game, including essential library imports, sprite initialization, background drawing using a callback, and continuous game logic within the `playdate.update()` loop to handle d-pad input for player movement. It provides a complete, runnable example for a simple sprite-based game. ```Lua -- Name this file `main.lua`. Your game can use multiple source files if you wish -- (use the `import "myFilename"` command), but the simplest games can be written -- with just `main.lua`. -- You'll want to import these in just about every project you'll work on. import "CoreLibs/object" import "CoreLibs/graphics" import "CoreLibs/sprites" import "CoreLibs/timer" -- Declaring this "gfx" shorthand will make your life easier. Instead of having -- to preface all graphics calls with "playdate.graphics", just use "gfx." -- Performance will be slightly enhanced, too. -- NOTE: Because it's local, you'll have to do it in every .lua source file. local gfx = playdate.graphics -- Here's our player sprite declaration. We'll scope it to this file because -- several functions need to access it. local playerSprite = nil -- A function to set up our game environment. function myGameSetUp() -- Set up the player sprite. local playerImage = gfx.image.new("Images/playerImage") assert( playerImage ) -- make sure the image was where we thought playerSprite = gfx.sprite.new( playerImage ) playerSprite:moveTo( 200, 120 ) -- this is where the center of the sprite is placed; (200,120) is the center of the Playdate screen playerSprite:add() -- This is critical! -- We want an environment displayed behind our sprite. -- There are generally two ways to do this: -- 1) Use setBackgroundDrawingCallback() to draw a background image. (This is what we're doing below.) -- 2) Use a tilemap, assign it to a sprite with sprite:setTilemap(tilemap), -- and call :setZIndex() with some low number so the background stays behind -- your other sprites. local backgroundImage = gfx.image.new( "Images/background" ) assert( backgroundImage ) gfx.sprite.setBackgroundDrawingCallback( function( x, y, width, height ) -- x,y,width,height is the updated area in sprite-local coordinates -- The clip rect is already set to this area, so we don't need to set it ourselves backgroundImage:draw( 0, 0 ) end ) end -- Now we'll call the function above to configure our game. -- After this runs (it just runs once), nearly everything will be -- controlled by the OS calling `playdate.update()` 30 times a second. myGameSetUp() -- `playdate.update()` is the heart of every Playdate game. -- This function is called right before every frame is drawn onscreen. -- Use this function to poll input, run game logic, and move sprites. function playdate.update() -- Poll the d-pad and move our player accordingly. -- (There are multiple ways to read the d-pad; this is the simplest.) -- Note that it is possible for more than one of these directions -- to be pressed at once, if the user is pressing diagonally. if playdate.buttonIsPressed( playdate.kButtonUp ) then playerSprite:moveBy( 0, -2 ) end if playdate.buttonIsPressed( playdate.kButtonRight ) then playerSprite:moveBy( 2, 0 ) end if playdate.buttonIsPressed( playdate.kButtonDown ) then playerSprite:moveBy( 0, 2 ) end if playdate.buttonIsPressed( playdate.kButtonLeft ) then playerSprite:moveBy( -2, 0 ) end -- Call the functions below in playdate.update() to draw sprites and keep -- timers updated. (We aren't using timers in this example, but in most -- average-complexity games, you will.) gfx.sprite.update() playdate.timer.updateTimers() end ``` -------------------------------- ### Playdate Sound Sampleplayer API Reference Source: https://sdk.play.date/2.7.4/index Comprehensive API documentation for the playdate.sound.sampleplayer class, covering its instantiation, playback controls, volume management, loop and finish callbacks, sample manipulation, and status checks. ```APIDOC playdate.sound.sampleplayer Class Constructors: new(path: string) Returns: playdate.sound.sampleplayer | nil, error Description: Returns a new playdate.sound.sampleplayer object, with the sound data loaded in memory. If the sample can’t be loaded, the function returns nil and a second value containing the error. new(sample: playdate.sound.sample) Returns: playdate.sound.sampleplayer Description: Returns a new playdate.sound.sampleplayer object for playing the given sample. Methods: copy() Returns: playdate.sound.sampleplayer Description: Returns a new playdate.sound.sampleplayer with the same sample, volume, and rate as the given sampleplayer. play([repeatCount: number], [rate: number]) Description: Starts playing the sample. If repeatCount is greater than one, it loops the given number of times. If zero, it loops endlessly until it is stopped with playdate.sound.sampleplayer:stop(). If rate is set, the sample will be played at the given rate instead of the rate previous set with playdate.sound.sampleplayer.setRate(). playAt(when: number, [vol: number], [rightvol: number], [rate: number]) Returns: boolean Description: Schedules the sound for playing at device time when. If vol is specified, the sample will be played at level vol (with optional separate right channel volume rightvol), otherwise it plays at the volume set by playdate.sound.sampleplayer.setVolume(). Note that the when argument is an offset in the audio device’s time scale, as returned by playdate.sound.getCurrentTime(); it is NOT relative to the current time! If when is less than the current audio time, the sample is played immediately. If rate is set, the sample will be played at the given rate instead of the rate previously set with playdate.sound.sampleplayer.setRate(). Only one event can be queued at a time. If playAt() is called while another event is queued, it will overwrite it with the new values. The function returns true if the sample was successfully added to the sound channel, otherwise false (i.e., if the channel is full). setVolume(left: number, [right: number]) Description: Sets the playback volume (0.0 - 1.0) for left and right channels. If the optional right argument is omitted, it is the same as left. If the sampleplayer is currently playing using the default volume (that is, it wasn’t triggered by playAt() with a volume given) it also changes the volume of the playing sample. getVolume() Returns: number | (number, number) Description: Returns the playback volume for the sampleplayer, a single value for mono sources or a pair of values (left, right) for stereo sources. setLoopCallback(callback: function, [arg: any]) Description: Sets a function to be called every time the sample loops. The sample object is passed to this function as the first argument, and the optional arg argument is passed as the second. setPlayRange(start: number, end: number) Description: Sets the range of the sample to play. start and end are frame offsets from the beginning of the sample. setPaused(flag: boolean) Description: Pauses or resumes playback. isPlaying() Returns: boolean Description: Returns a boolean indicating whether the sample is playing. stop() Description: Stops playing the sample. setFinishCallback(func: function, [arg: any]) Description: Sets a function to be called when playback has completed. The sample object is passed to this function as the first argument, and the optional arg argument is passed as the second. setSample(sample: playdate.sound.sample) Description: Sets the sample to be played. getSample() Returns: playdate.sound.sample Description: Gets the sample to be played. getLength() Returns: number Description: Returns the length of the sampleplayer’s sample, in seconds. Length is not scaled by playback rate. setRate(rate: number) Description: Sets the playback rate for the sample. 1.0 is normal speed, 0.5 is down an octave, 2.0 is up an octave, etc. Sampleplayers can also play samples backwards, by setting a negative rate; note, however, this does not work with ADPCM-encoded files. getRate() Returns: number Description: Returns the playback rate for the sample. setRateMod(signal: any) Description: (No description provided in source text, but method signature is present.) ``` -------------------------------- ### Compiling Playdate Project with pdc Source: https://sdk.play.date/2.7.4/index Illustrates the basic usage of the 'pdc' command-line tool to compile a Playdate project. It shows how to specify the source directory and the desired output .pdx bundle name. ```Shell $ pdc MyGameSource MyGame.pdx ``` -------------------------------- ### Playdate TCP Connection Open Callback Source: https://sdk.play.date/2.7.4/index Example of opening a TCP connection and handling the connection success or failure using a callback function. The callback receives a boolean indicating connection status and an error string if it failed. ```Lua connection:open(function tcpConnectCallback(connected, err) if connected then print("connected!") else print("connection failed: "..err) end end) ``` -------------------------------- ### Lua Example: Simple Player Collision with moveWithCollisions Source: https://sdk.play.date/2.7.4/index Demonstrates how to use `playdate.graphics.sprite:moveWithCollisions` to handle player-obstacle collisions in a Playdate game. It sets up player and obstacle sprites, assigns tags, defines collision rectangles, and implements basic movement with collision detection. ```Lua -- You can copy and paste this example directly as your main.lua file to see it in action import "CoreLibs/graphics" import "CoreLibs/sprites" -- Creating a tags object, to keep track of tags more easily TAGS = { player = 1, obstacle = 2, coin = 3, powerUp = 4 } -- Creating a player sprite we can move around and collide things with local playerImage = playdate.graphics.image.new(20, 20) playdate.graphics.pushContext(playerImage) playdate.graphics.fillCircleInRect(0, 0, playerImage:getSize()) playdate.graphics.popContext() local playerSprite = playdate.graphics.sprite.new(playerImage) -- Setting a tag on the player, so we can check the tag to see if we're colliding against the player playerSprite:setTag(TAGS.player) playerSprite:moveTo(200, 120) -- Remember to set a collision rect, or this all doesn't work! playerSprite:setCollideRect(0, 0, playerSprite:getSize()) playerSprite:add() -- Creating an obstacle sprite we can collide against local obstacleImage = playdate.graphics.image.new(20, 20, playdate.graphics.kColorBlack) local obstacleSprite = playdate.graphics.sprite.new(obstacleImage) -- Setting a tag for the obstacle as well obstacleSprite:setTag(TAGS.obstacle) obstacleSprite:moveTo(300, 120) -- Can't forget this! obstacleSprite:setCollideRect(0, 0, obstacleSprite:getSize()) obstacleSprite:add() function playdate.update() playdate.graphics.sprite.update() -- Some simple movement code for the sake of demonstration local moveSpeed = 3 local goalX, goalY = playerSprite.x, playerSprite.y if playdate.buttonIsPressed(playdate.kButtonUp) then goalY -= moveSpeed elseif playdate.buttonIsPressed(playdate.kButtonDown) then goalY += moveSpeed elseif playdate.buttonIsPressed(playdate.kButtonLeft) then goalX -= moveSpeed elseif playdate.buttonIsPressed(playdate.kButtonRight) then goalX += moveSpeed end -- Remember to use :moveWithCollisions(), and not :moveTo() or :moveBy(), or collisions won't happen! ``` -------------------------------- ### Get Arc Length Source: https://sdk.play.date/2.7.4/index Returns the calculated length of the arc in pixels. ```APIDOC playdate.geometry.arc:length() Returns: number - The length of the arc. ``` -------------------------------- ### playdate.sound.synth Class Reference Source: https://sdk.play.date/2.7.4/index Comprehensive API documentation for the playdate.sound.synth object, including constructors, playback controls, envelope management, and modulation settings. ```APIDOC playdate.sound.synth Class: Description: Represents a synth object for playing waveforms or samples, with extensive controls for playback, envelopes, and modulation. Constructors: new([waveform]): Description: Returns a new synth object to play a waveform or wavetable. Parameters: waveform: (optional) The waveform to use. See playdate.sound.synth:setWaveform for values. Returns: A new synth object. new(sample, [sustainStart, sustainEnd]): Description: Returns a new synth object to play a Sample. Sample data must be uncompressed PCM, not ADPCM. An optional sustain region (measured in sample frames) defines a loop to play while the note is active. Parameters: sample: The Sample object to play. sustainStart: (optional) The start frame of the sustain loop. sustainEnd: (optional) The end frame of the sustain loop. If sustainStart > 0 and sustainEnd is omitted, it defaults to sample length. Returns: A new synth object. Methods: copy(): Description: Returns a copy of the given synth. Returns: A copy of the synth object. playNote(pitch, [volume, [length, [when]]]): Description: Plays a note with the current waveform or sample. Parameters: pitch: (number or string) The pitch value in Hertz (e.g., 261.63 for C4) or a note string (e.g., "Db3"). volume: (number, optional, default: 1) The volume, from 0 to 1. length: (number, optional) The length of the note in seconds. If omitted, plays until noteOff(). when: (number, optional) Seconds since the sound engine started. Defaults to current time. Returns: (boolean) True if successfully added to the sound channel, false otherwise. playMIDINote(note, [volume, [length, [when]]]): Description: Identical to playNote but uses a note name or MIDI note number. Parameters: note: (string or number) A note name (e.g., "C4") or MIDI note number (e.g., 60 for C4). Fractional values allowed for MIDI numbers. volume: (number, optional, default: 1) The volume, from 0 to 1. length: (number, optional) The length of the note in seconds. If omitted, plays until noteOff(). when: (number, optional) Seconds since the sound engine started. Defaults to current time. Returns: (boolean) True if successfully added to the sound channel, false otherwise. noteOff(): Description: Releases the note, if one is playing. The note will continue to be voiced through the release section of the synth’s envelope. stop(): Description: Stops the synth immediately, without playing the release part of the envelope. isPlaying(): Description: Returns true if the synth is still playing, including the release phase of the envelope. Returns: (boolean) True if the synth is playing. setAmplitudeMod(signal): Description: Sets the signal to use as the amplitude modulator. Set to nil to clear the modulator. Parameters: signal: (playdate.sound.signal or nil) The signal to use for amplitude modulation. setADSR(attack, decay, sustain, release): Description: Sets the attack time, decay time, sustain level, and release time for the sound envelope. Parameters: attack: (number) The attack time in seconds. decay: (number) The decay time in seconds. sustain: (number) The sustain level (0.0 to 1.0). release: (number) The release time in seconds. setAttack(time): Description: Sets the attack time, in seconds. Parameters: time: (number) The attack time in seconds. setDecay(time): Description: Sets the decay time, in seconds. Parameters: time: (number) The decay time in seconds. setSustain(level): Description: Sets the sustain level, as a proportion of the total level (0.0 to 1.0). Parameters: level: (number) The sustain level (0.0 to 1.0). setRelease(time): Description: Sets the release time, in seconds. Parameters: time: (number) The release time in seconds. clearEnvelope(): Description: Clears the synth’s envelope settings. setEnvelopeCurvature(amount): Description: Smoothly changes the envelope’s shape from linear (amount=0) to exponential (amount=1). Parameters: amount: (number) The curvature amount (0 to 1). getEnvelope(): Description: Returns the synth’s envelope as a playdate.sound.envelope object. Returns: (playdate.sound.envelope) The synth's envelope object. setFinishCallback(function): Description: Sets a function to be called when the synth stops playing. Parameters: function: (function) The callback function. setFrequencyMod(signal): Description: Sets the signal to use as the frequency modulator. Set to nil to clear the modulator. Parameters: signal: (playdate.sound.signal or nil) The signal to use for frequency modulation. setLegato(flag): Description: Sets whether to use legato phrasing for the synth. If the legato flag is set and a new note starts while a previous note is still playing, the synth’s envelope remains in the sustain phase instead of starting a new attack. Parameters: flag: (boolean) True to enable legato, false otherwise. setVolume(left, [right]): Description: Sets the synth volume. If a single value is passed in, sets both left side and right side volume to the given value. If two values are given, volumes are set separately. Volume values are between 0.0 and 1.0. Parameters: left: (number) The volume for the left channel (0.0 to 1.0). right: (number, optional) The volume for the right channel (0.0 to 1.0). getVolume(): Description: Returns the current volume for the synth, a single value for mono sources or a pair of values (left, right) for stereo sources. Volume values are between 0.0 and 1.0. Returns: (number or tuple) The volume (single value for mono, pair for stereo). setWaveform(waveform): Description: Sets the waveform for the synth. Parameters: waveform: The waveform to set. ``` -------------------------------- ### Playdate Gridview: Get Selection Source: https://sdk.play.date/2.7.4/index Returns the currently-selected cell's position. ```APIDOC playdate.ui.gridview:getSelection() Returns: section: number, row: number, column: number - The currently-selected cell as section, row, column. ``` -------------------------------- ### Get All Nodes in Graph Source: https://sdk.play.date/2.7.4/index Returns an array containing all nodes currently in the graph. ```APIDOC playdate.pathfinder.graph:allNodes() -> table ``` -------------------------------- ### playdate.network.http Class Reference Source: https://sdk.play.date/2.7.4/index Detailed API documentation for the `playdate.network.http` class, including methods for network connection management, HTTP request handling, and response processing. ```APIDOC playdate.network.http Class: - new(server: string, [port: number], [usessl: boolean], [reason: string]): playdate.network.http Description: Returns a new HTTP object for connecting to the given server. The default port is 443 if usessl is true, otherwise 80. The default for usessl is false. If permission is not given, the game pauses to ask the user. Cannot be called at load time or from input handlers due to coroutine yield. - requestAccess([server: string], [port: number], [usessl: boolean], [reason: string]): void Description: Proactively requests network access. Can be used to request access for specific servers, all HTTP servers (empty server), or subdomains. Uses a coroutine yield, so must be called from a playdate.update() context. - close(): void Description: Closes the HTTP connection. The connection may be used again for another request. - setKeepAlive(flag: boolean): void Description: If 'flag' is true, this causes the HTTP request to include a 'Connection: keep-alive' header. - setByteRange(from: number, to: number): void Description: Adds a 'Range: bytes' header to the HTTP request. - setConnectTimeout(seconds: number): void Description: Sets the length of time (in seconds) to wait for the connection to the server to be made. - get(path: string, [headers: string | string[] | table]): boolean, string? Description: Opens the connection (if not already open) and sends a GET request to the specified path with additional headers if specified. Returns true if the request is successfully queued, or false and an error string on error. Headers: Can be a string (newlines between headers), an array of strings, or a table of key/value pairs. - post(path: string, [headers: string | string[] | table], data: any): boolean, string? Description: Opens the connection (if not already open) and sends a POST request to the specified path with optional headers and provided data. Returns true if the request is successfully queued, or false and an error string on error. Headers: Can be a string (newlines between headers), an array of strings, or a table of key/value pairs. If there is only one argument after 'path', it is assumed to be 'data'. - getError(): string | nil Description: Returns a text description of the last error on the connection, or nil if no error occurred. - getProgress(): number, number Description: Returns two values: the number of bytes already read from the connection and the total bytes the server plans to send. - getBytesAvailable(): number Description: Returns the number of bytes currently available for reading from the connection. - setReadTimeout(seconds: number): void Description: Sets the length of time, in seconds, 'playdate.network.http:read()' will wait for incoming data before returning. The default value is one second. - setReadBufferSize(bytes: number): void Description: Sets the size of the connection’s read buffer. - read([length: number]): string Description: On success, returns up to 'length' bytes (maximum 64KB) from the connection. If 'length' is more than the number of bytes available, the function will wait for more data up to the length of time set by 'setReadTimeout()' (default one second). - getResponseStatus(): number Description: Returns the HTTP status response code, if the request response headers have been received and parsed. - getResponseHeaders(): table | nil Description: Returns a table containing the key/value pairs in the HTTP response headers, or nil if no headers were received. - setRequestCallback(callback: function): void Description: Sets a function to be called when response data is available. - setHeadersReadCallback(callback: function): void Description: Sets a function to be called after the connection has parsed the headers from the server response. At this point, 'getResponseStatus()' and 'getProgress()' can be used to query the status and size of the response, and 'get()'/'post()' can queue another request if 'connection:setKeepAlive(true)' was set. ``` -------------------------------- ### Get Current Stroke Location Source: https://sdk.play.date/2.7.4/index Retrieves the currently set stroke position. ```APIDOC playdate.graphics.getStrokeLocation() Returns: The current stroke location constant. ``` -------------------------------- ### Get Current Line Width Source: https://sdk.play.date/2.7.4/index Retrieves the currently set line width. ```APIDOC playdate.graphics.getLineWidth() Returns: The current line width. ``` -------------------------------- ### playdate.datastore Source: https://sdk.play.date/2.7.4/index Easy writing and reading of data. ```APIDOC playdate.datastore Purpose: Easy writing and reading of data. ``` -------------------------------- ### Get Background Color Source: https://sdk.play.date/2.7.4/index Retrieves the color currently set for drawing the background. ```APIDOC playdate.graphics.getBackgroundColor() Returns: playdate.graphics.color - The current background color. ```