### Example of State Replacement on Save Load (Twee) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-state-sessions-and-saving.md Demonstrates how loading a save replaces the current game state. Changes made after a save are lost when that save is loaded, as shown by a variable not present in the older save becoming undefined. ```twee :: StoryInit <> :: Start $$x is <> $x <> undefined <> ``` ```twee :: StoryInit <> <> :: Start $$x is <> $x <> undefined <> $$y is <> $y <> undefined <> ``` -------------------------------- ### SugarCube Tagged Stylesheet Examples (CSS) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/css.md Demonstrates how to apply styles to passages based on their tags using CSS. It shows examples using both [data-tags~="..."] attribute selectors on the html or body element, and class selectors on the body element. These selectors allow for conditional styling of backgrounds, text color, and link colors. ```css /* Using [data-tags~="…"] attribute selectors on */ html[data-tags~="forest"] { background-image: url(forest-bg.jpg); } html[data-tags~="forest"] .passage { color: darkgreen; } html[data-tags~="forest"] a { color: green; } html[data-tags~="forest"] a:hover { color: lime; } /* Using [data-tags~="…"] attribute selectors on */ body[data-tags~="forest"] { background-image: url(forest-bg.jpg); } body[data-tags~="forest"] .passage { color: darkgreen; } body[data-tags~="forest"] a { color: green; } body[data-tags~="forest"] a:hover { color: lime; } /* Using class selectors on */ body.forest { background-image: url(forest-bg.jpg); } body.forest .passage { color: darkgreen; } body.forest a { color: green; } body.forest a:hover { color: lime; } ``` -------------------------------- ### Implementing Container Macros Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Shows the transition from Harlowe's hook-based syntax to SugarCube's opening and closing tag structure for conditional logic. ```Harlowe (if: $var is 1)[ The variable is 1. ] ``` ```SugarCube <> The variable is 1. <> ``` -------------------------------- ### Create New Character Instance in SugarCube Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-non-generic-object-types.md This SugarCube macro example demonstrates how to create a new instance of the custom 'Character' class, initializing it with specific properties like name, race, and stats. This is used after defining the 'Character' class with compatible serialization methods. ```sugarcube <> ``` -------------------------------- ### Converting Link Macros Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Illustrates how to replicate Harlowe link functionality using SugarCube's linkreplace, link, and passage navigation macros. ```Harlowe (link: "Hey there.")[Hay is for horses.] (link-repeat: "Get some money")[(set: $cash to it + 1)] (link-goto: "Move on", "next passage") ``` ```SugarCube <>Hay is for horses.<> <><><> <><> <><> ``` -------------------------------- ### Demonstrate State Moment Capture in Twee Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-state-sessions-and-saving.md A Twee example illustrating how story variables are captured in the history only upon passage navigation. It demonstrates that variable changes made via links do not persist in the save state until a new moment is created. ```twee :: one passage <> [[another passage]] :: another passage <> <> <> ``` -------------------------------- ### Get Auto Save Details by Index (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Fetches the descriptor object for an auto save at a specific index using `Save.browser.auto.get(index)`. If the auto save does not exist, it returns `null`. The example logs the retrieved descriptor. ```javascript console.log(`Descriptor of the auto save at index ${index}:`, Save.browser.auto.get(index)); ``` -------------------------------- ### Passing Expressions to Macros Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Demonstrates how to pass expressions to SugarCube macros using backquotes, contrasting it with Harlowe's comma-separated argument style. ```Harlowe (link-goto: "Go somewhere else", (either: "this passage", "that passage", "the other passage")) ``` ```SugarCube <><> ``` -------------------------------- ### Create and initialize a Dialog Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-dialog.md Prepares a new dialog instance with optional title and CSS class names. Supports method chaining for complex dialog setups. ```javascript Dialog.create(); Dialog.create('Character Sheet'); Dialog.create(null, 'charsheet'); Dialog.create('Character Sheet', 'charsheet'); Dialog .create('Character Sheet', 'charsheet') .wikiPassage('Player Character') .open(); ``` -------------------------------- ### Using Arrays: Harlowe vs. SugarCube Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Demonstrates the syntax for creating and manipulating arrays in both Harlowe and SugarCube. SugarCube utilizes standard JavaScript array methods. ```Harlowe (set: $array to (a:)) (set: $array to it + (a: "something")) (if: $array contains "something")[…] ``` ```SugarCube <> <> <>…<> ``` -------------------------------- ### GET SimpleAudio.tracks.get Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio.md Retrieves an AudioTrack instance by ID. ```APIDOC ## GET SimpleAudio.tracks.get ### Description Returns the AudioTrack instance for the given ID, or null if not found. ### Method GET ### Endpoint SimpleAudio.tracks.get(trackId) ### Parameters #### Path Parameters - **trackId** (string) - Required - The ID of the track to retrieve. ### Response #### Success Response (200) - **track** (AudioTrack|null) - The requested track object. ``` -------------------------------- ### Using Datamaps: Harlowe vs. SugarCube Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Illustrates how to create and modify datamaps (similar to JavaScript Maps) in Harlowe and SugarCube. SugarCube uses the JavaScript `Map` object. ```Harlowe (set: $map to (dm: "key", "value")) (set: $map's key to "another value") (if: $map contains key)[…] ``` ```SugarCube <> <> <>…<> ``` -------------------------------- ### Implement Function-based Constructor with Discrete Parameters Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-non-generic-object-types.md A legacy approach using function prototypes to define a constructor with discrete arguments. Includes manual property assignment and serialization logic. ```javascript window.Character = function (name, race, st, dx, iq, ht, hp) { this.name = name || '(none)'; this.race = race || '(none)'; this.st = st || 10; this.dx = dx || 10; this.iq = iq || 10; this.ht = ht || 10; this.hp = hp || 10; }; Character.prototype.clone = function () { return new Character(this.name, this.race, this.st, this.dx, this.iq, this.ht, this.hp); }; Character.prototype.toJSON = function () { return Serial.createReviver(String.format( 'new Character({0},{1},{2},{3},{4},{5},{6})', JSON.stringify(this.name), JSON.stringify(this.race), JSON.stringify(this.st), JSON.stringify(this.dx), JSON.stringify(this.iq), JSON.stringify(this.ht), JSON.stringify(this.hp) )); }; ``` -------------------------------- ### Implement Class-based Constructor with Discrete Parameters Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-non-generic-object-types.md Defines a Character class using ES6 syntax with discrete parameters. Includes methods for cloning the instance and serializing it for save-game compatibility. ```javascript window.Character = class Character { constructor(name, race, st, dx, iq, ht, hp) { this.name = name ?? '(none)'; this.race = race ?? '(none)'; this.st = st ?? 10; this.dx = dx ?? 10; this.iq = iq ?? 10; this.ht = ht ?? 10; this.hp = hp ?? 10; } clone() { return new this.constructor(this.name, this.race, this.st, this.dx, this.iq, this.ht, this.hp); } toJSON() { return Serial.createReviver(String.format( 'new {0}({1},{2},{3},{4},{5},{6},{7})', this.constructor.name, JSON.stringify(this.name), JSON.stringify(this.race), JSON.stringify(this.st), JSON.stringify(this.dx), JSON.stringify(this.iq), JSON.stringify(this.ht), JSON.stringify(this.hp) )); } }; ``` -------------------------------- ### Get Milliseconds Since Render Macro Example Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/functions.md Provides an example of using the time() function within a TwineScript macro to determine the time elapsed since the current passage was rendered. This is used to create time-sensitive link behaviors. ```twine /* Links that vary based on the time. */ In the darkness, something wicked this way comes. Quickly! Do you <> <> /* The player clicked the link in under 10s, so they escape. */ <> <> /* Elsewise, they're eaten by a grue. */ <> <> <> or [[stand your ground|Eaten by a grue]]? ``` -------------------------------- ### Play Audio with AudioRunner Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiorunner.md Initiates playback of selected audio tracks. If browser policy prevents immediate playback, it queues the tracks to start upon user interaction. ```javascript someTracks.playWhenAllowed(); ``` -------------------------------- ### Control SugarCube-2 Playlists with the <> macro Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Demonstrates how to initialize a playlist using <> and control it using the <> macro. The examples cover common operations like playing, pausing, volume adjustment, and fading. ```SugarCube-2 <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> ``` -------------------------------- ### Using Generic Objects: SugarCube Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Shows how to create and manipulate generic JavaScript objects in SugarCube, which can be an alternative to Maps for certain use cases. Uses standard JavaScript object property access. ```SugarCube <> <> <>…<> ``` -------------------------------- ### Get Last Element with last() in SugarCube Macros Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/methods.md The last() method returns the final element of an array without modifying the original array. This is a convenient way to access the last item. The example demonstrates its usage within SugarCube macros. ```text <> <> /* Returns 'Pumpkin' */ ``` -------------------------------- ### SugarCube 2 Image Markup Examples Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/markup.md Demonstrates various syntaxes for SugarCube 2's image markup, including plain text, TwineScript expressions, and combinations with Text, Link, and Setter components. Assumes predefined variables $src, $go, and $show. ```TwineScript [img[home.png]] [img[$src]] ``` ```TwineScript [img[Go home|home.png]] [img[$show|$src]] ``` ```TwineScript [img[home.png][Home]] [img[$src][$go]] ``` ```TwineScript [img[Go home|home.png][Home]] [img[$show|$src][$go]] ``` ```TwineScript [img[home.png][Home][$done to true]] [img[$src][$go][$done to true]] ``` ```TwineScript [img[Go home|home.png][Home][$done to true]] [img[$show|$src][$go][$done to true]] ``` -------------------------------- ### Implement return links in menus Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-tips.md Demonstrates how to create navigation links that return the player to the previously stored passage. Using the <> macro is recommended in Twine 2 to avoid accidental passage creation. ```sugarcube /* Using link markup */ [[Return|$return]] /* Using <> macro (separate argument form) */ <><> ``` -------------------------------- ### Get Current Turn Count (Macros/JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/functions.md Provides examples for retrieving the total number of played turns in the game using the `turns()` function. This function is useful for tracking game progression or displaying turn-based information to the player. It can be used in both macro and JavaScript contexts. ```macro <> ``` ```macro <<= 'This is turn #' + turns()>> ``` ```javascript // Record the turn count. let turnCount = turns(); ``` -------------------------------- ### Manage Master Audio Settings in SugarCube Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Provides examples for controlling global audio states such as volume, muting, and visibility-based muting. It also includes commands for forcing the loading or unloading of all audio assets. ```SugarCube <> <> <> <> <> <> <> <> ``` -------------------------------- ### Get All Auto Save Entries (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Retrieves an array of objects, each containing the index and descriptor information for all available auto saves using `Save.browser.auto.entries()`. It iterates through the returned array to log details of each auto save. ```javascript Save.browser.auto.entries().forEach(function (entry) { console.log(`Descriptor of the auto save at index ${entry.index}:`, entry.info); }); ``` -------------------------------- ### Demonstrating Initialization Code Execution During Restart (Twee) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-state-sessions-and-saving.md Illustrates that initialization code, such as setting a global variable like `setup.y`, executes even when a save state is loaded or a playthrough session is restored. This is because such variables are not part of the save state itself and persist across loads. ```twee :: StoryInit <> <> :: Start $$x is <> $x <> undefined <> setup.y is <> <<= setup.y>> <> undefined <> ``` -------------------------------- ### Check for Element Inclusion with includes in SugarCube Macros and JavaScript Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/methods.md The includes method determines whether an array includes a certain value among its entries, returning true or false as appropriate. It can also take an optional position argument to start the search from. Examples are shown for SugarCube macros and JavaScript. ```text <> <> /* Returns true */ <> /* Returns true */ ``` ```javascript let pies = ['Blueberry', 'Cherry', 'Cream', 'Pecan', 'Pumpkin']; let result = pies.includes('Cherry'); // Returns true let result = pies.includes('Pecan', 3); // Returns true ``` -------------------------------- ### Fade in selected tracks using AudioRunner.fadeIn Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiorunner.md Starts playback and fades tracks from a starting volume to full volume (1) over a specified duration. ```JavaScript // Fade the selected tracks in from volume 0 over 5 seconds. someTracks.fadeIn(5, 0); ``` -------------------------------- ### POST SimpleAudio.groups.add Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio.md Creates a group of tracks for batch operations. ```APIDOC ## POST SimpleAudio.groups.add ### Description Adds a new audio group. Group IDs must begin with a colon. ### Method POST ### Endpoint SimpleAudio.groups.add(groupId, ...trackIds) ### Parameters #### Request Body - **groupId** (string) - Required - The ID of the group (must start with ':'). - **trackIds** (string|Array) - Required - List of track IDs to include in the group. ### Request Example SimpleAudio.groups.add(":ui", "ui_beep", "ui_boop"); ### Response #### Success Response (200) - **status** (string) - Confirmation of group creation. ``` -------------------------------- ### Configure AudioList shuffle state Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiolist.md Gets or sets the random playback shuffle state for the playlist. Returns a boolean when getting the state, or the AudioList instance for chaining when setting it. ```javascript // Get the playlist's current shuffle state. var isShuffled = aList.shuffle(); // Enable shuffling of the playlist. aList.shuffle(true); // Disable shuffling of the playlist. aList.shuffle(false); ``` -------------------------------- ### Navigation: Harlowe's (goto:) vs. SugarCube's <> Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Compares Harlowe's (goto:) macro, which terminates passage rendering, with SugarCube's <> macro, which does not terminate rendering, potentially leading to side effects if not handled carefully. SugarCube's <> can also accept link markup. ```Harlowe :: some passage (set: $count to 0) (goto: "next") (set: $count to it + 1) :: next $count ``` -------------------------------- ### Dialog.create() Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-dialog.md Prepares the dialog for use, optionally setting a title and CSS classes. Returns a reference to the Dialog object for chaining. ```APIDOC ## Dialog.create([title [, classNames]]) ### Description Prepares the dialog for use. Returns a reference to the `Dialog` object for chaining. ### Method `Dialog.create([title [, classNames]])` ### Parameters #### Path Parameters * **`title`** (optional, string) - The title of the dialog. * **`classNames`** (optional, string) - The space-separated list of classes to add to the dialog. ### Returns * **Dialog** - The `Dialog` object for chaining. ### Request Example ##### Basic usage ```javascript Dialog.create(); ``` ##### With the optional `title` parameter ```javascript Dialog.create('Character Sheet'); ``` ##### With the optional `classNames` parameter ```javascript Dialog.create(null, 'charsheet'); ``` ##### With both optional parameters ```javascript Dialog.create('Character Sheet', 'charsheet'); ``` ##### Making use of chaining ```javascript Dialog .create('Character Sheet', 'charsheet') .wikiPassage('Player Character') .open(); ``` ``` -------------------------------- ### Fade In AudioList Playback Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiolist.md Starts playlist playback and fades the current track from a specified volume to maximum (1) over a given duration. An optional starting volume can be provided. Returns a Promise. ```javascript // Fade the playlist in from volume 0 over 5 seconds. aList.fadeIn(5, 0); ``` -------------------------------- ### Getting Active Passage Title - SugarCube 2 State API Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-state.md Returns the title of the passage associated with the active (present) moment. This is a direct way to get the name of the current screen. ```javascript State.passage ``` -------------------------------- ### User Input: Harlowe's (prompt:) vs. SugarCube's <> Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Illustrates how to handle user input, contrasting Harlowe's (prompt:) macro with SugarCube's <> macro. SugarCube's <> uses a receiver variable and cannot be nested within a <> macro. ```Harlowe (set: $name to (prompt: "What is your name?", "Frank")) ``` -------------------------------- ### Get or Set Master Volume with SimpleAudio Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio.md Manages the master volume level for all audio. Can be used to get the current volume or set a new volume level between 0 (silent) and 1 (loudest). ```javascript // Get the current master volume level. var currentMasterVolume = SimpleAudio.volume(); // Set the master volume level to 75%. SimpleAudio.volume(0.75); ``` -------------------------------- ### Get or Set AudioTrack Mute State Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Controls the volume mute state of an AudioTrack. It returns a boolean when getting the state and accepts a boolean when setting the state, returning the AudioTrack instance for chaining. ```javascript // Get the track's current volume mute state. var isMuted = aTrack.mute(); // Mute the track's volume. aTrack.mute(true); // Unmute the track's volume. aTrack.mute(false); ``` -------------------------------- ### Navigation: Harlowe's (goto:) vs. SugarCube's <> Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Compares Harlowe's (goto:) macro, which terminates passage rendering, with SugarCube's <> macro, which does not terminate rendering, potentially leading to side effects if not handled carefully. SugarCube's <> can also accept link markup. ```SugarCube :: some passage <> <> <> :: next $count /* 1 */ ``` ```SugarCube <> ``` -------------------------------- ### Get or Set AudioTrack Loop State Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Manages the looping playback state of an AudioTrack. When used to get the state, it returns a boolean. When used to set the state, it accepts a boolean and returns the AudioTrack instance for chaining. ```javascript // Get the track's current loop state. var isLooped = aTrack.loop(); // Loop the track. aTrack.loop(true); // Unloop the track. aTrack.loop(false); ``` -------------------------------- ### Fade In AudioTrack Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Starts playback and fades the audio track in from a specified volume level to the maximum (1) over a given duration. Optionally takes a starting volume; defaults to the current volume. Introduced in v2.28.0, returns a Promise since v2.29.0. ```javascript // Fade the track in from volume 0 over 5 seconds. aTrack.fadeIn(5, 0); ``` -------------------------------- ### Synchronize audio loading with waitforaudio Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Displays a loading screen until all registered audio tracks are ready. This is essential for ensuring assets are cached before gameplay begins. ```SugarCube <> <> <> ``` -------------------------------- ### Wiki Content Formatting (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-macrocontext.md Shows how to use the wiki method to format plain text content into HTML. It supports single or multiple content sources for wikification. ```javascript this.wiki('Who //are// you?'); // Outputs "Who are you?" ``` ```javascript this.wiki( 'Goodnight…', 'sweet prince.' ); // Outputs "Goodnight…sweet prince." ``` -------------------------------- ### Save.browser.auto.size Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Gets the total number of existing browser auto saves. ```APIDOC ## Save.browser.auto.size ### Description The integer `number` count of existing browser auto saves. ### Method GET ### Endpoint /Save/browser/auto/size ### Parameters #### Path Parameters *None* #### Query Parameters *None* ### Request Example ```javascript console.log(`There are currently ${Save.browser.auto.size} browser auto saves`); ``` ### Response #### Success Response (200) - **size** (integer) - The count of existing browser auto saves. #### Response Example ```json { "size": 3 } ``` ``` -------------------------------- ### Dynamic Content Updates with <> and <> Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Demonstrates how to create dynamic content containers that can be updated on demand using the <> macro and triggered by <> commands, including support for tags to filter specific updates. ```TwineScript <> ''Money:'' <>$money<> <> <> <> <> ''Foo:'' <><<= ["fee", "fie", "foe", "fum"].random()>><> <> <> <> ``` -------------------------------- ### Save.browser.size Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Gets the total number of existing browser saves (auto and slot). ```APIDOC ## Save.browser.size ### Description The integer `number` count of existing browser saves. ### Method GET ### Endpoint /Save/browser/size ### Parameters #### Path Parameters *None* #### Query Parameters *None* ### Request Example ```javascript console.log(`There are currently ${Save.browser.size} browser saves`); ``` ### Response #### Success Response (200) - **size** (integer) - The count of existing browser saves. #### Response Example ```json { "size": 5 } ``` ``` -------------------------------- ### Create Interactive Links Source: https://context7.com/tmedwards/sugarcube-2/llms.txt Demonstrates the use of the <> macro to trigger code execution, navigate between passages, and update UI elements dynamically. ```TwineScript < <> <>You picked up the sword.<> <> < < <> Strength: $pcStr < <> <>$pcStr<> <> ``` -------------------------------- ### Fade AudioTrack Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Starts playback and fades the audio track between specified volume levels over a given duration. Optionally takes a starting volume; defaults to the current volume. The pauseOnFadeToZero setting can affect behavior when fading to silence. Introduced in v2.28.0, returns a Promise since v2.29.0. ```javascript // Fade the track from volume 0 to 1 over 6 seconds. aTrack.fade(6, 1, 0); ``` -------------------------------- ### Create Basic Links in SugarCube Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/markup.md Demonstrates the syntax for creating simple navigation links using passage names or TwineScript variables. These links direct the user to the specified passage or URL. ```SugarCube [[Grocery]] [[$go]] ``` -------------------------------- ### Get and Set AudioTrack Volume (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md This snippet demonstrates how to get the current volume of an audio track and how to set it to a specific level using the AudioTrack.volume() method. The method accepts an optional numeric level between 0 and 1. When setting the volume, it returns the AudioTrack instance for chaining. ```javascript // Get the track's current volume level. var trackVolume = aTrack.volume(); // Set the track's volume level to 75%. aTrack.volume(0.75); ``` -------------------------------- ### User Input: Harlowe's (prompt:) vs. SugarCube's <> Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-harlowe-to-sugarcube.md Illustrates how to handle user input, contrasting Harlowe's (prompt:) macro with SugarCube's <> macro. SugarCube's <> uses a receiver variable and cannot be nested within a <> macro. ```SugarCube ``` -------------------------------- ### Fade Out AudioTrack Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Starts playback and fades the audio track out from a specified volume level to silence (0) over a given duration. Optionally takes a starting volume; defaults to the current volume. The pauseOnFadeToZero setting can affect behavior when fading to silence. Introduced in v2.28.0, returns a Promise since v2.29.0. ```javascript // Fade the track out from volume 1 over 8 seconds. aTrack.fadeOut(8, 1); ``` -------------------------------- ### Create and use a container widget Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Demonstrates defining a container widget that wraps content using the _contents special variable and accepts arguments for dynamic attributes. ```SugarCube <>

