### Game Start and Restart Functionality
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Manages the starting and restarting of the game. The 'start' function handles initial setup, including checking for a starting passage and loading saved states or initiating a new game. The 'restart' function reloads the entire application.
```javascript
start:{value:function(){if(_state===States.Init){if(null==Config.passages.start)throw new Error("starting passage not selected");if(!Story.has(Config.passages.start))throw new Error('starting passage ("'.concat(Config.passages.start,'") not found'));if(_state=States.Idle,document.documentElement.focus(),State.restore())engineShow();else{var autoloadType=_typeof(Config.saves._internal_autoload_);"string"===autoloadType?"prompt"===Config.saves._internal_autoload_&&(UI.buildAutoload(),Dialog.open()):new Promise((function(resolve,reject){if(Save.browser.hasContinue()&&("boolean"===autoloadType&&Config.saves._internal_autoload_ ||"function"===autoloadType&&Config.saves._internal_autoload_()))return resolve();reject()})).then((function(){return Save.browser.continue()})).catch((function(){enginePlay(Config.passages.start)}))}}},restart:{value:function(){LoadScreen.show(),window.scroll(0,0),State.reset(),triggerEvent(":enginerestart"),window.location.reload()}}
```
--------------------------------
### Initialization and Startup Logic
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/crafting.html
Manages the initial setup and startup sequence of the game engine. This includes running user-defined initialization passages, handling save data autoloading, and starting the game by playing the designated starting passage.
```javascript
if (_state === States.Init && (Story.getInits().forEach((function(passage) {
try {
var debugBuffer = Wikifier.wikifyEval(passage.text);
if (Config.debug) {
var debugView = new DebugView(document.createDocumentFragment(), "special", "".concat(passage.name, " [init-tagged]"), "".concat(passage.name, " [init-tagged]"));
debugView.modes({ hidden: !0 }), debugView.append(debugBuffer), _initDebugViews.push(debugView.output)
}
} catch (ex) {
console.error(ex), Alert.error("".concat(passage.name, " [init-tagged]"), getErrorMessage(ex))
}
})), Story.has("StoryInit"))) try {
var debugBuffer = Wikifier.wikifyEval(Story.get("StoryInit").text);
if (Config.debug) {
var debugView = new DebugView(document.createDocumentFragment(), "special", "StoryInit", "StoryInit");
debugView.modes({ hidden: !0 }), debugView.append(debugBuffer), _initDebugViews.push(debugView.output)
}
} catch (ex) {
console.error(ex), Alert.error("StoryInit", getErrorMessage(ex))
}
if (_state === States.Init) {
if (null == Config.passages.start) throw new Error("starting passage not selected");
if (!Story.has(Config.passages.start)) throw new Error('starting passage ("'.concat(Config.passages.start, '") not found'));
if (_state = States.Idle, document.documentElement.focus(), State.restore()) engineShow();
else {
var autoloadType = _typeof(Config.saves._internal_autoload);
"string" === autoloadType ? "prompt" === Config.saves._internal_autoload && (UI.buildAutoload(), Dialog.open()) : new Promise((function(resolve, reject) {
if (Save.browser.hasContinue() && ("boolean" === autoloadType && Config.saves._internal_autoload || "function" === autoloadType && Config.saves._internal_autoload())) return resolve();
reject()
})).then((function() {
return Save.browser.continue()
})).catch((function() {
enginePlay(Config.passages.start)
}))
}
}
```
--------------------------------
### Key Items Inventory Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Recipes.md
Demonstrates the creation and usage of simple key-style items. This recipe shows an example of a player finding an important item that can be used to advance in the game.
```twee
recipes/keys/index.twee
```
--------------------------------
### Equipment System Inventory Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Recipes.md
Shows how to create a basic equipment system for players. This recipe covers the fundamental aspects of equipping and managing items that provide player enhancements.
```twee
recipes/equipment/index.twee
```
--------------------------------
### JavaScript Settings Initialization Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Demonstrates how to initialize and configure various settings using the provided JavaScript API. Includes examples for range, toggle, and list settings with custom validation and callbacks.
```javascript
var Types = {
Header: 0,
List: 1,
Range: 2,
Toggle: 3,
Value: 4
};
// Example of adding a range setting
addRange('volume', {
min: 0,
max: 100,
step: 1,
default: 50,
desc: 'Master volume level',
onChange: function(data) {
console.log('Volume changed to:', data.value);
}
});
// Example of adding a toggle setting
addToggle('darkMode', {
default: false,
desc: 'Enable dark mode',
onChange: function(data) {
document.body.classList.toggle('dark-mode', data.value);
}
});
// Example of adding a list setting
addList('theme', {
default: 'light',
values: ['light', 'dark', 'system'],
desc: 'UI theme selection'
});
// Initialize all settings
init();
// Get a setting value
var currentVolume = getValue('volume');
// Set a setting value
setValue('darkMode', true);
// Reset a specific setting
reset('volume');
// Reset all settings
reset();
```
--------------------------------
### SugarCube Initialization and Setup
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/collectibles.html
Handles the initialization of SugarCube, including storage, UI elements, engine, and event listeners. It manages the loading screen and ensures the story is ready before starting.
```javascript
Object.defineProperty(window,"SugarCube",{
value:Object.seal(Object.assign(Object.create(null),{
Browser:Browser,
Config:Config,
Dialog:Dialog,
Engine:Engine,
Fullscreen:Fullscreen,
Has:Has,
L10n:L10n,
Macro:Macro,
Passage:Passage,
Save:Save,
Scripting:Scripting,
Setting:Setting,
SimpleAudio:SimpleAudio,
State:State,
Story:Story,
UI:UI,
UIBar:UIBar,
DebugBar:DebugBar,
Util:Util,
Visibility:Visibility,
Wikifier:Wikifier,
session:session,
settings:settings,
setup:setup,
storage:storage,
version:version
}))
}),
jQuery((function(){
var lockId=LoadScreen.lock();
LoadScreen.init();
document.normalize&&document.normalize();
new Promise((function(resolve){
Story.init();
try{
SugarCube.storage=storage=SimpleStore.create(Story.id,!0);
SugarCube.session=session=SimpleStore.create(Story.id,!1)
}catch(ex){
throw new Error(L10n.get("warningNoStorage"))
}
Dialog.init();
UIBar.init();
Engine.init();
Outliner.init();
Engine.runUserScripts();
L10n.init();
session.has("rcWarn")||"cookie"!==storage.name||
(session.set("rcWarn",1),window.alert(L10n.get("warningNoWebStorage")))
Save.init();
Setting.init();
Macro.init();
DebugBar.init();
var $window=jQuery(window),
vpReadyId=setInterval((function(){
$window.width()&&LoadScreen.size<=1&&
(clearInterval(vpReadyId),resolve())
}),Engine.DOM_DELAY)
})).then((function(){
Engine.runUserInit();
UIBar.start();
Engine.start();
DebugBar.start();
triggerEvent(":storyready");
setTimeout((function(){
return LoadScreen.unlock(lockId)
}),2*Engine.DOM_DELAY)
})).catch((function(ex){
return console.error(ex),LoadScreen.clear(),Alert.fatal(null,ex.message,ex)
}))
}))(window,window.document,jQuery);
```
--------------------------------
### SugarCube Initialization and Setup
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Handles the initialization and setup of the SugarCube environment. This includes setting up storage, session management, UI elements, engine, and user scripts. It also manages the loading screen and ensures the DOM is ready before proceeding.
```javascript
jQuery((function(){var lockId=LoadScreen.lock();LoadScreen.init(),document.normalize&&document.normalize(),new Promise((function(resolve){Story.init();try{SugarCube.storage=storage=SimpleStore.create(Story.id,!0),SugarCube.session=session=SimpleStore.create(Story.id,!1)}catch(ex){throw new Error(L10n.get("warningNoStorage"))}Dialog.init(),UIBar.init(),Engine.init(),Outliner.init(),Engine.runUserScripts(),L10n.init(),session.has("rcWarn")||"cookie"!==storage.name||
(session.set("rcWarn",1),window.alert(L10n.get("warningNoWebStorage"))),Save.init(),Setting.init(),Macro.init(),DebugBar.init();var $window=jQuery(window),vpReadyId=setInterval((function(){$window.width()&&LoadScreen.size<=1&&(clearInterval(vpReadyId),resolve())}),Engine.DOM_DELAY)})).then((function(){Engine.runUserInit(),UIBar.start(),Engine.start(),DebugBar.start(),triggerEvent(":storyready"),setTimeout((function(){return LoadScreen.unlock(lockId)}),2*Engine.DOM_DELAY)})).catch((function(ex){return console.error(ex),LoadScreen.clear(),Alert.fatal(null,ex.message,ex)}))}))})(window,window.document,jQuery);}
```
--------------------------------
### Shop System Inventory Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Recipes.md
Shows how to handle basic buying and selling mechanics within a game. This recipe outlines a simple shop system for player transactions.
```twee
recipes/shop/index.twee
```
--------------------------------
### Engine Start Function in JavaScript
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
This JavaScript code snippet defines the `start` function for a game engine. It checks for a starting passage and handles autoloading of saved games. If autoloading fails, it starts the game with the configured starting passage.
```JavaScript
if(_state===States.Init){if(null==Config.passages.start)throw new Error("starting passage not selected");if(!Story.has(Config.passages.start))throw new Error('starting passage ("'.concat(Config.passages.start,'") not found'));if(_state=States.Idle,document.documentElement.focus(),State.restore())engineShow();else{var autoloadType=_typeof(Config.saves._internal_autoload_);"string"===autoloadType?"prompt"===Config.saves._internal_autoload_&&(UI.buildAutoload(),Dialog.open()):new Promise((function(resolve,reject){if(Save.browser.hasContinue()&&("boolean"===autoloadType&&Config.saves._internal_autoload_||"function"===autoloadType&&Config.saves._internal_autoload_()))return resolve();reject()})).then((function(){return Save.browser.continue()})).catch((function(){enginePlay(Config.passages.start)}))}}
```
--------------------------------
### UI Bar Start and Feature Integration
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Handles the initial setup and behavior when the UI bar starts. This includes conditionally stowing the bar based on window width, setting up a toggle for stowing, configuring history controls, and dynamically updating various story elements and menu items based on game state and available passages.
```javascript
start: {
value: function() {
if (_$uiBar) {
// Stow bar initially based on config
(Config.ui.stowBarInitially === true || jQuery(window).width() <= Config.ui.stowBarInitially) && stow(!0),
// Toggle functionality
jQuery("#ui-bar-toggle").ariaClick({ label: L10n.get("uiBarLabelToggle") }, (function() { return _$uiBar.toggleClass("stowed") })),
// History controls
Config.history.controls ? (
jQuery("#history-backward").ariaDisabled(State.length < 2).ariaClick({ label: L10n.get("uiBarLabelBackward") }, (function() { return Engine.backward() })),
Story.filter((function(passage) { return passage.tags.includes("bookmark") })).length > 0 ? jQuery("#history-jumpto").ariaClick({ label: L10n.get("uiBarLabelJumpto") }, (function() { return UI.jumpto() })) : jQuery("#history-jumpto").remove(),
jQuery("#history-forward").ariaDisabled(State.length === State.size).ariaClick({ label: L10n.get("uiBarLabelForward") }, (function() { return Engine.forward() }))
) : jQuery("#ui-bar-history").remove();
// Dynamic content updates for story elements and menus
var storyTitleHandler, addUiUpdateHandler = function(handler) {
return jQuery(document)[Config.ui.updateStoryElements ? "on" : "one"](":uiupdate".concat(".ui-bar"), handler)
};
var addUpdaterOrRemove = function(selector, passageName) {
var $el = jQuery(selector);
Story.has(passageName) ? addUiUpdateHandler((function() {
var frag = document.createDocumentFragment();
new Wikifier(frag, Story.get(passageName).processText().trim()),
$el.empty().append(frag)
})) : $el.remove()
};
// Update story title, banner, subtitle, author, caption
storyTitleHandler = Story.has("StoryDisplayTitle") ? function() { return setDisplayTitle(Story.get("StoryDisplayTitle").processText()) } : function() { return setDisplayTitle(Story.name, !0) },
addUiUpdateHandler(storyTitleHandler),
addUpdaterOrRemove("#story-banner", "StoryBanner"),
addUpdaterOrRemove("#story-subtitle", "StorySubtitle"),
addUpdaterOrRemove("#story-author", "StoryAuthor"),
addUpdaterOrRemove("#story-caption", "StoryCaption");
// Update story menu
if (Story.has("StoryMenu")) {
var $menuStory = jQuery("#menu-story");
jQuery(document).on(":uiupdate".concat(".ui-bar"), (function() {
try {
var frag = UI.assembleLinkList("StoryMenu", document.createDocumentFragment());
$menuStory.empty().append(frag)
} catch (ex) {
console.error(ex), Alert.error("StoryMenu", ex.message)
}
}))
} else jQuery("#menu-story").remove();
// Continue, Saves, Settings, Restart, Share menu items
Save.browser.size > 0 ? (jQuery("#menu-item-continue a").ariaClick({ role: "button" }, (function(ev) {
ev.preventDefault(), Save.browser.continue().then((function() {
jQuery(document).off(".menu-item-continue"), jQuery("#menu-item-continue").remove(), Engine.show()
}), (function(ex) { return UI.alert("".concat(ex.message.toUpperFirst(), ".
").concat(L10n.get("textAborting"), ".")) }))
})).text(L10n.get("continueTitle")), jQuery(document).on(":passagestart.menu-item-continue", (function() {
State.turns > 1 && (jQuery(document).off(".menu-item-continue"), jQuery("#menu-item-continue").remove())
}))) : jQuery("#menu-item-continue").remove(),
jQuery("#menu-item-saves a").ariaClick({ role: "button" }, (function(ev) { ev.preventDefault(), UI.buildSaves(), Dialog.open() })).text(L10n.get("savesTitle")),
Setting.isEmpty() ? jQuery("#menu-item-settings").remove() : jQuery("#menu-item-settings a").ariaClick({ role: "button" }, (function(ev) { ev.preventDefault(), UI.buildSettings(), Dialog.open() })).text(L10n.get("settingsTitle")),
jQuery("#menu-item-restart a").ariaClick({ role: "button" }, (function(ev) { ev.preventDefault(), UI.buildRestart(), Dialog.open() })).text(L10n.get("restartTitle")),
Story.has("StoryShare") ? jQuery("#menu-item-share a").ariaClick({ role: "button" }, (function(ev) { ev.preventDefault(), UI.buildShare(), Dialog.open() })).text(L10n.get("shareTitle")) : jQuery("#menu-item-share").remove()
}
}
}
```
--------------------------------
### Python API Interaction: Basic GET Request
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Shows a basic example of making an HTTP GET request using the `requests` library in Python. This is a common pattern for fetching data from web APIs.
```Python
import requests
url = 'https://api.example.com/data'
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes
data = response.json()
print(data)
except requests.exceptions.RequestException as e:
print(f'An error occurred: {e}')
```
--------------------------------
### Collectibles Inventory Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Recipes.md
Demonstrates how to create basic collectible items and use events to automate rewards for players collecting them. This recipe focuses on rewarding player exploration.
```twee
recipes/collectibles/index.twee
```
--------------------------------
### Python API Interaction: JSON Placeholder Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Provides a practical example of interacting with a public API (JSONPlaceholder) to fetch and display user data. This demonstrates common API patterns in a real-world scenario.
```Python
import requests
url = 'https://jsonplaceholder.typicode.com/users/1'
try:
response = requests.get(url)
response.raise_for_status()
user_data = response.json()
print(f"User Name: {user_data['name']}")
print(f"User Email: {user_data['email']}")
except requests.exceptions.RequestException as e:
print(f'An error occurred: {e}')
```
--------------------------------
### Crafting and Gathering Inventory Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Recipes.md
Illustrates a very basic crafting and gathering style game mechanic. This recipe provides a foundation for implementing item creation and resource collection.
```twee
recipes/crafting/index.twee
```
--------------------------------
### Take Items from Container
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Uses the `<>` macro to display items from a container inventory and allow players to pick them up, adding them to their own inventory.
```javascript
<>
```
--------------------------------
### Inventory with Inspect and All Flags
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Adds 'inspect' and 'all' flags, allowing players to view item descriptions and potentially perform actions on all items.
```javascript
<>
```
--------------------------------
### SugarCube Initialization and Setup
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/shop.html
This code block details the initialization process for the SugarCube framework. It includes setting up storage (both persistent and session-based), initializing UI components like Dialog and UIBar, the main Engine, and the Outliner. It also handles user script execution, localization, warnings for non-web storage, save/setting/macro initialization, and the debug bar. The process is wrapped in a Promise to manage asynchronous operations and includes error handling for critical failures.
```javascript
Object.defineProperty(window,"SugarCube",{
value:Object.seal(Object.assign(Object.create(null),{
Browser:Browser,
Config:Config,
Dialog:Dialog,
Engine:Engine,
Fullscreen:Fullscreen,
Has:Has,
L10n:L10n,
Macro:Macro,
Passage:Passage,
Save:Save,
Scripting:Scripting,
Setting:Setting,
SimpleAudio:SimpleAudio,
State:State,
Story:Story,
UI:UI,
UIBar:UIBar,
DebugBar:DebugBar,
Util:Util,
Visibility:Visibility,
Wikifier:Wikifier,
session:session,
settings:settings,
setup:setup,
storage:storage,
version:version
}))
}),
jQuery((function(){
var lockId=LoadScreen.lock();
LoadScreen.init();
document.normalize&&document.normalize();
new Promise((function(resolve){
Story.init();
try{
SugarCube.storage=storage=SimpleStore.create(Story.id,!0);
SugarCube.session=session=SimpleStore.create(Story.id,!1)
}
catch(ex){
throw new Error(L10n.get("warningNoStorage"))
}
Dialog.init();
UIBar.init();
Engine.init();
Outliner.init();
Engine.runUserScripts();
L10n.init();
session.has("rcWarn")||"cookie"!==storage.name||
(session.set("rcWarn",1),window.alert(L10n.get("warningNoWebStorage")))
Save.init();
Setting.init();
Macro.init();
DebugBar.init();
var $window=jQuery(window),
vpReadyId=setInterval((function(){
$window.width()&&LoadScreen.size<=1&&
(clearInterval(vpReadyId),resolve())
}),Engine.DOM_DELAY)
})).then((function(){
Engine.runUserInit();
UIBar.start();
Engine.start();
DebugBar.start();
triggerEvent(":storyready");
setTimeout((function(){
return LoadScreen.unlock(lockId)
}),2*Engine.DOM_DELAY)
})).catch((function(ex){
return console.error(ex),LoadScreen.clear(),Alert.fatal(null,ex.message,ex)
}))
}))(window,window.document,jQuery);
}
```
--------------------------------
### Get the count of a specific item
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Returns the exact number of a specified item currently in the inventory. This can be used for direct quantity checks or calculations.
```twine
<= 3>>
You have all three keycards!
<>
```
--------------------------------
### Get number of unique items in inventory
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Retrieves the count of distinct item types in the inventory, ignoring stacks or duplicates. This property reflects the variety of items.
```twine
<<= $box.uniqueLength>> /* 3 */
```
--------------------------------
### Web Storage Adapter Initialization and Usage
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Demonstrates how to check for Web Storage availability, initialize the adapter, and perform basic operations like setting and getting items. It includes error handling for quota exceptions.
```javascript
var store;
try {
store = window[storeId];
var val = "_sc_".concat(String(Date.now()));
store.setItem(val, val);
var result = store.getItem(val) === val;
return store.removeItem(val), result;
} catch (ex) {
return store && 0 !== store.length && isQuotaDOMException(ex);
}
```
--------------------------------
### Get total number of items in inventory
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Retrieves the total count of all items in the inventory, including duplicates and stacked items. This property reflects the overall inventory size.
```twine
<>
<>
<<= $box.length>> /* 15 */
```
--------------------------------
### SugarCube Initialization and Event Handling
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
This snippet details the initialization process of the SugarCube framework, including setting up storage, session management, UI components, and running user scripts. It also covers the story readiness event and loading screen management.
```javascript
jQuery((function(){
var lockId = LoadScreen.lock();
LoadScreen.init();
document.normalize && document.normalize();
new Promise((function(resolve) {
Story.init();
try {
SugarCube.storage = storage = SimpleStore.create(Story.id, !0);
SugarCube.session = session = SimpleStore.create(Story.id, !1);
} catch (ex) {
throw new Error(L10n.get("warningNoStorage"));
}
Dialog.init();
UIBar.init();
Engine.init();
Outliner.init();
Engine.runUserScripts();
L10n.init();
session.has("rcWarn") || "cookie" !== storage.name || (session.set("rcWarn", 1), window.alert(L10n.get("warningNoWebStorage")));
Save.init();
Setting.init();
Macro.init();
DebugBar.init();
var $window = jQuery(window);
var vpReadyId = setInterval((function() {
$window.width() && LoadScreen.size <= 1 && (clearInterval(vpReadyId), resolve());
}), Engine.DOM_DELAY);
})).then((function() {
Engine.runUserInit();
UIBar.start();
Engine.start();
DebugBar.start();
triggerEvent(":storyready");
setTimeout((function() {
return LoadScreen.unlock(lockId);
}), 2 * Engine.DOM_DELAY);
})).catch((function(ex) {
return console.error(ex), LoadScreen.clear(), Alert.fatal(null, ex.message, ex);
}));
}))(window, window.document, jQuery);
```
--------------------------------
### Create Item with Tags
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Shows how to create an item with specified tags. Tags are strings used to add metadata to items. Requires the Item object.
```javascript
<- >
<>
<>\
An old, rusty key with a skull shape on it. Spoooooky.\
<
>
<>
```
--------------------------------
### Build and Demo Scripts
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/README.md
Provides instructions for building the project's JavaScript and CSS files, and for generating a demo HTML file. Requires Node.js and npm. The build process outputs to the 'dist/' directory, and the demo generation requires Tweego.
```bash
npm install
npm run build
npm run demo
```
--------------------------------
### Potions Inventory Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Recipes.md
Provides examples of basic consumable items, such as potions that can restore the player's HP. This recipe focuses on implementing items with immediate effects.
```twee
recipes/potions/index.twee
```
--------------------------------
### UI Bar Start and Configuration
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Initializes the UI bar's behavior on startup, including conditionally stowing it based on screen width and configuring navigation controls. It also sets up click handlers for the toggle button and history navigation.
```javascript
start:{value:function(){if(_$uiBar){("boolean"==typeof Config.ui.stowBarInitially?Config.ui.stowBarInitially:jQuery(window).width()<=Config.ui.stowBarInitially)&&stow(!0),jQuery("#ui-bar-toggle").ariaClick({label:L10n.get("uiBarLabelToggle")},(function(){return _$uiBar.toggleClass("stowed")})),Config.history.controls?(jQuery("#history-backward").ariaDisabled(State.length<2).ariaClick({label:L10n.get("uiBarLabelBackward")},(function(){return Engine.backward()})),Story.filter((function(passage){return passage.tags.includes("bookmark")})).length>0?jQuery("#history-jumpto").ariaClick({label:L10n.get("uiBarLabelJumpto")},(function(){return UI.jumpto()})):jQuery("#history-jumpto").remove(),jQuery("#history-forward").ariaDisabled(State.length===State.size).ariaClick({label:L10n.get("uiBarLabelForward")},(function(){return Engine.forward()}))):jQuery("#ui-bar-history").remove();var storyTitleHandler,addUiUpdateHandler=function(handler){return jQuery(document)[Config.ui.updateStoryElements?"on":"one"](":uiupdate".concat(".ui-bar"),handler)},addUpdaterOrRemove=function(selector,passageName){var $el=jQuery(selector);Story.has(passageName)?addUiUpdateHandler((function(){var frag=document.createDocumentFragment();new Wikifier(frag,Story.get(pas
```
--------------------------------
### Passage Start Configuration
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/collectibles.html
Sets the starting passage of the story. The provided value must be a string or null/undefined.
```javascript
Config.passages.start = 'Introduction';
```
--------------------------------
### Application Initialization and User Script Execution
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Handles the initial setup of the application, including DOM manipulation for the story interface, processing special passages like 'StoryInterface', and executing user-defined scripts and styles.
```javascript
return Object.preventExtensions(Object.create(null,{States:{value:States},DOM_DELAY:{get:function(){return DOM_DELAY}},init:{value:function(){if(\_state===States.Init){jQuery("#init-no-js,#init-lacking").remove();var $main=jQuery(''),markup=Story.has("StoryInterface")&&Story.get("StoryInterface").text.trim();if(markup){if(Config.ui.updateStoryElements=!1,UIBar.destroy(),jQuery(document.head).find("#style-core-display").remove(),$main.append(markup),$main.find("#story").length>0)throw new Error('element with ID "story" found within "StoryInterface" special passage');var $passages=$main.find("#passages");if(0===$passages.length)throw new Error('no element with ID "passages" found within "StoryInterface" special passage');$passages.empty().not("[aria-live]").attr("aria-live","polite").end();var $dataInitPassages=$main.find("[data-init-passage]"),$dataPassages=$main.find("[data-passage]");$dataInitPassages.each((function(i,el){if("passages"===el.id)throw new Error('"StoryInterface" element <'.concat(el.nodeName.toLowerCase(),' id="passages"> must not contain a "data-init-passage" content attribute'));var passage=el.getAttribute("data-init-passage").trim();if(el.hasAttribute("data-passage"))throw new Error('"StoryInterface" element <'.concat(el.nodeName.toLowerCase(),' data-init-passage="').concat(passage,'"> must not contain a "data-passage" content attribute'));if(null!==el.firstElementChild)throw new Error('"StoryInterface" element <'.concat(el.nodeName.toLowerCase(),' data-init-passage="').concat(passage,'"> contains child elements'));Story.has(passage)&&jQuery(document).one(":uiupdate".concat(".engine"),(function(){var frag=document.createDocumentFragment();new Wikifier(frag,Story.get(passage).processText().trim()),jQuery(el).empty().append(frag)}))})),$dataPassages.each((function(i,el){if("passages"===el.id)throw new Error('"StoryInterface" element <'.concat(el.nodeName.toLowerCase(),' id="passages"> must not contain a "data-passage" content attribute'));var passage=el.getAttribute("data-passage").trim();if(null!==el.firstElementChild)throw new Error('"StoryInterface" element <'.concat(el.nodeName.toLowerCase(),' data-passage="').concat(passage,'"> contains child elements'));Story.has(passage)&&jQuery(document).on(":uiupdate".concat(".engine"),(function(){var frag=document.createDocumentFragment();new Wikifier(frag,Story.get(passage).processText().trim()),jQuery(el).empty().append(frag)}))}))}else $main.append('');$main.insertBefore("body>script#script-sugarcube")}},runUserScripts:{value:function(){var storyStyle;\_state===States.Init&&(storyStyle=document.createElement("style"),new StyleWrapper(storyStyle).add(Story.getStyles().map((function(style){return style.text.trim()})).join("\n")),jQuery(storyStyle).appendTo(document.head).attr({id:"style-story",type:"text/css"}),Story.getScripts().forEach((function(script){try{Scripting.evalJavaScript(script.text)}catch(ex){console.error(ex),Alert.error(script.name,getErrorMessage(ex))}})),Story.getWidgets().forEach((function(widget){try{W
```
--------------------------------
### Get ToString Tag
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Determines the internal [[Class]] property of an object, providing a more robust way to get the type than typeof.
```javascript
var getToStringTag=(toString=Object.prototype.toString,slice=String.prototype.slice,"[object Object]"===toString.call(new Map)?function(O){return O instanceof Map?"Map":O instanceof Set?"Set":slice.call(toString.call(O),8,-1)}:function(O){return slice.call(toString.call(O),8,-1)}),toString,slice;
```
--------------------------------
### Python HTTP Requests (GET)
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/collectibles.html
This snippet demonstrates how to make an HTTP GET request in Python using the `requests` library.
```python
import requests
url = "https://api.example.com/data"
try:
response = requests.get(url)
response.raise_for_status() # Raise an exception for bad status codes
data = response.json()
print("GET Request Successful:")
print(data)
except requests.exceptions.RequestException as e:
print(f"Error making GET request: {e}")
```
--------------------------------
### AudioRunner Initialization and Core Operations
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/shop.html
Demonstrates the initialization of the AudioRunner class with a list of track IDs and the core methods for loading and unloading audio tracks.
```javascript
AudioRunner(list)
- Constructor for the AudioRunner class.
- Parameters:
- list: A Set of track IDs or another AudioRunner instance.
- Throws TypeError if the list parameter is not a Set or AudioRunner instance.
load()
- Loads all audio tracks associated with the AudioRunner instance.
unload()
- Unloads all audio tracks associated with the AudioRunner instance.
play()
- Starts playback of the audio tracks.
```
--------------------------------
### JavaScript Macro Handler Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/collectibles.html
Illustrates a basic JavaScript macro handler function. This example shows how a macro's logic can be defined and executed.
```javascript
var Macro = function() {
var _macros = {},
_tags = {},
_validNameRe = new RegExp("^(?:" + Patterns.macroName + ")");
function macrosHas(name) { return Object.hasOwn(_macros, name); }
function tagsRegister(parent, bodyTags) {
if (!parent) throw new Error("no parent specified");
var endTags = ["/".concat(parent), "end".concat(parent)],
allTags = [].concat(endTags, Array.isArray(bodyTags) ? bodyTags : []);
for (var i = 0; i < allTags.length; ++i) {
var tag = allTags[i];
if (macrosHas(tag)) throw new Error("cannot register tag for an existing macro");
tagsHas(tag) ? _tags[tag].includes(parent) || (_tags[tag].push(parent), _tags[tag].sort()) : _tags[tag] = [parent];
}
}
function tagsUnregister(parent) {
if (!parent) throw new Error("no parent specified");
Object.keys(_tags).forEach(function(tag) {
var i = _tags[tag].indexOf(parent);
-1 !== i && (1 === _tags[tag].length ? delete _tags[tag] : _tags[tag].splice(i, 1));
});
}
function tagsHas(name) { return Object.hasOwn(_tags, name); }
return Object.preventExtensions(Object.create(null, {
add: {
value: function macrosAdd(name, def) {
if (Array.isArray(name)) name.forEach(function(name) { return macrosAdd(name, def); });
else {
if (!_validNameRe.test(name)) throw new Error('invalid macro name "'.concat(name, '"'));
if (macrosHas(name)) throw new Error("cannot clobber existing macro <<".concat(name, ">> "));
if (tagsHas(name)) throw new Error("cannot clobber child tag <<".concat(name, ">> of parent macro ").concat(1 === _tags[name].length ? "" : "s <<").concat(_tags[name].join(" >>, << "), ">>"));
try {
if ("object" === _typeof(def)) _macros[name] = Object.assign(Object.create(null), def, { _MACRO_API: !0 });
else {
if (!macrosHas(def)) throw new Error("cannot create alias of nonexistent macro <<".concat(def, ">> "));
_macros[name] = Object.create(_macros[def], { _ALIAS_OF: { enumerable: !0, value: def } });
}
Object.defineProperty(_macros, name, { writable: !1 });
} catch (ex) {
throw "TypeError" === ex.name ? new Error("cannot clobber protected macro <<".concat(name, ">> ")) : new Error("unknown error when attempting to add macro <<".concat(name, ">>: [").concat(ex.name, " ] ").concat(ex.message));
}
if (void 0 !== _macros[name].tags)
if (null == _macros[name].tags) tagsRegister(name);
else {
if (!Array.isArray(_macros[name].tags)) throw new Error('bad value for "tags" property of macro <<'.concat(name, ">> "));
tagsRegister(name, _macros[name].tags);
}
}
}
},
delete: {
value: function macrosDelete(name) {
if (Array.isArray(name)) name.forEach(function(name) { return macrosDelete(name); });
else if (macrosHas(name)) {
void 0 !== _macros[name].tags && tagsUnregister(name);
try {
Object.defineProperty(_macros, name, { writable: !0 }), delete _macros[name];
} catch (ex) {
throw new Error("unknown error removing macro <<".concat(name, ">>: ").concat(ex.message));
}
} else if (tagsHas(name)) throw new Error("cannot remove child tag <<".concat(name, ">> of parent macro <<").concat(_tags[name], ">> "));
}
},
isEmpty: {
value: function() { return 0 === Object.keys(_macros).length; }
},
has: {
value: macrosHas
},
get: {
value: function(name) {
var macro = null;
return macrosHas(name) && "function" == typeof _macros[name].handler ? macro = _macros[name] : Object.hasOwn(macros, name) && "function" == typeof macros[name].handler && (macro = macros[name]), macro;
}
},
init: {
value: function() {
var handler = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "init";
Object.keys(_macros).forEach(
```
--------------------------------
### Configuration Loading
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/shop.html
Shows how to load configuration settings from a file. This is crucial for managing application parameters like database credentials, API keys, or feature flags without hardcoding them.
```Python
import json
def load_config(filepath):
"""Loads configuration from a JSON file."""
with open(filepath, 'r') as f:
return json.load(f)
```
--------------------------------
### Get Error Message
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Provides a consistent way to get an error message from various error-like objects. It handles null inputs and objects with a 'message' property.
```javascript
function getErrorMessage(O){return null==O?"unknown error":"object"===_typeof(O)&&"message"in O?O.message:String(O)}
```
--------------------------------
### OpenAIModel API Documentation
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Documentation for interacting with OpenAI models. Includes the constructor for initializing a model with its name and provider, and methods for generating text.
```APIDOC
OpenAIModel:
__init__(model_name: str, provider: str = 'openai')
model_name: The name of the OpenAI model to use
provider: The provider to use (defaults to 'openai')
generate_text(prompt: str, max_tokens: int = 150) -> str
Generates text based on the provided prompt.
prompt: The input text prompt.
max_tokens: The maximum number of tokens to generate.
Returns: The generated text.
```
--------------------------------
### Initialization and Event Handling
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Initializes the settings by loading them and then calls the 'onInit' function for each setting definition if it exists. This allows for custom initialization logic for each setting.
```javascript
init: function(){load(),_definitions.forEach((function(def){if(Object.hasOwn(def,"onInit")){var data=createResultObject(def);def.onInit.call(data,data)}}))}
```
--------------------------------
### Constructor and Proxy Utilities
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
Utilities for handling constructor functions and creating proxies, essential for advanced JavaScript patterns and library implementations.
```javascript
var Ee=function wrapConstructor(e,t,r){
m.preserveToString(t,e);
if(Object.setPrototypeOf){
Object.setPrototypeOf(e,t)
}
if(s){
l(Object.getOwnPropertyNames(e),function(n){
if(n in W||r[n]){return}
m.proxy(e,n,t)
})}
else{
l(Object.keys(e),function(n){
if(n in W||r[n]){return}
t[n]
```
--------------------------------
### Python Decorator Example
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/crafting.html
This snippet provides an example of a Python decorator, which is a way to modify or enhance functions or methods. Decorators are often used for logging, access control, and instrumentation.
```Python
def my_decorator(func):
def wrapper():
print('Something is happening before the function is called.')
func()
print('Something is happening after the function is called.')
return wrapper
@my_decorator
def say_hello():
print('Hello!')
say_hello()
```
--------------------------------
### SimpleStore Initialization and Adapters
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/shop.html
Manages data storage using adapters. It initializes the storage system and allows for different storage adapters (like cookies) to be registered and used.
```javascript
var SimpleStore=(
_adapters=
[],
_initialized=null,
Object.preventExtensions(Object.create(null,{
adapters:{value:
_adapters
},
create:{value:function(storageId,persistent){
if(_initialized)
return _initialized.create(storageId,persistent);
for(var i=0;i<_adapters.length;++i)
if(_adapters[i].init(storageId,persistent))
return(
_initialized=
_adapters[i]
).create(storageId,persistent);
throw new Error("No valid storage adapters found")
}}}
}))
),_adapters,_initialized,_MAX_EXPIRY,_MIN_EXPIRY,_ok,CookieAdapter;
```
--------------------------------
### Python Basic Arithmetic Operations
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/collectibles.html
This snippet provides examples of basic arithmetic operations in Python, including addition, subtraction, multiplication, and division. It's a fundamental code example.
```Python
def perform_calculations(a, b):
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b if b != 0 else 'Cannot divide by zero'
return addition, subtraction, multiplication, division
# Example usage:
# result = perform_calculations(10, 5)
# print(f"Addition: {result[0]}")
# print(f"Subtraction: {result[1]}")
# print(f"Multiplication: {result[2]}")
# print(f"Division: {result[3]}")
```
--------------------------------
### SimpleStore Initialization
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/recipes/equipment.html
Provides a top-level function to create a SimpleStore instance, automatically selecting the best available storage adapter (WebStorage or Cookie).
```javascript
var SimpleStore = {
adapters: [],
create: function(storageId, persistent) {
if (_initialized) return _initialized.create(storageId, persistent);
for (var i = 0; i < _adapters.length; ++i) {
if (_adapters[i].init(storageId, persistent)) {
return (_initialized = _adapters[i]).create(storageId, persistent);
}
}
throw new Error("No valid storage adapters found");
}
};
// Adapters are pushed into SimpleStore.adapters during definition.
// Example: SimpleStore.adapters.push(WebStorageAdapter);
// Example: SimpleStore.adapters.push(CookieAdapter);
```
--------------------------------
### Create Inventory with Tags
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/Guide.md
Demonstrates how to create an inventory instance with specified tags. Tags are strings used to add metadata to inventories. Requires the Inventory object.
```javascript
<>
<>
```
--------------------------------
### Run User Initialization Passages in JavaScript
Source: https://github.com/chapelr/simple-inventory/blob/main/docs/demo.html
This JavaScript code snippet iterates through initialization passages and evaluates their text using `Wikifier.wikifyEval`. It includes debugging features and error handling. The code also handles a 'StoryInit' passage if it exists.
```JavaScript
Story.getInits().forEach((function(passage){try{var debugBuffer=Wikifier.wikifyEval(passage.text);if(Config.debug){var debugView=new DebugView(document.createDocumentFragment(),"special","".concat(passage.name," [init-tagged]"),"".concat(passage.name," [init-tagged]"));debugView.modes({hidden:!0}),debugView.append(debugBuffer),_initDebugViews.push(debugView.output)}}catch(ex){console.error(ex),Alert.error("".concat(passage.name," [init-tagged]"),getErrorMessage(ex))}})),Story.has("StoryInit")))try{var debugBuffer=Wikifier.wikifyEval(Story.get("StoryInit").text);if(Config.debug){var debugView=new DebugView(document.createDocumentFragment(),"special","StoryInit","StoryInit");debugView.modes({hidden:!0}),debugView.append(debugBuffer),_initDebugViews.push(debugView.output)}}catch(ex){console.error(ex),Alert.error("StoryInit",getErrorMessage(ex))}
```