_contents

<
> <>Tweego is a pathway to many abilities some consider to be… unnatural.<> ``` -------------------------------- ### GET State.random() Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-state.md Retrieves a pseudo-random decimal number between 0 and 1. ```APIDOC ## GET State.random() ### Description Returns a pseudo-random decimal number (floating-point) in the range 0 (inclusive) up to, but not including, 1 (exclusive). If a seedable PRNG is initialized, it returns deterministic results. ### Method GET ### Endpoint State.random() ### Parameters #### Path Parameters - None ### Response #### Success Response (200) - **value** (number) - A floating-point number in the range [0, 1). ### Response Example 0.482910384756201 ``` -------------------------------- ### Load audio tracks with SimpleAudio Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio.md Methods to force the loading of registered audio tracks. SimpleAudio.load() triggers immediate loading, while SimpleAudio.loadWithScreen() displays a loading overlay until tracks are ready. ```javascript SimpleAudio.load(); SimpleAudio.loadWithScreen(); ``` -------------------------------- ### Implement Icon Reference IDs Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-icon-font.md Demonstrates the required syntax for using icon hexadecimal reference IDs in different programming contexts. Each format ensures the icon is correctly interpreted by the browser or runtime environment. ```JavaScript "\uf004" ``` ```CSS \f004 ``` ```HTML  ``` -------------------------------- ### turns() - Get Turn Count Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/functions.md Retrieves the total number of played turns currently in effect. ```APIDOC ## GET /turns ### Description Returns the total number of played turns currently in effect. Future or undone moments are not included. ### Method GET ### Endpoint /turns ### Parameters #### Path Parameters *None* #### Query Parameters *None* ### Request Example ```javascript turns(); ``` ### Response #### Success Response (200) - **turnCount** (integer) - The total number of played turns. #### Response Example ```json { "turnCount": 15 } ``` ``` -------------------------------- ### Set Starting Passage Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-config.md Defines the name of the initial passage that the story will display upon loading. ```javascript Config.passages.start = 'That Other Starting Passage'; ``` -------------------------------- ### Implement Function-based Constructor with Configuration Object Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-non-generic-object-types.md Uses legacy function syntax to accept a single configuration object. It automatically maps properties from the config object to the instance using SugarCube's clone utility. ```javascript window.Character = function Character(config) { this.name = '(none)'; this.race = '(none)'; this.st = 10; this.dx = 10; this.iq = 10; this.ht = 10; this.hp = 10; Object.keys(config).forEach(function (pn) { this[pn] = clone(config[pn]); }, this); }; Character.prototype.clone = function () { return new Character(this); }; Character.prototype.toJSON = function () { var ownData = {}; Object.keys(this).forEach(function (pn) { ownData[pn] = clone(this[pn]); }, this); return Serial.createReviver('new Character($ReviveData$)', ownData); }; ``` -------------------------------- ### AudioTrack Time and Metadata Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Methods for getting or setting the current playback time and retrieving remaining duration. ```APIDOC ## [METHOD] .time([seconds]) ### Description Gets or sets the track's current time in seconds. When setting, returns the AudioTrack instance. ### Parameters #### Arguments - **seconds** (number) - Optional - The time to set in seconds. ### Response #### Success Response (200) - **time** (number) - Returns current time if no argument provided. ## [METHOD] .remaining() ### Description Returns how much remains of the track's total playtime in seconds. ``` -------------------------------- ### HTML/CSS: Web Page Structure and Styling Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/templates/html/intro.html This snippet defines the structure and styling of a web page using HTML and CSS. HTML provides the content, and CSS handles the presentation. The input is content and design requirements, and the output is a visually rendered web page. ```html Page Title

Hello World

``` ```css h1 { color: blue; } ``` -------------------------------- ### Array.prototype.count Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/methods.md Returns the number of times a specified member appears in an array, optionally starting from a given position. ```APIDOC ## Array.prototype.count ### Description Returns the number of times that the given member was found within the array, starting the search at `position`. ### Method `count(needle [, position])` ### Parameters #### Parameters - **`needle`** (any) - Required - The member to count. - **`position`** (integer number) - Optional - The zero-based index at which to begin searching for `needle`. Defaults to `0`. ### Returns An integer number representing the count of the `needle` in the array. ### Request Example ```javascript let fruits = ['Apples', 'Oranges', 'Plums', 'Oranges']; let countOranges = fruits.count('Oranges'); // Returns 2 let countOrangesFromSecond = fruits.count('Oranges', 2); // Returns 1 ``` ### Response #### Success Response (200) - **count** (integer number) - The number of times the `needle` was found. ``` -------------------------------- ### Play Audio with AudioRunner Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiorunner.md Starts or resumes playback of the selected audio tracks. This method requires no parameters and was introduced in v2.28.0. ```javascript someTracks.play(); ``` -------------------------------- ### Config API Deprecations Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/guides/guide-code-updates.md Overview of deprecated configuration settings and their recommended replacements. ```APIDOC ## Config API Changes ### Description List of deprecated settings within the Config object and their modern alternatives. ### Deprecated Settings - **Config.macros.ifAssignError**: Deprecated. Use `Config.enableOptionalDebugging`. - **Config.passages.descriptions**: Deprecated. Use `Config.saves.descriptions`. - **Config.saves.autoload**: Deprecated. Use `Save.browser.continue()` if replacing UI. - **Config.saves.autosave**: Deprecated. Use `Config.saves.maxAutoSaves` and `Config.saves.isAllowed`. - **Config.saves.slots**: Deprecated. Use `Config.saves.maxSlotSaves`. - **Config.saves.tryDiskOnMobile**: Deprecated. Unconditionally enabled. ``` -------------------------------- ### Control audio playback Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-simpleaudio-audiotrack.md Methods to manage the playback state of an audio track, including starting, pausing, stopping, and unloading data. ```javascript aTrack.pause(); // Basic play aTrack.play(); // Play with promise handling aTrack.play() .then(function () { console.log('The track is playing.'); }) .catch(function (problem) { console.warn('There was a problem with playback: ' + problem); }); aTrack.playWhenAllowed(); someTrack.stop(); aTrack.unload(); ``` -------------------------------- ### Get Browser Save Count (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Retrieves the integer count of existing browser saves. This can be used to check if any saves are present before attempting to load or delete them. ```javascript console.log(`There are currently ${Save.browser.size} browser saves`); ``` ```javascript if (Save.browser.size > 0) { /* Browser saves exist. */ } ``` ```javascript if (Save.browser.size === 0) { /* No browser saves exist. */ } ``` -------------------------------- ### Prepend content on link click Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md The <> macro creates a single-use link that, when clicked, prepends the contained text or elements to the link itself. It supports optional transition effects. ```SugarCube-2 You see a <>GIANT <>. ``` ```SugarCube-2 I <>do not <> lemons. ``` -------------------------------- ### Count Substring Occurrences in Strings Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/methods.md Counts the number of times a substring appears in a string, starting from an optional position. This method is case-sensitive. ```twinescript <> <> /* Returns 4 */ <> /* Returns 2 */ ``` ```javascript let text = 'How now, brown cow.'; let result = text.count('ow'); // Returns 4 let result = text.count('ow', 8); // Returns 2 ``` -------------------------------- ### Add On-Load Handler with Save Type Switching (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Provides an example of adding an 'on-load' handler that uses a switch statement to process different types of save objects (Auto, Base64, Disk, Slot) based on their 'type' property. This allows for type-specific save data processing before loading. ```javascript Save.onLoad.add(function (save) { switch (save.type) { case Save.Type.Auto: { /* code to process an auto save object before it's loaded */ break; } case Save.Type.Base64: { /* code to process a base64 save object before it's loaded */ break; } case Save.Type.Disk: { /* code to process a disk save object before it's loaded */ break; } case Save.Type.Slot: { /* code to process a slot save object before it's loaded */ break; } } }); ``` -------------------------------- ### Get Browser Auto Save Count (JavaScript) Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/api/api-save.md Retrieves the integer count of existing browser auto saves. This is useful for managing or checking the status of automatic saves. ```javascript console.log(`There are currently ${Save.browser.auto.size} browser auto saves`); ``` ```javascript if (Save.browser.auto.size > 0) { /* Browser auto saves exist. */ } ``` ```javascript if (Save.browser.auto.size === 0) { /* No browser auto saves exist. */ } ``` -------------------------------- ### Create Audio Playlists with `createplaylist` in SugarCube 2 Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Describes the `<>` macro for collecting cached audio tracks into a playlist. Playlists are managed via `<>` children within the macro. It is recommended to set up playlists in the `StoryInit` special passage. ```javascript → Example of creating a playlist (best done in StoryInit) <> <> <> <> ``` -------------------------------- ### Control Audio Playback with Groups and Tracks Source: https://github.com/tmedwards/sugarcube-2/blob/develop/docs/core/macros.md Demonstrates how to manipulate audio playback state using predefined group selectors and specific track IDs. These examples show how to perform bulk operations on multiple tracks or target individual audio files for playback, pausing, and volume adjustments. ```SugarCube 2 <