This documentation is a reference for SugarCube v2, a free (gratis and libre) story format for Twine/Twee.
本文档是 SugarCube v2 的参考,SugarCube v2 是一个免费的(免费且自由)Twine/Twee 故事格式。
Tip:
This document is a single page, so you may use your browser's find-in-page functionality—CTRL+F, CMD+F, F3—to search for specific terms.
提示:本文档是一页,您可以使用浏览器中的查找功能—— CTRL + F , CMD + F , F3 ——来搜索特定术语。
Note:
If you believe that you've found a bug in SugarCube, or simply wish to make a suggestion, you may do so by creating a new issue at its source code repository.
注意:如果您认为在 SugarCube 中发现了错误,或者只是想提出建议,您可以通过在其源代码仓库中创建新问题来这样做。
Contributions to this documentation have been graciously made by:
本文档的贡献者包括:
Note:
Except where noted, all markup has been available since v2.0.0
.
注意:除非另有说明,否则所有标记都自 v2.0.0
以来一直可用。
In addition to using one of the print macros (<<print>>
, <<=>>
, <<->>
) to print the values of TwineScript variables, SugarCube's naked variable markup allows printing them simply by including them within your normal passage text—i.e., variables in passage text are interpolated into a string representation of their values.
除了使用打印宏( <<print>>
、 <<=>>
、 <<->>
)来打印 TwineScript 变量的值之外,SugarCube 的裸变量标记还允许通过在正常段落文本中包含它们来简单地打印它们——即,段落文本中的变量将被插入到它们的字符串表示形式中。
The following forms are supported by the naked variable markup:
裸变量标记支持以下形式:
Type 类型 | Syntax 语法 | Example 示例 |
---|---|---|
Simple variable 简单变量 |
|
|
Property access, 属性访问, dot notation 点表示法 |
|
|
Index/property access, 索引/属性访问, square bracket notation 方括号表示法 |
|
|
If you need to print anything more complex—e.g., using a calculation, $variable[_i + 1]
, or a method call, $variable.someMethod()
—then you will still need to use one of the print macros.
如果您需要打印更复杂的内容——例如,使用计算、 $variable[_i + 1]
或方法调用, $variable.someMethod()
——那么您仍然需要使用其中一个打印宏。
For example: 例如:
/* Explicitly printing the value of $name via the <<print>> macro */
Well hello there, <<print $name>>.
/* Implicitly printing the value of $name via the naked variable markup */
Well hello there, $name.
/* Assuming $name is set to "Mr. Freeman", both should yield the following */
Well hello there, Mr. Freeman.
Because variables within your passage text are transformed into their values automatically, if you actually want to output a variable as-is—i.e., without interpolation; e.g., for a tutorial, debug output, or whatever—then you'll need to escape it in some fashion. For example:
由于段落文本中的变量会自动转换为它们的值,如果您实际上想以原始形式输出一个变量——即不进行插值;例如,用于教程、调试输出或任何其他用途——那么您需要以某种方式转义它。例如:
/* Using the nowiki markup: """…""" (triple double-quotes) */
The variable """$name""" is set to: $name
/* Using the nowiki markup: <nowiki>…</nowiki> */
The variable <nowiki>$name</nowiki> is set to: $name
/* Using the double dollar-sign markup (which escapes the $-sigil): $$ */
The variable $$name is set to: $name
/* Assuming $name is set to "Mr. Freeman", all of the above should yield the following */
The variable $name is set to: Mr. Freeman
Additionally, you could use the inline code markup to escape the variable, though it will also wrap the escaped variable within a <code>
element, so it's probably best used for examples and tutorials. For example:
此外,您还可以使用内联代码标记来转义变量,尽管这也会将转义的变量包裹在 <code>
元素中,因此它可能最好用于示例和教程。例如:
/* Using the inline code markup: {{{…}}} (triple curly braces) */
The variable {{{$name}}} is set to: $name
/* Assuming $name is set to "Mr. Freeman", it should yield the following */
The variable <code>$name</code> is set to: Mr. Freeman
SugarCube's link markup consists of a required Link
component and optional Text
and Setter
components.
SugarCube 的链接标记由一个必需的 Link
组件和可选的 Text
和 Setter
组件组成。
The Link
component may be either plain text or any valid TwineScript expression, which will be evaluated early—i.e., when the link is initially processed. Its value should be the title of a passage or any valid URL to a resource (local or remote).
Link
组件可以是纯文本或任何有效的 TwineScript 表达式,它将在链接最初处理时进行评估——即,当链接最初被处理时。其值应该是篇章的标题或任何有效的资源(本地或远程)的 URL。
The optional Text
component may be either plain text or any valid TwineScript expression, which will be evaluated early—i.e., when the link is initially processed.
可选的 Text
组件可以是纯文本或任何有效的 TwineScript 表达式,它将在链接最初处理时进行评估——即,当链接最初被处理时。
The optional Setter
component, which only works with passage links, must be a valid TwineScript expression, of the <<set>>
macro variety, which will be evaluated late—i.e., when the link is clicked on. If you need to specify multiple expressions, then they should be separated by semi-colons (;
)—e.g., $a to 5; $b to true
.
可选的 Setter
组件,仅适用于篇章链接,必须是一个有效的 TwineScript 表达式,属于 <<set>>
宏类型,它将在链接点击时进行评估——即,当链接被点击时。如果您需要指定多个表达式,则应使用分号( ;
)分隔——例如, $a to 5; $b to true
。
In addition to the standard pipe separator (|
) used to separate the Link
and Text
components (as seen below), SugarCube also supports the arrow separators (->
& <-
). Particular to the arrow separators, the arrows' direction determines the order of the components, with the arrow always pointing at the Link
component—i.e., the right arrow works like the pipe separator, Text->Link
, while the left arrow is reversed, Link<-Text
.
除了用于分隔 Link
和 Text
组件的标准管道分隔符( |
)外,SugarCube 还支持箭头分隔符( ->
& <-
)。对于箭头分隔符,箭头的方向决定了组件的顺序,箭头始终指向 Link
组件——即右箭头的作用类似于管道分隔符, Text->Link
,而左箭头则是相反的, Link<-Text
。
Warning (Twine 2):
Due to how the Twine 2 automatic passage creation feature currently works, using any TwineScript expression for the Link
component will cause a passage named after the expression to be created that will need to be deleted. To avoid this problem, it's suggested that you use the separate argument form of the <<link>>
macro in Twine 2 when you need to use an expression.
警告(TWINE 2):由于 Twine 2 自动创建段落功能当前的工作方式,使用任何 TwineScript 表达式作为 Link
组件将导致创建一个以表达式命名的段落,该段落需要被删除。为了避免这个问题,建议在需要使用表达式时,使用 Twine 2 中 <<link>>
宏的单独参数形式。
Syntax 语法 | Example 示例 |
---|---|
|
|
|
|
|
|
|
|
SugarCube's image markup consists of a required Image
component and optional Title
, Link
, and Setter
components.
SugarCube 的图像标记由一个必需的 Image
组件和可选的 Title
、 Link
和 Setter
组件组成。
The Image
component may be either plain text or any valid TwineScript expression, which will be evaluated early—i.e., when the link is initially processed. Its value may be any valid URL to an image resource (local or remote) or the title of an media (image) passage.
Image
组件可以是纯文本或任何有效的 TwineScript 表达式,该表达式将在链接最初处理时进行评估。其值可以是任何有效的图像资源(本地或远程)的 URL 或媒体(图像)篇章的标题。
The optional Title
component may be either plain text or any valid TwineScript expression, which will be evaluated early—i.e., when the link is initially processed. Its value will be used as the alt text of the image.
可选的 Title
组件可以是纯文本或任何有效的 TwineScript 表达式,该表达式将在链接最初处理时进行评估。其值将用作图像的 alt 文本。
The optional Link
component may be either plain text or any valid TwineScript expression, which will be evaluated early—i.e., when the link is initially processed. Its value may be the title of a passage or any valid URL to a resource (local or remote).
可选的 Link
组件可以是纯文本或任何有效的 TwineScript 表达式,它将在链接最初处理时被评估——即,当链接最初被处理时。它的值可以是篇章的标题或任何有效的资源(本地或远程)URL。
The optional Setter
component, which only works with passage links, must be a valid TwineScript expression, of the <<set>>
macro variety, which will be evaluated late—i.e., when the link is clicked on. If you need to specify multiple expressions, then they should be separated by semi-colons (;
)—e.g., $a to 5; $b to true
.
可选的 Setter
组件仅适用于篇章链接,必须是一个有效的 TwineScript 表达式,属于 <<set>>
宏类型,它将在点击链接时被评估——即,当链接被点击时。如果您需要指定多个表达式,则它们应该由分号( ;
)分隔——例如, $a to 5; $b to true
。
In addition to the standard pipe separator (|
) used to separate the Image
and Title
components (as seen below), SugarCube also supports the arrow separators (->
& <-
). Particular to the arrow separators, the arrows' direction determines the order of the components, with the arrow always pointing at the Image
component—i.e., the right arrow works like the pipe separator, Title->Image
, while the left arrow is reversed, Image<-Title
.
除了用于分隔 Image
和 Title
组件的标准管道分隔符( |
)之外,SugarCube 还支持箭头分隔符( ->
& <-
)。对于箭头分隔符,箭头的方向决定了组件的顺序,箭头始终指向 Image
组件——即,右箭头的作用类似于管道分隔符 Title->Image
,而左箭头是相反的, Image<-Title
。
Warning (Twine 2):
Due to how the Twine 2 automatic passage creation feature currently works, using any TwineScript expression for the Link
component will cause a passage named after the expression to be created that will need to be deleted. To avoid this problem, it's suggested that you use the separate argument form of the <<link>>
macro in Twine 2 when you need to use an expression.
警告(TWINE 2):由于 Twine 2 自动段落创建功能当前的工作方式,使用任何 TwineScript 表达式为 Link
组件将导致创建一个以表达式命名的段落,该段落需要被删除。为了避免这个问题,建议在 Twine 2 中需要使用表达式时,使用 <<link>>
宏的单独参数形式。
Syntax 语法 | Example 示例 |
---|---|
|
|
|
|
|
|
|
|
|
|
|
|
A restricted subset of the image markup, allowing only the Image
component, may be used within stylesheets—primarily to allow the easy use of media (image) passages. For example:
图像标记的受限子集,仅允许使用 Image
组件,可以在样式表中使用——主要用于允许轻松使用媒体(图像)段落。例如:
/* Using the external image "forest.png" as the <body> background. */
body {
background-image: [img[forest.png]];
}
/* Using the image passage "lagoon" as the <body> background. */
body {
background-image: [img[lagoon]];
}
Warning:
None of these features work within the verbatim HTML markup.
警告:这些功能在直接 HTML 标记中都无法工作。
SugarCube provides a few special HTML & SVG attributes, which you may add to tags to enable special behaviors. There are attributes for passage links, media passages, and setters.
SugarCube 提供了一些特殊的 HTML 和 SVG 属性,您可以将这些属性添加到标签中以启用特殊行为。这些属性包括段落链接、媒体段落和设置器。
Type 类型 | Attribute 属性 | Example 示例 |
---|---|---|
Passage, Link 段落,链接 |
|
|
Passage, Audio 段落,音频 |
|
|
Passage, Image 文本,图片 |
|
|
Passage, Source 文本,来源 |
|
|
Passage, Video 文本,视频 |
|
|
Setter 设置者 |
|
|
v2.0.0
: Introduced. v2.0.0
: 引入。v2.24.0
: Added data-passage
attribute support to <audio>
, <source>
, and <video>
tags.data-passage
、 <audio>
和 <source>
标签的 <video>
属性支持。HTML & SVG attributes may be prefixed with directives, special text, which trigger special processing of such attributes.
HTML 和 SVG 属性可以带有指令,这些指令是特殊的文本,可以触发对这些属性的特定处理。
sc-eval:
, @
sc-eval:
, @
The evaluation directive causes the attribute's value to be evaluated as TwineScript. Post-evaluation, the directive will be removed from the attribute's name and the result of the evaluation will be used as the actual value of the attribute.
评估指令会导致将属性的值评估为 TwineScript。评估后,指令将从属性名称中删除,并将评估结果用作属性的真正值。
Warning:
The evaluation directive is not allowed on the data-setter
attribute—as its function is to evaluate its contents upon activation of its own element—and any such attempt will cause an error.
警告:评估指令不允许用于 data-setter
属性——因为它的功能是在其自身元素激活时评估其内容——任何此类尝试都将导致错误。
Syntax 语法 | Example 示例 | Rendered As 渲染为 |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
v2.21.0
: Introduced. v2.21.0
: 引入。v2.23.5
: Fixed an issue with the evaluation directive where using multiple directives on a single HTML tag would result in some being unprocessed.v2.23.5
: 修复了评估指令的问题,当在单个 HTML 标签上使用多个指令时,会导致某些指令未被处理。See Also:
The various no-break features—<<nobr>>
macro, nobr
special tag, and Config.passages.nobr
setting—all perform a similar, though slightly different, function.
参考以下各种不间断特性—— <<nobr>>
宏、 nobr
特殊标签和 Config.passages.nobr
设置,它们都执行类似但略有不同的功能。
Warning:
Line continuations, or any markup that relies on line positioning, are incompatible with the no-break features because of how the latter function.
警告:由于不间断特性的工作方式,行续或任何依赖于行定位的标记都不兼容,因为它们的功能。
A backslash (\
) that begins or ends a line is the line continuation markup. Upon processing the backslash, associated line break, and all whitespace between them are removed—thus, joining the nearby lines together. This is mostly useful for controlling whitespace when you want to wrap lines for readability, but not generate extra whitespace upon display, and the <<silently>>
macro isn't an option because you need to generate output.
一个以反斜杠( \
)开始或结束的行是行续标记。在处理反斜杠、相关的换行符以及它们之间的所有空白后,将附近的行连接在一起。这主要用于控制空白,当您想要为了可读性而换行时,但又不希望在显示时产生额外的空白,并且当 <<silently>>
宏不可用时,因为您需要生成输出。
For example, all of the following: (n.b., ·
represents whitespace that will be removed, ¬
represents line breaks)
例如,以下所有内容:(注意, ·
代表将被删除的空白, ¬
代表换行符)
The rain in Spain falls \¬
mainly on the plain.
The rain in Spain falls \····¬
mainly on the plain.
The rain in Spain falls¬
\ mainly on the plain.
The rain in Spain falls¬
····\ mainly on the plain.
Yield the single line in the final output:
输出单行文本:产生最终输出单行
The rain in Spain falls mainly on the plain.
An exclamation point (!
) that begins a line defines the heading markup. It consists of one to six exclamation points, each additional one beyond the first signifying a lesser heading.
以感叹号( !
)开始的行定义标题标记。它由一个到六个感叹号组成,每个额外的感叹号都表示比第一个更小的标题。
Type 类型 | Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|---|
Level 1 一级 |
|
|
Level 1 Heading 一级标题 |
Level 2 二级 |
|
|
Level 2 Heading 二级标题 |
Level 3 三级 |
|
|
Level 3 Heading 三级标题 |
Level 4 四级 |
|
|
Level 4 Heading 四级标题 |
Level 5 五级 |
|
|
Level 5 Heading 五级标题 |
Level 6 六级 |
|
|
Level 6 Heading 六级标题 |
Warning:
Because the style markups use the same tokens to begin and end each markup, the same style cannot be nested within itself.
警告:由于样式标记使用相同的标记来开始和结束每个标记,相同的样式不能嵌套在其自身内部。
Type 类型 | Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|---|
Emphasis 强调 |
|
|
Emphasis 强调 |
Strong 强烈 |
|
|
Strong 强烈 |
Underline 下划线 |
|
|
Underline 下划线 |
Strikethrough 删除线 |
|
|
|
Superscript 上标 |
|
|
Superscript 上标 script |
Subscript 下标 |
|
|
Subscript 子 script |
An asterisk (*
) or number sign (#
) that begins a line defines a member of the unordered or ordered list markup, respectively.
以星号( *
)或井号( #
)开头的行分别定义无序列表或有序列表的标记。
Type 类型 | Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|---|
Unordered 无序列表 |
|
|
|
Ordered 有序的 |
|
|
|
A right angle bracket (>
) that begins a line defines the blockquote markup. It consists of one or more right angle brackets, each additional one beyond the first signifying a level of nested blockquote.
一个右尖括号( >
)开始一行,定义了引用标记。它由一个或多个右尖括号组成,第一个之后的每个额外的右尖括号表示嵌套引用标记的级别。
Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|
|
|
Line 1 行 1 |
Type 类型 | Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|---|
Inline 行内 |
|
|
|
Block 区块 |
|
|
|
A set of four hyphen/minus characters (-
) that begins a line defines the horizontal rule markup.
一行开头的四个连字符( -
)定义了水平线标记。
Type 类型 | Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|---|
Horizontal rule 水平线 |
|
|
The verbatim text markup disables processing of all markup contained within—both SugarCube and HTML—passing its contents directly into the output as plain text.
原文文本标记禁用了所有标记的处理,包括 SugarCube 和 HTML,直接将其内容作为纯文本传递到输出中。
Type 类型 | Syntax & Example 语法 & 示例 | Rendered As 渲染为 | Displays As (roughly) 显示为(大致) |
---|---|---|---|
Triple double quotes 三重双引号 |
|
|
No //format// 没有 //格式// |
<nowiki> tag 标签 |
|
|
No //format// 没有 //格式// |
A set of opening and closing <html> tags—i.e., <html></html>
—defines the verbatim HTML markup. The verbatim HTML markup disables processing of all markup contained within—both SugarCube and HTML—passing its contents directly into the output as HTML markup for the browser. Thus, you should only use plain HTML markup within the verbatim markup—meaning using none of SugarCube's special HTML attributes or directives.
一组开始和结束的标签——即 <html></html>
——定义了原始 HTML 标记。原始 HTML 标记禁用了对其中包含的所有标记的处理——无论是 SugarCube 还是 HTML——直接将其内容作为 HTML 标记传递到输出中。因此,您只能在原始标记内使用纯 HTML 标记——这意味着不要使用 SugarCube 的特殊 HTML 属性或指令。
Note:
You should virtually never need to use the verbatim HTML markup.
注意:您几乎永远不需要使用原始 HTML 标记。
Warning:
Because the custom style markup uses the same tokens to begin and end the markup, it cannot be nested within itself.
警告:由于自定义样式标记使用相同的标记开始和结束标记,因此它不能嵌套在其自身内部。
Type 类型 | Syntax 语法 | Example 示例 | Rendered As 渲染为 |
---|---|---|---|
Inline 行内 |
|
|
|
|
|
||
Block 区块 |
|
|
|
|
|
;
) separated list consisting of one or more of the following:
;
)分隔的列表,包含以下之一或多个:#alfa
.#alfa
。.bravo
..bravo
。color:red
.color:red
。v2.31.0
, the ID and class names components may be conjoined without need of extra semi-colons—e.g., #alfa;.bravo;.charlie;
may also be written as #alfa.bravo.charlie;
.
v2.31.0
,ID 和类名组件可以合并使用,无需额外分号——例如, #alfa;.bravo;.charlie;
也可以写成 #alfa.bravo.charlie;
。A text replacement markup. The template markup begins with a question mark (?
) followed by the template name—e.g., ?yolo
—and are set up as functions-that-return-strings, strings, or arrays of either—from which a random member is selected whenever the template is processed. They are defined via the Template
API.
文本替换标记。模板标记以问号( ?
)开头,后跟模板名称——例如, ?yolo
——并设置为返回字符串、字符串或数组的函数,从其中随机选择一个成员,每当处理模板时。它们通过 Template
API 定义。
For example, consider the following markup:
例如,考虑以下标记:
?He was always willing to lend ?his ear to anyone.
Assuming that ?He
resolves to She
and ?his
to her
, then that will produce the following output:
假设 ?He
解析为 She
, ?his
解析为 her
,那么这将产生以下输出:
She was always willing to lend her ear to anyone.
v2.29.0
: Introduced. v2.29.0
: 引入。Note:
Comments used within passage markup are not rendered into the page output.
注意:段落标记内使用的注释不会渲染到页面输出中。
Type 类型 | Syntax & Example 语法 & 示例 | Supported Within… 支持在... |
---|---|---|
C-style, Block C 样式,块 |
|
Passage markup, JavaScript, Stylesheets 段落标记,JavaScript,样式表 |
TiddlyWiki, Block TiddlyWiki,块 |
|
Passage markup 段落标记 |
HTML, Block HTML,块 |
|
Passage markup 段落标记 |
TwineScript in SugarCube is, essentially, JavaScript with an extra spoonful of sugar on top to make it a bit nicer for the uninitiated.
SugarCube 中的 TwineScript 实质上是带有额外一勺糖的 JavaScript,使其对初学者更加友好。
Note:
Temporary variables were added in v2.3.0
.
注意:已添加临时变量 v2.3.0
。
A variable is a bit of storage where you may stash a value for later use. In SugarCube, they come in two types: story variables and temporary variables. Story variables are a part of the story history and exist for the lifetime of a playthrough session. Temporary variables do not become part of the story history and only exist for the lifetime of the moment/turn that they're created in. You'll likely use story variables most often throughout your project—though, temporary variables are perfect candidates for things like loop variables, if you're using the <<for>>
macro.
变量是一种存储空间,您可以将其用于存储值以供以后使用。在 SugarCube 中,变量分为两种:故事变量和临时变量。故事变量是故事历史的一部分,存在于整个游戏会话期间。临时变量不会成为故事历史的一部分,仅存在于它们被创建的那个时刻/回合。您可能会在项目中更频繁地使用故事变量——尽管,如果您使用 <<for>>
宏,临时变量是循环变量等事物的完美候选。
For example, you might use the story variable $name
to store the main player character's name or the story variable $cash
to store how much money the player has on hand.
例如,您可以使用故事变量 $name
来存储主要玩家角色的名字,或者使用故事变量 $cash
来存储玩家手中的金钱。
Values may be of most primitive types and some object types, see Supported Types for more information.
值可以是大多数基本类型和一些对象类型,更多详细信息请参阅“支持类型”。
The names of both story and temporary variables have a certain format that they must follow—which signifies that they are variables and not some other kind of data.
故事变量和临时变量的命名都遵循一定的格式,这表明它们是变量,而不是其他类型的数据。
The very first, and mandatory, character is their sigil, which denotes whether they are a story or temporary variable. The sigil must be a dollar sign ($
) for story variables or an underscore (_
) for temporary variables.
第一个且必须的字符是它们的符号,它表示它们是故事变量还是临时变量。符号必须是美元符号( $
)用于故事变量,或者下划线( _
)用于临时变量。
The second, and also mandatory, character of the variable name may be one of the following: the letters A though Z (in upper or lower case), the dollar sign, and the underscore (i.e., A-Za-z$_
)—after their initial use as the sigil, the dollar sign and underscore become regular variable characters.
第二个字符,也是变量名必须遵守的规则之一,可以是以下之一:大写或小写的字母 A 到 Z、美元符号和下划线(即 A-Za-z$_
)——在它们作为符号的初始使用之后,美元符号和下划线成为常规变量字符。
Subsequent, optional, characters have the same set as the second with the addition of numerals (i.e., 0-9
, so the full set is A-Za-z0-9$_
). No other characters are allowed.
后续可选字符与第二个字符集相同,并增加了数字(例如 0-9
,所以完整集合为 A-Za-z0-9$_
)。不允许其他字符。
A few examples of valid names:
一些有效的名称示例:
/* Story variables */
$cash
$hasKeyCard5
$met_alice
$TIMES_POKED_MR_BEAR
/* Temporary variables */
_i
_something2
_some_loop_value
_COUNT
Note:
This is not an exhaustive list. There are many ways to use and interact with variables.
注意:这不是一个详尽的列表。有许多使用和交互变量的方式。
To modify the values contained within variables, see the <<set>>
macro and setter links.
要修改变量中包含的值,请参阅 <<set>>
宏和设置器链接。
To print the values contained within variables, see the naked variable markup and the <<print>>
, <<=>>
, and <<->>
macros.
要打印变量中包含的值,请参阅裸变量标记和 <<print>>
、 <<=>>
、 <<->>
宏。
To control aspects of your project based on the values contained within variables, see the <<if>>
and <<switch>>
macros.
要根据变量中包含的值控制项目的一些方面,请参阅 <<if>>
和 <<switch>>
宏。
The following types of values are natively supported by SugarCube and may be safely used within story and temporary variables.
以下类型的数据由 SugarCube 原生支持,可以在故事和临时变量中安全使用。
true
& false
布尔值—例如, true
& false
42
, 3.14
, -24
, -17.76
, & Infinity
42
, 3.14
, -24
, -17.76
,& Infinity
"I like pie"
& 'You like pie'
字符串—例如, "I like pie"
& 'You like pie'
null
undefined
Array
Date
Map
Set
Any supported object type may itself contain any supported primitive or object type.
任何支持的对象类型本身可以包含任何支持的原始或对象类型。
Unsupported object types, either native or custom, can be made compatible by implementing .clone()
and .toJSON()
methods for them—see the Non-generic object types (classes) guide for more information.
不支持的对象类型,无论是原生还是自定义,都可以通过实现 .clone()
和 .toJSON()
方法使其兼容——有关更多信息,请参阅“非泛型对象类型(类)”指南。
Due to how SugarCube stores the state history a few constructs are not supported within story variables.
由于 SugarCube 存储状态历史的方式,一些结构不支持在故事变量中使用。
Functions, including static—i.e., non-instance—methods, due to a few issues.
函数,包括静态(即非实例)方法,由于一些问题。
Instance methods of classes are not affected by either issue, as they're never actually stored within story variables, being referenced from their classes' prototypes instead.
类实例方法不受这两个问题的影响,因为它们实际上从未存储在故事变量中,而是从它们所属类的原型中进行引用。
Expressions are simply units of code that yield values when evaluated. For example:
表达式是代码单元,当它们被评估时会产生值。例如:
// Yields: true
true
// Yields: 1 (assuming that it is the first turn)
turns()
// Yields: 4
2 + 2
// Yields: "22"
"2" + "2"
Basic expressions simply consist of identifiers and literals—e.g., $a
, 69
, and "hello"
. Complex expressions consist of basic expressions joined together by operators—e.g., =
and +
.
基本表达式仅由标识符和字面量组成——例如: $a
, 69
,和 "hello"
。复杂表达式由基本表达式通过运算符连接而成——例如: =
和 +
。
While every valid expression—even those you might not expect—yields a value, there are essentially two types of expressions: those with side effects and those without. A side effect simply means that the evaluation of the expression modifies some state. For example:
虽然每个有效的表达式——甚至是你可能没有预料到的——都会产生一个值,但本质上存在两种类型的表达式:带有副作用和不带有副作用的表达式。副作用简单来说就是表达式的评估会修改某些状态。例如:
// Yields: 5; Side effect: assigns 5 to the story variable $a
$a = 5
// Yields: 25 (assuming $x is 15); No side effects
$x + 10
In general, you can group expressions into categories based on what kind of value they yield and/or what side effects they cause. For example: (not an exhaustive list)
通常,你可以根据表达式产生的值类型和/或它们引起的副作用将表达式分组。例如:(以下非详尽列表)
42
or 3.14
.42
或 3.14
。"Lulamoon"
or "5678"
."Lulamoon"
或 "5678"
。true
or false
.true
或 false
。$a = 5
.$a = 5
。You will, in all likelihood, use expressions most often within macros—e.g., <<set>>
, <<print>>
, <<if>>
, <<for>>
.
你很可能会在宏中频繁使用表达式——例如, <<set>>
, <<print>>
, <<if>>
, <<for>>
。
Operators join together operands, which are formed from either basic or complex expressions.
运算符将操作数连接起来,操作数由基本或复杂表达式形成。
In both TwineScript and JavaScript there are binary and unary operators—n.b., Javascript also includes a ternary operator, the conditional operator. Binary operators require two operands, one before and one after the operator, while unary operators only require one operand, either before or after the operator.
在 TwineScript 和 JavaScript 中都有二元和一元运算符——请注意,JavaScript 还包括三元运算符,即条件运算符。二元运算符需要两个操作数,一个在运算符之前,一个在运算符之后,而一元运算符只需要一个操作数,可以在运算符之前或之后。
Binary operator examples:
二元运算符示例:
// operand1 OPERATOR operand2
2 + 2
$a = 5
Unary operator examples:
一元运算符示例:
// operand OPERATOR
$i++
// OPERATOR operand
++$x
not $hasKey
Assignment operators assign a value to their left-hand operand based on the value of their right-hand operand.
赋值运算符根据其右操作数的值将其左操作数赋值。
Operator 操作员 | Description 描述 | Example 示例 |
---|---|---|
to |
Assigns the value on the right-hand side of the operator to the left-hand side. 将运算符右侧的值分配给左侧。 |
|
Operator 操作员 | Description 描述 | Example 示例 |
---|---|---|
= |
Assigns the value on the right-hand side of the operator to the left-hand side. 将运算符右侧的值分配给左侧。 |
|
+= |
Adds the value on the right-hand side of the operator to the current value on the left-hand side and assigns the result to the left-hand side. 将运算符右侧的值与左侧的当前值相加,并将结果分配给左侧。 |
|
-= |
Subtracts the value on the right-hand side of the operator from the current value on the left-hand side and assigns the result to the left-hand side. 从左侧的当前值中减去运算符右侧的值,并将结果分配给左侧。 |
|
*= |
Multiplies the current value on the left-hand side of the operator by the value on the right-hand side and assigns the result to the left-hand side. 将运算符左侧的当前值乘以右侧的值,并将结果分配给左侧。 |
|
/= |
Divides the current value on the left-hand side of the operator by the value on the right-hand side and assigns the result to the left-hand side. 将运算符左侧的当前值除以右侧的值,并将结果分配给左侧。 |
|
%= |
Divides the current value on the left-hand side of the operator by the value on the right-hand side and assigns the remainder to the left-hand side. 将运算符左侧的当前值除以右侧的值,并将余数分配给左侧。 |
|
Comparison operators compare their operands and return a boolean value based on whether the comparison is true.
比较运算符比较它们的操作数,并根据比较是否为真返回布尔值。
Operator 操作员 | Description 描述 | Example 示例 |
---|---|---|
is |
Evaluates to true if both sides are strictly equal.如果两边严格相等,则评估为 true 。 |
|
isnot |
Evaluates to true if both sides are strictly not equal.如果两边严格不相等,则评估为 true 。 |
|
eq |
Evaluates to true if both sides are equivalent. Not recommended, use the is operator.如果两边等价,则评估为 true 。不推荐使用,请使用 is 运算符。 |
|
neq |
Evaluates to true if both sides are not equivalent. Not recommended, use the isnot operator.如果两边不相等,则返回 true 。不推荐使用,请使用 isnot 运算符。 |
|
gt |
Evaluates to true if the left side is greater than the right side.判断结果为 true ,如果左侧大于右侧。 |
|
gte |
Evaluates to true if the left side is greater than or equal to the right side.计算结果为 true ,如果左侧大于或等于右侧。 |
|
lt |
Evaluates to true if the left side is less than the right side.等于 true 如果左侧小于右侧。 |
|
lte |
Evaluates to true if the left side is less than or equal to the right side.如果左侧小于或等于右侧,则返回 true 。 |
|
not |
Flips a true evaluation to false , and vice versa.将 true 的评估结果翻转至 false ,反之亦然。 |
|
and |
Evaluates to true if all subexpressions evaluate to true .如果所有子表达式都评估为 true ,则返回 true 。 |
|
or |
Evaluates to true if any subexpressions evaluate to true .如果任何子表达式评估为 true ,则返回 true 。 |
|
def |
Evaluates to true if the right side is defined. See the precedence warning below.如果右侧已定义,则评估为 true 。下面是优先级警告。 |
|
ndef |
Evaluates to true if the right side is not defined. See the precedence warning below.如果右侧未定义,则评估为 true 。下面是优先级警告。 |
|
Warning:
The def
and ndef
operators have very low precedence, so it is strongly recommended that if you mix them with other operators, that you wrap them in parentheses—e.g., (def $style) and ($style is "girly")
.
警告: def
和 ndef
运算符的优先级非常低,因此强烈建议如果您将它们与其他运算符混合使用,请将它们放在括号内——例如, (def $style) and ($style is "girly")
。
Operator 操作员 | Description 描述 | Example 示例 |
---|---|---|
=== |
Evaluates to true if both sides are strictly equal.如果两边严格相等,则返回 true |
|
!== |
Evaluates to true if both sides are strictly not equal.如果两边严格不相等,则返回 true |
|
== |
Evaluates to true if both sides are equivalent. Not recommended, use the === operator.等于 true 如果两边相等。不推荐,请使用 === 操作符。 |
|
!= |
Evaluates to true if both sides are not equivalent. Not recommended, use the !== operator.如果两边不相等,则返回 true 。不推荐使用,请使用 !== 运算符。 |
|
> |
Evaluates to true if the left side is greater than the right side.判断结果为 true ,如果左侧大于右侧。 |
|
>= |
Evaluates to true if the left side is greater than or equal to the right side.计算结果为 true ,如果左侧大于或等于右侧。 |
|
< |
Evaluates to true if the left side is less than the right side.等于 true 如果左侧小于右侧。 |
|
<= |
Evaluates to true if the left side is less than or equal to the right side.等于 true ,如果左侧小于或等于右侧。 |
|
! |
Flips a true evaluation to false , and vice versa.翻转 true 评估为 false ,反之亦然。 |
|
&& |
Evaluates to true if all subexpressions evaluate to true .如果所有子表达式都评估为 true ,则评估为 true 。 |
|
|| |
Evaluates to true if any subexpressions evaluate to true .如果任何子表达式评估为 true ,则评估为 true 。 |
|
Macros fall into two broad categories based on the kind of arguments they accept: those that want an expression—e.g., <<set>>
and <<print>>
—and those that want discrete arguments separated by whitespace—e.g., <<link>>
and <<audio>>
. The documentation for each macro will tell you what it expects.
宏分为两大类,根据它们接受的参数类型:那些想要一个表达式——例如, <<set>>
和 <<print>>
——以及那些想要由空格分隔的离散参数——例如, <<link>>
和 <<audio>>
。每个宏的文档将告诉您它期望的内容。
Those that want an expression are fairly straightforward, as you simply supply an expression.
那些想要表达式的人相当简单,因为你只需提供一个表达式即可。
The discrete argument type of macros are also fairly straightforward, most of the time, as you simply supply the requisite arguments separated by whitespace, which may include variables—as SugarCube automatically yields their values to the macro. There are cases, however, where things get a bit more complicated, namely: instances where you need to pass the name of a variable as an argument, rather than its value, and those where you want to pass the result of an expression as argument.
宏的离散参数类型通常也很简单,你只需用空格分隔所需参数即可,这些参数可能包括变量——因为 SugarCube 会自动将它们的值传递给宏。然而,有时事情会变得稍微复杂一些,具体来说:当你需要传递变量的名称作为参数而不是其值时,以及当你想要传递表达式结果作为参数时。
Passing the name of a variable as an argument is problematic because variable substitution occurs automatically in SugarCube macros. Meaning that when you pass a variable as an argument, its value is passed to the macro rather than its name.
传递变量名称作为参数是有问题的,因为在 SugarCube 宏中变量替换是自动发生的。这意味着当你传递一个变量作为参数时,传递的是它的值而不是它的名称。
Normally, this is exactly what you want to happen. Occasionally, however, macros will need the name of a variable rather than its value—e.g., data input macros like <<textbox>>
—so that they may modify the variable. To resolve these instances, you will need to quote the name of the variable—i.e., instead of passing $pie
as normal, you'd pass "$pie"
. These, rare, instances are noted in the macros' documentation and shown in their examples.
通常情况下,这正是你希望发生的事情。然而,有时宏需要变量的名称而不是其值——例如,像 <<textbox>>
这样的数据输入宏——以便它们可以修改变量。为了解决这些情况,你需要引用变量的名称——也就是说,你将像传递 "$pie"
一样传递 $pie
。这些罕见的实例在宏的文档中有说明,并在它们的示例中展示。
Passing the result of an expression as an argument is problematic for a couple of reasons: because the macro argument parser doesn't treat arguments as expressions by default and because it separates arguments with whitespace.
传递表达式结果作为参数存在几个问题:因为宏参数解析器默认不将参数视为表达式,并且它使用空格来分隔参数。
Normally, those aren't issues as you should not need to use the result of an expression as an argument terribly often. To resolve instances where you do, however, you'll want to use either a temporary variable or a backquote expression.
通常情况下,这些问题并不严重,因为你通常不需要非常频繁地将表达式的结果用作参数。然而,当你确实需要这样做时,你将想要使用一个临时变量或反引号表达式来解决这个问题。
For example, the following will not work because the macro parser will think that you're passing five discrete arguments, rather than a single expression:
例如,以下代码将无法正常工作,因为宏解析器会认为您传递了五个独立的参数,而不是一个单独的表达式:
<<link "Wake " + $friend + ".">> … <</link>>
You could solve the problem by using a temporary variable to hold the result of the expression, then pass that to the macro. For example:
您可以通过使用一个临时变量来保存表达式的结果,然后将该结果传递给宏来解决该问题。例如:
<<set _text to "Wake " + $friend + ".">>\
<<link _text>> … <</link>>
A better solution, however, would be to use a backquote1 (`
) expression, which is really just a special form of quoting available in macro arguments that causes the contents of the backquotes to be evaluated and then yields the result as a singular argument. For example:
更好的解决方案是使用反引号 1( `
)表达式,这实际上是一种在宏参数中可用的特殊引用形式,它会导致反引号内的内容被评估,然后作为单个参数输出。例如:
<<link `"Wake " + $friend + "."`>> … <</link>>
~
) on keyboards.~
)一起出现在键盘上。<<capture variableList>> … <</capture>>
Captures story $variables and temporary _variables, creating localized versions of their values within the macro body.
捕获故事变量和临时变量,在宏体内部创建其值的本地化版本。
Note:
Use of this macro is only necessary when you need to localize a variable's value for use with an asynchronous macro—i.e., a macro whose contents are executed at some later time, rather than when it's invoked; e.g., interactive macros, <<repeat>>
, <<timed>>
. Generally, this means only when the variable's value will change between the time the asynchronous macro is invoked and when it's activated—e.g., a loop variable.
注意:仅在需要为异步宏(即内容将在稍后时间执行的宏)本地化变量值时使用此宏——即,在调用时而不是在调用时执行的宏;例如,交互式宏, <<repeat>>
, <<timed>>
。通常,这意味着只有当变量值在异步宏被调用和激活之间会发生变化时——例如,循环变量。
v2.14.0
: Introduced. v2.14.0
: 引入。variableList
: A list of story $variables and/or temporary _variables.variableList
: 故事变量和/或临时变量的列表。→ Using <<capture>> to localize a temporary loop variable for use within a <<linkappend>>
<<set _what to [
"a crab rangoon",
"a gaggle of geese",
"an aardvark",
"the world's smallest violin"
]>>
<<for _i to 0; _i lt _what.length; _i++>>
<<capture _i>>
I spy with my little <<linkappend "eye" t8n>>, _what[_i]<</linkappend>>.
<</capture>>
<</for>>
→ Capturing several variables at once
<<capture $aStoryVar, $anotherStoryVar, _aTempVar>> … <</capture>>
<<set expression>>
Sets story $variables and temporary _variables based on the given expression.
根据给定的表达式设置故事变量和临时变量。
v2.0.0
: Introduced. v2.0.0
: 引入。expression
: A valid expression. See Variables, Expressions, Operators for more information.expression
: 一个有效的表达式。请参阅变量、表达式、运算符以获取更多信息。<<set $cheese to "a nice, sharp cheddar">> → Assigns "a nice, sharp cheddar" to story variable $cheese
<<set $chestEmpty to true>> → Assigns boolean true to story variable $chestEmpty
<<set $sum to $a + $b>> → Assigns the summation of story variables $a and $b to $sum
<<set $gold to $gold + 5>> → Adds 5 to the value of story variable $gold
<<set _counter to _counter + 1>> → Adds 1 to the value of temporary variable _counter
<<set $cheese = "a nice, sharp cheddar">> → Assigns "a nice, sharp cheddar" to story variable $cheese
<<set $chestEmpty = true>> → Assigns boolean true to story variable $chestEmpty
<<set $sum = $a + $b>> → Assigns the summation of story variables $a and $b to $sum
<<set $gold += 5>> → Adds 5 to the value of story variable $gold
<<set _counter += 1>> → Adds 1 to the value of temporary variable _counter
<<unset variableList>>
Unsets story $variables, temporary _variables, and properties of objects stored within either.
取消设置故事变量、临时变量以及存储在其中的对象的属性
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Added ability to unset object properties.variableList
: A list of story $variables, temporary variables, or properties of objects stored within either.variableList
: 存储在故事变量、临时变量或对象属性中的列表。Basic usage, unsetting story and temporary variables.
基本用法,取消设置故事和临时变量。
<<unset $rumors>>
<<unset _npc>>
<<unset $rumors, _npc, _choices, $job>>
Unsetting object properties.
取消设置对象属性。
<<unset _choices.b>>
<<unset $towns['port ulster'].rumors>>
<<unset _choices.b, $towns['port ulster'].rumors, $pc.notes, _park.rides['wheel of death']>>
<<run expression>>
Functionally identical to <<set>>
. Intended to be mnemonically better for uses where the expression is arbitrary code, rather than variables to set—i.e., <<run>>
to run code, <<set>>
to set variables.
与 <<set>>
功能相同。旨在在表达式为任意代码而非设置变量时提供更好的记忆性——即 <<run>>
运行代码, <<set>>
设置变量。
<<script [language]>> … <</script>>
Silently executes its contents as either JavaScript or TwineScript code (default: JavaScript).
静默执行其内容作为 JavaScript 或 TwineScript 代码(默认:JavaScript)。
Note:
The predefined variable output
, which is a reference to a local content buffer, is available for use within the macro's code contents. Once the code has been fully executed, the contents of the buffer, if any, will be output.
注意:预定义变量 output
,它是对本地内容缓冲区的引用,可以在宏的代码内容中使用。一旦代码完全执行,缓冲区的内容(如果有)将被输出。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Added optional language
argument.v2.37.0
:添加了可选的 language
参数。language
: (optional) The language to evaluate the given code as; case-insensitive options: JavaScript
, TwineScript
. If omitted, defaults to JavaScript
.JavaScript
, TwineScript
。如果省略,则默认为 JavaScript
。<<script>>
/* JavaScript code */
<</script>>
<<script TwineScript>>
/* TwineScript code */
<</script>>
<<script>>
/*
When accessing managed variables in JavaScript, it's often a good idea
to cache references to whichever variable store you happen to be using.
*/
const svars = State.variables;
const tvars = State.temporary;
/* Access the `$items` story variable. */
if (svars.items.includes('bloody knife')) {
/* Has a bloody knife. */
}
/* Access the `_hit` temporary variable. */
tvars.hit += 1;
<</script>>
<<script TwineScript>>
/* Access the `$items` story variable. */
if ($items.includes('bloody knife')) {
/* Has a bloody knife. */
}
/* Access the `_hit` temporary variable. */
_hit += 1;
<</script>>
There's no difference between JavaScript and TwineScript here.
在这里,JavaScript 和 TwineScript 没有区别。
<<script>>
/* Parse some markup and append the result to the output buffer. */
$(output).wiki("Cry 'Havoc!', and let slip the //ponies// of ''friendship''.");
<</script>>
<<= expression>>
Outputs a string representation of the result of the given expression. This macro is an alias for <<print>>
.
输出给定表达式的字符串表示形式。此宏是 <<print>>
的别名。
Tip:
If you only need to print the value of a TwineScript variable, then you may simply include it in your normal passage text and it will be printed automatically via the naked variable markup.
提示:如果您只需要打印 TwineScript 变量的值,那么您可以直接将其包含在正常段落文本中,它将通过裸变量标记自动打印。
v2.0.0
: Introduced. v2.0.0
: 引入。expression
: A valid expression. See Expressions for more information.expression
:一个有效的表达式。有关更多信息,请参阅表达式。→ Assuming $gold is 5
You found <<= $gold>> gold. → Outputs: You found 5 gold.
→ Assuming $weight is 74.6466266
You weigh <<= $weight.toFixed(2)>> kg. → Outputs: You weigh 74.65 kg.
<<- expression>>
Outputs a string representation of the result of the given expression. This macro is functionally identical to <<print>>
, save that it also encodes HTML special characters in the output.
输出给定表达式的字符串表示形式。此宏在功能上与 <<print>>
相同,区别在于它还会在输出中编码 HTML 特殊字符。
Tip:
If you only need to print the value of a TwineScript variable, then you may simply include it in your normal passage text and it will be printed automatically via the naked variable markup.
TIP:如果您只需要打印 TwineScript 变量的值,那么您只需将其包含在正常的段落文本中,它将通过裸变量标记自动打印。
v2.0.0
: Introduced. v2.0.0
: 引入。expression
: A valid expression. See Expressions for more information.expression
:一个有效的表达式。有关更多信息,请参阅表达式。→ Assuming $gold is 5
You found <<- $gold>> gold. → Outputs: You found 5 gold.
→ Assuming $weight is 74.6466266
You weigh <<- $weight.toFixed(2)>> kg. → Outputs: You weigh 74.65 kg.
<<do [tag tags] [element tag]>> … <</do>>
Displays its contents. Listens for <<redo>>
macro commands upon which it updates its contents.
显示其内容。监听 <<redo>>
宏命令,根据这些命令更新其内容。
v2.37.0
: Introduced. v2.37.0
: 引入。tag
tags
: (optional) The space separated list of tags used to filter <<redo>>
commands.tag
tags
:(可选)用于过滤 <<redo>>
命令的空格分隔的标签列表。element
tag
: (optional) The element to use as the content container—e.g., div
and span
. If omitted, defaults to span
.element
tag
:(可选)用作内容容器的元素——例如, div
和 span
。如果省略,则默认为 span
。<<set $money to 10>>
''Money:'' <<do>>$money<</do>>
<<link "Update money display">>
<<set $money += 10>>
<<redo>>
<</link>>
<<set $key to "">> /* no key */
<<do>>
<<if $key>>
You have the $key key.
<<else>>
You do not have a key.
<</if>>
<</do>>
<<link "Update key display">>
<<set $key to ["", "red", "blue", "skull"].random()>>
<<redo>>
<</link>>
''Foo:'' <<do tag "foo foobar">><<= ["fee", "fie", "foe", "fum"].random()>><</do>>
''Bar:'' <<do tag "bar foobar">><<= ["alfa", "bravo", "charlie", "delta"].random()>><</do>>
<<link "Update foo">>
<<redo "foo">>
<</link>>
<<link "Update bar">>
<<redo "bar">>
<</link>>
<<link "Update foo & bar (1)">>
<<redo "foo bar">>
<</link>>
<<link "Update foo & bar (2)">>
<<redo "foobar">>
<</link>>
<<include passageName [elementName]>>
<<include linkMarkup [elementName]>>
Outputs the contents of the passage with the given name, optionally wrapping it within an HTML element. May be called either with the passage name or with a link markup.
输出具有给定名称的段落内容,可选地将其包裹在 HTML 元素中。可以使用段落名称或链接标记来调用。
v2.15.0
: Introduced. v2.15.0
: 引入。passageName
: The name of the passage to include.passageName
: 要包含的段落的名称。elementName
: (optional) The HTML element to wrap the included passage in. If used, the element will include the passage's name normalized into a class name. See CSS passage conversions for more information.elementName
: (可选)包裹包含的段落的 HTML 元素。如果使用,则该元素将包含段落的名称,并将其规范化为类名。有关更多信息,请参阅 CSS 段落转换。linkMarkup
: The link markup to use (regular syntax only, no setters).elementName
: Identical to the passage name form.<<include "Go West">> → Include the passage "Go West"
<<include [[Go West]]>> → Include the passage "Go West"
<<include "Go West" "div">> → Include the passage "Go West", wrapping it within a <div>
<<include [[Go West]] "div">> → Include the passage "Go West", wrapping it within a <div>
<<nobr>> … <</nobr>>
Executes its contents and outputs the result, after removing leading/trailing newlines and replacing all remaining sequences of newlines with single spaces.
执行其内容并输出结果,在删除首尾换行符后,将所有剩余的换行序列替换为单个空格。
Note:
The nobr
special tag and Config.passages.nobr
setting applies the same processing to an entire passage or all passages, respectively. The line continuation markup performs a similar function, though in a slightly different way.
注意: nobr
特殊标记和 Config.passages.nobr
设置将对整个段落或所有段落应用相同的处理。行续标记执行类似功能,但方式略有不同。
v2.0.0
: Introduced. v2.0.0
: 引入。→ Given: $feeling eq "blue", outputs: I'd like a blueberry pie.
I'd like a <<nobr>>
<<if $feeling eq "blue">>
blueberry
<<else>>
cherry
<</if>>
<</nobr>> pie.
<<print expression>>
Outputs a string representation of the result of the given expression.
输出给定表达式的字符串表示形式。
Tip:
If you only need to print the value of a TwineScript variable, then you may simply include it in your normal passage text and it will be printed automatically via the naked variable markup.
提示:如果您只需要打印 TwineScript 变量的值,那么您可以直接将其包含在正常段落文本中,它将通过裸变量标记自动打印。
v2.0.0
: Introduced. v2.0.0
: 引入。expression
: A valid expression. See Expressions for more information.expression
:一个有效的表达式。有关更多信息,请参阅表达式。→ Assuming $gold is 5
You found <<print $gold>> gold. → Outputs: You found 5 gold.
→ Assuming $weight is 74.6466266
You weigh <<print $weight.toFixed(2)>> kg. → Outputs: You weigh 74.65 kg.
<<redo [tags]>>
Causes one or more <<do>>
macros to update their contents.
导致一个或多个 <<do>>
宏更新其内容。
v2.37.0
: Introduced. v2.37.0
: 引入。tags
: (optional) The space separated list of tags corresponding to tagged <<do>>
macros to send update commands to. If omitted, sends update commands to all <<do>>
macros.<<do>>
宏对应的空格分隔的标签列表,用于发送更新命令。如果省略,则向所有 <<do>>
宏发送更新命令。See:
<<do>>
macro for examples.
查看: <<do>>
宏示例。
<<silent>> … <</silent>>
Causes any output generated within its body to be discarded, except for errors (which will be displayed). Generally, only really useful for formatting blocks of macros for ease of use/readability, while ensuring that no output is generated, from spacing or whatnot.
导致其体内生成的任何输出都被丢弃,除了错误(将显示)。通常,仅对格式化宏块以方便使用/可读性非常有用,同时确保不生成任何输出,从间距等。
v2.37.0
: Introduced. v2.37.0
: 引入。→ Basic
<<silent>>
You'll never see any of this!
<</silent>>
→ Hiding the guts of a countdown timer
<<set $seconds to 10>>\
Countdown: <span id="countdown">$seconds seconds remaining</span>!\
<<silent>>
<<repeat 1s>>
<<set $seconds to $seconds - 1>>
<<if $seconds gt 0>>
<<replace "#countdown">>$seconds seconds remaining<</replace>>
<<else>>
<<replace "#countdown">>Too Late<</replace>>
/* do something useful here */
<<stop>>
<</if>>
<</repeat>>
<</silent>>
<<type speed [start delay] [class classes] [element tag] [id ID] [keep|none] [skipkey key]>>
…
<</type>>
Outputs its contents a character—technically, a code point—at a time, mimicking a teletype/typewriter. Can type most content: links, markup, macros, etc.
输出其内容,一个字符——技术上,一个码点——一次,模仿电传打字机/打字机。可以输入大多数内容:链接、标记、宏等。
Warning:
Interactions with macros or other code that inject content only after some external action or period—e.g., <<linkreplace>>
, <<timed>>
, etc.—may or may not behave as you'd expect. Testing is strongly advised.
警告:与在某个外部动作或一段时间后仅注入内容的宏或其他代码(例如, <<linkreplace>>
, <<timed>>
等)的交互可能不会按预期行为。强烈建议进行测试。
See Also:
Config.macros.typeSkipKey
, Config.macros.typeVisitedPassages
, <<type>>
Events.
参见: Config.macros.typeSkipKey
, Config.macros.typeVisitedPassages
, <<type>>
事件。
v2.32.0
: Introduced. v2.32.0
: 引入。v2.33.0
: Added class
, element
, and id
options and macro-type-done
class.v2.33.0
:添加了 class
, element
, id
选项和 macro-type-done
类。v2.33.1
: Added skipkey
option.v2.33.1
:添加了 skipkey
选项。v2.37.0
: Updated speed
argument so 0s
and 0ms
skip.v2.37.0
:更新了 speed
参数,使 0s
和 0ms
跳过。speed
: The rate at which characters are typed, as a valid CSS time value—e.g., 1s
and 40ms
. Values in the range 20–60ms
are a good starting point. Values of 0s
and 0ms
cause typing to finish immediately.1s
和 40ms
。范围 20–60ms
的值是一个良好的起点。 0s
和 0ms
的值会导致打字立即完成。start
delay
: (optional) The amount of time to delay the start of typing, as a valid CSS time value—e.g., 5s
and 500ms
. If omitted, defaults to 400ms
.start
delay
:(可选)延迟打字开始的时间,作为有效的 CSS 时间值——例如, 5s
和 500ms
。如果省略,则默认为 400ms
。class
classes
: (optional) The space separated list of classes to be added to the typing container.class
classes
:(可选)要添加到打字容器的类名列表,空格分隔。element
tag
: (optional) The element to use as the typing container—e.g., div
and span
. If omitted, defaults to div
.element
tag
:(可选)用作打字容器的元素——例如, div
和 span
。如果省略,则默认为 div
。id
ID
: (optional) The unique ID to be assigned to the typing container.keep
: (optional) Keyword, used to signify that the cursor should be kept after typing is complete.keep
:(可选)关键字,用于表示在输入完成后应保留光标。none
: (optional) Keyword, used to signify that the cursor should not be used at all.none
: (可选)关键字,用于表示光标不应使用。skipkey
: (optional) The key used to cause typing to finish immediately. If omitted, defaults to the value of Config.macros.typeSkipKey
.skipkey
: (可选)用于立即结束输入的键。如果省略,则默认为 Config.macros.typeSkipKey
的值。<<type 40ms>>
Type characters from this content every 40 milliseconds. Including [[links]] and ''other markup''!
<</type>>
<<type 40ms start 2s>>
Type characters from this content every 40 milliseconds, starting after a 2 second delay.
<</type>>
<<type 40ms class "foo bar">>
Type characters from this content every 40 milliseconds, adding classes to the typing container.
<</type>>
<<type 40ms element "span">>
Type characters from this content every 40 milliseconds, using a <span> as the typing container.
<</type>>
<<type 40ms id "type01">>
Type characters from this content every 40 milliseconds, assigning an ID to the typing container.
<</type>>
<<type 40ms keep>>
Type characters from this content every 40 milliseconds, keeping the cursor after typing is complete.
<</type>>
<<type 40ms skipkey "Control">>
Type characters from this content every 40 milliseconds, using the Control (CTRL) key as the skip key.
<</type>>
The typed text has no default styling. If you want to change the font or color, then you'll need to change the styling of the macro-type
class. For example:
打字文本默认没有样式。如果您想更改字体或颜色,则需要更改 macro-type
类的样式。例如:
.macro-type {
color: limegreen;
font-family: monospace, monospace;
}
There's also a macro-type-done
class that is added to text that has finished typing, which may be used to style it differently from actively typing text.
此外,还有一个 macro-type-done
类会被添加到已完成的打字文本上,可以用来将其与正在打字的文本进行不同的样式处理。
The default cursor is the block element character Right Half Block (U+2590) and it has no default font or color styling. If you want to change the font, color, or character, then you'll need to change the styling of the :after
pseudo-element of the macro-type-cursor
class. For example:
默认光标是字符块元素右半块(U+2590),它没有默认的字体或颜色样式。如果您想更改字体、颜色或字符,则需要更改 macro-type-cursor
类的 :after
伪元素的样式。例如:
.macro-type-cursor:after {
color: limegreen;
content: "\269C\FE0F"; /* Fleur-de-lis emoji */
font-family: monospace, monospace;
}
<<silently>> … <</silently>>
Deprecated:
This macro has been deprecated and should no longer be used. See the <<silent>>
macro for its replacement.
已弃用:此宏已被弃用,不应再使用。请参阅 <<silent>>
宏以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of <<silent>>
.<<silent>>
。<<if conditional>> … [<<elseif conditional>> …] [<<else>> …] <</if>>
Executes its contents if the given conditional expression evaluates to true
. If the condition evaluates to false
and an <<elseif>>
or <<else>>
exists, then other contents can be executed.
如果给定的条件表达式评估为 true
,则执行其内容。如果条件评估为 false
,并且存在 <<elseif>>
或 <<else>>
,则可以执行其他内容。
Note:
SugarCube does not trim whitespace from the contents of <<if>>
macros, so that authors don't have to resort to various kludges to get whitespace where they want it. This means, however, that extra care must be taken when writing them to ensure that unwanted whitespace is not created within the final output.
注意:SugarCube 不会从 <<if>>
宏的内容中删除空白字符,这样作者就不必求助于各种技巧来获取他们想要的空白字符。然而,这也意味着在编写时必须格外小心,以确保最终输出中不会产生不想要的空白字符。
v2.0.0
: Introduced. v2.0.0
: 引入。conditional
: A valid conditional expression, evaluating to either true
or false
. See Expressions and Operators for more information.true
或 false
。请参阅表达式和运算符以获取更多信息。<<if $daysUntilLoanDue is 0>><<include "Panic">><</if>>
<<if $cash lt 5>>
I'm sorry, ma'am, but you don't have enough for the pie.
<<else>>
<<set $cash -= 5, $hasMeatPie = true>>
One meat pie, fresh out of the oven, coming up!
<</if>>
<<if $affection gte 75>>
I love you!
<<elseif $affection gte 50>>
I like you.
<<elseif $affection gte 25>>
I'm okay with you.
<<else>>
Get out of my face.
<</if>>
<<if $hullBreached>>
<<if $wearingHardSuit>>
<<include "That was close">>
<<elseif $wearingSoftSuit>>
<<include "Hole in suit">>
<<else>>
<<include "You die">>
<</if>>
<</if>>
<<for [conditional]>> … <</for>>
<<for [init] ; [conditional] ; [post]>> … <</for>>
<<for [[keyVariable ,] valueVariable] range collection>> … <</for>>
Repeatedly executes its contents. There are three forms: a conditional-only form, a 3-part conditional form, and a range form.
反复执行其内容。有三种形式:仅条件形式、三部分条件形式和范围形式。
See Also:
<<break>>
and <<continue>>
.
参见: <<break>>
和 <<continue>>
。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.20.0
: Added range form.v2.37.0
: Added range over integers and made range value variable optional._i
._i
。Executes its contents while the given conditional expression evaluates to true
. If no conditional expression is given, it is equivalent to specifying true
.
当给定的条件表达式评估为 true
时执行其内容。如果没有提供条件表达式,则相当于指定 true
。
Note:
The maximum number of loop iterations in the conditional forms is not unlimited by default, however, it is configurable. See Config.macros.maxLoopIterations
for more information.
注意:默认情况下,条件表单中的最大循环迭代次数不是无限的,但是可以配置。请参阅 Config.macros.maxLoopIterations
获取更多信息。
init
: (optional) A valid expression, evaluated once at loop initialization. Typically used to initialize counter variable(s). See <<set>>
for more information.init
:(可选)一个有效的表达式,在循环初始化时评估一次。通常用于初始化计数器变量。有关更多信息,请参阅 <<set>>
。conditional
: (optional) A valid conditional expression, evaluated prior to each loop iteration. As long as the expression evaluates to true
, the loop is executed. See <<if>>
for more information.conditional
:(可选)一个有效的条件表达式,在每个循环迭代之前进行评估。只要表达式评估为 true
,循环就会执行。有关更多信息,请参阅 <<if>>
。post
: (optional) A valid expression, evaluated after each loop iteration. Typically used to update counter variable(s). See <<set>>
for more information.post
: (可选)一个有效的表达式,在每个循环迭代后评估。通常用于更新计数器变量。有关更多信息,请参阅 <<set>>
。→ Example setup
<<set $dwarves to ["Doc", "Dopey", "Bashful", "Grumpy", "Sneezy", "Sleepy", "Happy"]>>
→ Loop
<<for _i to 0; _i lt $dwarves.length; _i++>>
<<print _i + 1>>. $dwarves[_i]
<</for>>
→ Result
1. Doc
2. Dopey
3. Bashful
4. Grumpy
5. Sneezy
6. Sleepy
7. Happy
Iterates through all enumerable entries of the given collection. For each iteration, it assigns the key/value pair of the associated entry in the collection to the iteration variables and then executes its contents. Valid collection types are: arrays, generic objects, integers, maps, sets, and strings.
遍历给定集合的所有可枚举条目。对于每次迭代,它将集合中相关条目的键/值对分配给迭代变量,然后执行其内容。有效的集合类型包括:数组、泛型对象、整数、映射、集合和字符串。
keyVariable
: (optional) A story or temporary variable that will be set to the iteration key.valueVariable
: (optional) A story or temporary variable that will be set to the iteration value.range
: Keyword, used to signify that the loop is using the range form syntax.collection
: An expression that yields a valid collection type, evaluated once at loop initialization.Collection type 收藏类型 | Iteration: key, value 迭代:键,值 |
---|---|
Arrays, Integers, & Sets 数组、整数和集合 |
Member: index, value 成员:索引,值 |
Generic objects 泛型对象 | Property: name, value 属性:名称,值 |
Maps 映射 | Entry: key, value 条目:键,值 |
Strings 字符串 | Code point: start index, value 代码点:起始索引,值 |
Note:
Strings are iterated by Unicode code point, however, due to historic reasons they are comprised of, and indexed by, individual UTF-16 code units. This means that some code points may span multiple code units—e.g., the character 💩 is one code point, but two code units.
注意:字符串按 Unicode 代码点迭代,但由于历史原因,它们由单个 UTF-16 代码单元组成,并按单个代码单元索引。这意味着某些代码点可能跨越多个代码单元——例如,字符💩是一个代码点,但由两个代码单元组成。
→ Example setup
<<set $dwarves to ["Doc", "Dopey", "Bashful", "Grumpy", "Sneezy", "Sleepy", "Happy"]>>
→ Loop
<<for _i, _name range $dwarves>>
<<print _i + 1>>. _name
<</for>>
→ Result
1. Doc
2. Dopey
3. Bashful
4. Grumpy
5. Sneezy
6. Sleepy
7. Happy
→ Loop
<<for _value range 7>>
<<print _value + 1>>.
<</for>>
→ Result
1.
2.
3.
4.
5.
6.
7.
<<break>>
Used within <<for>>
macros. Terminates the execution of the current <<for>>
.
在 <<for>>
宏中使用。终止当前 <<for>>
的执行。
v2.0.0
: Introduced. v2.0.0
: 引入。<<continue>>
Used within <<for>>
macros. Terminates the execution of the current iteration of the current <<for>>
and begins execution of the next iteration.
用于 <<for>>
宏中。终止当前 <<for>>
的当前迭代执行,并开始执行下一个迭代。
Note:
May eat line-breaks in certain situations.
注意:在某些情况下可能会吃掉换行符。
v2.0.0
: Introduced. v2.0.0
: 引入。<<switch expression>>
[<<case valueList>> …]
[<<default>> …]
<</switch>>
Evaluates the given expression and compares it to the value(s) within its <<case>>
children. The value(s) within each case are compared to the result of the expression given to the parent <<switch>>
. Upon a successful match, the matching case will have its contents executed. If no cases match and an optional <<default>>
case exists, which must be the final case, then its contents will be executed. At most one case will execute.
评估给定的表达式,并将其与 <<case>>
子项中的值进行比较。每个案例中的值与提供给父项的表达式结果进行比较。如果匹配成功,则执行匹配的案例的内容。如果没有案例匹配,并且存在可选的 <<default>>
案例,则必须是最終案例,其内容将被执行。最多执行一个案例。
Note:
SugarCube does not trim whitespace from the contents of <<case>>
/<<default>>
macros, so that authors don't have to resort to various kludges to get whitespace where they want it. However, this means that extra care must be taken when writing them to ensure that unwanted whitespace is not created within the final output.
注意:SugarCube 不会从 <<case>>
/ <<default>>
宏的内容中删除空白字符,这样作者就不必求助于各种技巧来获取他们想要的空白字符。然而,这意味着在编写时必须格外小心,以确保最终输出中不会创建不想要的空白字符。
v2.7.2
: Introduced. v2.7.2
: 引入。<<switch>>
expression
: A valid expression. See Expressions for more information.expression
:一个有效的表达式。有关更多信息,请参阅表达式。<<case>>
valueList
: A space separated list of values to compare against the result of the switch expression.→ Without a default case
<<switch $hairColor>>
<<case "red" "auburn">>
You ginger.
<<case "black" "brown">>
Dark haired, eh?
<<case "blonde">>
You may have more fun.
<</switch>>
→ With a default case (assume the passage is about a waterfall)
<<switch visited()>>
<<case 1>>
You gaze in wonder at the magnificent waterfall for the first time, awestruck by its natural beauty.
<<case 2 3>>
You once again gaze upon the magnificent waterfall.
<<case 4 5>>
Yet again, you find yourself looking upon the waterfall.
<<default>>
Oh, look. It's that waterfall again. Meh.
<</switch>>
Interactive macros are both asynchronous and require interaction from the player. Thus, there are some potential pitfalls to consider:
交互式宏既是异步的,又需要玩家的交互。因此,有一些潜在的陷阱需要考虑:
<<capture>>
macro due to their asynchronous nature.<<capture>>
宏。<<button linkText [passageName]>> … <</button>>
<<button linkMarkup>> … <</button>>
<<button imageMarkup>> … <</button>>
Creates a button that silently executes its contents when clicked, optionally forwarding the player to another passage. May be called with either the link text and passage name as separate arguments, a link markup, or an image markup.
创建一个按钮,当点击时,会静默执行其内容,并可选择将玩家转发到另一个段落。可以使用链接文本和段落名称作为单独的参数,也可以使用链接标记或图像标记来调用。
See:
Interactive macro warning.
查看:交互宏警告。
Note:
This macro is functionally identical to <<link>>, save that it uses a button element (<button>
) rather than an anchor element (<a>
).
注意:此宏在功能上与 <> 相同,区别在于它使用按钮元素( <button>
)而不是锚点元素( <a>
)。
v2.8.0
: Introduced. v2.8.0
: 引入。linkText
: The text of the link. May contain markup.linkText
:链接文本。可以包含标记。passageName
: (optional) The name of the passage to go to.passageName
:(可选)要跳转的段落名称。linkMarkup
: The link markup to use (regular syntax only, no setters).imageMarkup
: The image markup to use (regular syntax only, no setters).imageMarkup
: 要使用的图片标记(仅限常规语法,无设置器)。→ Without forwarding: a very basic statistic setting example
Strength: <<set $pcStr to 10>><span id="stats-str"><<print $pcStr>></span> \
( <<button "[+]">><<set $pcStr++>><<replace "#stats-str">><<print $pcStr>><</replace>><</button>> \
| <<button "[-]">><<set $pcStr-->><<replace "#stats-str">><<print $pcStr>><</replace>><</button>> )
→ With forwarding: execute a script, then go to the specified passage
<<button "Onward, Reginald!" "On with the story">><<script>>/* (code) */<</script>><</button>>
<<button [[Onward, Reginald!|On with the story]]>><<script>>/* (code) */<</script>><</button>>
<<button [img[onward.jpg][On with the story]]>><<script>>/* (code) */<</script>><</button>>
<<checkbox receiverName uncheckedValue checkedValue [autocheck|checked]>>
Creates a checkbox, used to modify the value of the variable with the given name.
创建一个复选框,用于修改给定名称的变量的值。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.32.0
: Added autocheck
keyword.v2.32.0
: 添加了 autocheck
关键字。receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
.receiverName
: 要修改的变量名称,必须加引号——例如, "$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。uncheckedValue
: The value set by the checkbox when unchecked.uncheckedValue
: 复选框未选中时设置的值。checkedValue
: The value set by the checkbox when checked.checkedValue
: 复选框选中时设置的值。autocheck
: (optional) Keyword, used to signify that the checkbox should be automatically set to the checked state based on the current value of the receiver variable. NOTE: Automatic checking may fail on non-primitive values—i.e., on arrays and objects.autocheck
:(可选)关键字,用于表示复选框应根据接收变量的当前值自动设置为选中状态。注意:自动选中可能无法在非原始值上(例如数组和对象)成功。checked
: (optional) Keyword, used to signify that the checkbox should be in the checked state.checked
:(可选)关键字,用于表示复选框应处于选中状态。What pies do you enjoy?
* <<checkbox "$pieBlueberry" false true autocheck>> Blueberry?
* <<checkbox "$pieCherry" false true autocheck>> Cherry?
* <<checkbox "$pieCoconutCream" false true autocheck>> Coconut cream?
What pies do you enjoy?
* <<checkbox "$pieBlueberry" false true checked>> Blueberry?
* <<checkbox "$pieCherry" false true>> Cherry?
* <<checkbox "$pieCoconutCream" false true checked>> Coconut cream?
<label>
element 使用 <label>
元素Tip:
For accessibility reasons, it's recommended that you wrap each <<checkbox>>
and its accompanying text within a <label>
element. Doing so allows interactions with the text to also trigger its <<checkbox>>
.
提示:出于可访问性的考虑,建议将每个 <<checkbox>>
及其伴随的文本包裹在 <label>
元素内。这样做可以使与文本的交互同时触发其 <<checkbox>>
。
What pies do you enjoy?
* <label><<checkbox "$pieBlueberry" false true autocheck>> Blueberry?</label>
* <label><<checkbox "$pieCherry" false true autocheck>> Cherry?</label>
* <label><<checkbox "$pieCoconutCream" false true autocheck>> Coconut cream?</label>
What pies do you enjoy?
* <label><<checkbox "$pieBlueberry" false true checked>> Blueberry?</label>
* <label><<checkbox "$pieCherry" false true>> Cherry?</label>
* <label><<checkbox "$pieCoconutCream" false true checked>> Coconut cream?</label>
<<cycle receiverName [once] [autoselect]>>
[<<option label [value [selected]]>> …]
[<<optionsfrom collection>> …]
<</cycle>>
Creates a cycling link, used to modify the value of the variable with the given name. The cycling options are populated via <<option>>
and/or <<optionsfrom>>
.
创建循环链接,用于修改给定名称的变量的值。循环选项通过 <<option>>
和/或 <<optionsfrom>>
填充。
See:
Interactive macro warning.
查看:交互宏警告。
v2.29.0
: Introduced. v2.29.0
: 引入。v2.36.0
: Fixed the selected
keyword and added the once
keyword.v2.36.0
: 修复了 selected
关键字并添加了 once
关键字。<<cycle>>
receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
."$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。once
: (optional) Keyword, used to signify that the cycle should stop upon reaching the last option and deactivate itself. NOTE: Since you likely want to start at the first option when using this keyword, you should either not select an option, so it defaults to the first, or, if you do, select the first option only.once
(可选)关键字,用于表示在达到最后一个选项时停止循环并使其失效。注意:由于您可能希望在使用此关键字时从第一个选项开始,因此您可以选择不选择任何选项,使其默认为第一个,或者,如果您确实选择了,请只选择第一个选项。autoselect
: (optional) Keyword, used to signify that an option should be automatically selected as the cycle default based on the current value of the receiver variable. NOTE: Automatic option selection will fail on non-primitive values—i.e., on arrays and objects.autoselect
(可选)关键字,用于表示应根据接收器变量的当前值自动选择一个选项作为循环的默认值。注意:自动选项选择将失败于非原始值——即数组和对象。<<option>>
label
: The label shown by the cycling link for the option.label
循环链接显示的选项标签。value
: (optional) The value set by the cycling link when the option is selected. If omitted, the label will be used as the value.value
: (可选)当选择选项时,循环链接设置的值。如果省略,则使用标签作为值。selected
: (optional) Keyword, used to signify that the option should be the cycle default. Only one option may be so selected. If no options are selected as the default, the cycling link will default to the first option, unless the cycle autoselect
keyword is specified. NOTE: If specified, the value
argument is not optional.selected
: (可选)关键字,用于表示该选项应为循环默认值。只能选择一个选项作为默认值。如果没有选项被选为默认值,则循环链接将默认为第一个选项,除非指定了循环 autoselect
关键字。注意:如果指定,则 value
参数不是可选的。<<optionsfrom>>
collection
: An expression that yields a valid collection type.
collection
: 一个产生有效集合类型的表达式。Collection type 收藏类型 | Option: label, value 选项:标签,值 |
---|---|
Arrays & Sets 数组和集合 | Member: value, value 成员:值,值 |
Generic objects 通用对象 | Property: name, value 属性:名称,值 |
Maps 映射 | Entry: key, value 条目:键,值 |
<<option>>
使用 <<option>>
The answer to the //Ultimate Question of Life, the Universe, and Everything// is?
<<cycle "$answer" autoselect>>
<<option "Towel">>
<<option "π" 3.14159>>
<<option 42>>
<<option 69>>
<<option "∞" Infinity>>
<</cycle>>
<<optionsfrom>>
with an array<<optionsfrom>>
与数组→ Given: _pieOptions = ["blueberry", "cherry", "coconut cream"]
What's your favorite pie?
<<cycle "$pie" autoselect>>
<<optionsfrom _pieOptions>>
<</cycle>>
<<optionsfrom>>
with an generic object<<optionsfrom>>
与通用对象→ Given: _pieOptions = { "Blueberry" : "blueberry", "Cherry" : "cherry", "Coconut cream" : "coconut cream" }
What's your favorite pie?
<<cycle "$pie" autoselect>>
<<optionsfrom _pieOptions>>
<</cycle>>
once
keyword 使用 once
关键字You see a large red, candy-like button.
<<cycle "$presses" once>>
<<option "Should you press it?" 0>>
<<option "Nothing happened. Press it again?" 1>>
<<option "Again?" 2>>
<<option "That time it locked into place with a loud click and began to glow ominously." 3>>
<</cycle>>
<<link linkText [passageName]>> … <</link>>
<<link linkMarkup>> … <</link>>
<<link imageMarkup>> … <</link>>
Creates a link that silently executes its contents when clicked, optionally forwarding the player to another passage. May be called with either the link text and passage name as separate arguments, a link markup, or an image markup.
创建一个在点击时静默执行其内容的链接,可选地将玩家转发到另一个段落。可以使用链接文本和段落名称作为单独的参数,或使用链接标记或图像标记来调用。
See:
Interactive macro warning.
查看:交互宏警告。
Note:
If you simply need a passage link that modifies variables, both the link markup and image markup offer setter variants.
注意:如果您只需要一个修改变量的段落链接,链接标记和图像标记都提供设置器变体。
v2.8.0
: Introduced. v2.8.0
: 引入。linkText
: The text of the link. May contain markup.linkText
:链接文本。可以包含标记。passageName
: (optional) The name of the passage to go to.passageName
:(可选)要跳转的段落名称。linkMarkup
: The link markup to use (regular syntax only, no setters).imageMarkup
: The image markup to use (regular syntax only, no setters).→ Without forwarding: a very basic statistic setting example
Strength: <<set $pcStr to 10>><span id="stats-str"><<print $pcStr>></span> \
( <<link "[+]">><<set $pcStr++>><<replace "#stats-str">><<print $pcStr>><</replace>><</link>> \
| <<link "[-]">><<set $pcStr-->><<replace "#stats-str">><<print $pcStr>><</replace>><</link>> )
→ With forwarding: execute a script, then go to the specified passage
<<link "Onward, Reginald!" "On with the story">><<script>>/* (code) */<</script>><</link>>
<<link [[Onward, Reginald!|On with the story]]>><<script>>/* (code) */<</script>><</link>>
<<link [img[onward.jpg][On with the story]]>><<script>>/* (code) */<</script>><</link>>
<<linkappend linkText [transition|t8n]>> … <</linkappend>>
Creates a single-use link that deactivates itself and appends its contents to its link text when clicked. Essentially, a combination of <<link>>
and <<append>>
.
创建一个一次性链接,点击后会自动失效,并将内容附加到链接文本中。本质上,是 <<link>>
和 <<append>>
的结合。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。linkText
: The text of the link. May contain markup.linkText
:链接文本。可以包含标记。transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ Without a transition
We—We should <<linkappend "take">> away their METAL BAWKSES<</linkappend>>!
→ With a transition
I spy with my little <<linkappend "eye" t8n>>, a crab rangoon<</linkappend>>.
<<linkprepend linkText [transition|t8n]>> … <</linkprepend>>
Creates a single-use link that deactivates itself and prepends its contents to its link text when clicked. Essentially, a combination of <<link>>
and <<prepend>>
.
创建一个一次性链接,点击后会自动失效,并将内容添加到链接文本前。本质上,是 <<link>>
和 <<prepend>>
的组合。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。linkText
: The text of the link. May contain markup.linkText
:链接文本。可以包含标记。transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ Without a transition
You see a <<linkprepend "robot">>GIANT <</linkprepend>>.
→ With a transition
I <<linkprepend "like" t8n>>do not <</linkprepend>> lemons.
<<linkreplace linkText [transition|t8n]>> … <</linkreplace>>
Creates a single-use link that deactivates itself and replaces its link text with its contents when clicked. Essentially, a combination of <<link>>
and <<replace>>
.
创建一个一次性链接,点击后会自动失效,并将链接文本替换为其内容。本质上,是 <<link>>
和 <<replace>>
的结合。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。linkText
: The text of the link. May contain markup.linkText
:链接文本。可以包含标记。transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ Without a transition
I'll have a <<linkreplace "cupcake">>slice of key lime pie<</linkreplace>>, please.
→ With a transition
<<linkreplace "You'll //never// take me alive!" t8n>>On second thought, don't hurt me.<</linkreplace>>
<<listbox receiverName [autoselect]>>
[<<option label [value [selected]]>> …]
[<<optionsfrom collection>> …]
<</listbox>>
Creates a listbox, used to modify the value of the variable with the given name. The list options are populated via <<option>>
and/or <<optionsfrom>>
.
创建一个列表框,用于修改给定名称的变量的值。列表选项通过 <<option>>
和/或 <<optionsfrom>>
填充。
See:
Interactive macro warning.
查看:交互宏警告。
v2.26.0
: Introduced. v2.26.0
: 引入。v2.27.0
: Added autoselect
keyword.v2.27.0
: 添加了 autoselect
关键字。v2.28.0
: <<optionsFrom>>
child tag.v2.28.0
: 添加了 <<optionsFrom>>
子标签。v2.28.1
: Fixed name of <<optionsfrom>>
child tag, which was erroneously added as <<optionsFrom>>
in v2.28.0
.v2.28.1
: 修正了 <<optionsfrom>>
子标签的名称,该名称错误地添加为 <<optionsFrom>>
,在 v2.28.0
中。v2.29.0
: Made the <<option>>
child tag's value
argument optional.v2.29.0
: 将 <<option>>
子标签的 value
参数设置为可选。v2.36.0
: Fixed the selected
keyword.v2.36.0
: 修正了 selected
关键字。<<listbox>>
receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
."$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。autoselect
: (optional) Keyword, used to signify that an option should be automatically selected as the listbox default based on the current value of the receiver variable. NOTE: Automatic option selection will fail on non-primitive values—i.e., on arrays and objects.autoselect
: (可选)关键字,用于表示选项应根据接收器变量的当前值自动选中。注意:自动选项选择将失败于非原始值——即数组和对象。<<option>>
label
: The label shown by the listbox for the option.label
: 列表框显示的标签。value
: (optional) The value set by the listbox when the option is selected. If omitted, the label will be used as the value.value
: (可选) 当选项被选中时设置的值。如果省略,则标签将用作值。selected
: (optional) Keyword, used to signify that the option should be the listbox default. Only one option may be so selected. If no options are selected as the default, the listbox will default to the first option, unless the listbox autoselect
keyword is specified. NOTE: If specified, the value
argument is not optional.selected
: (可选) 关键字,用于表示该选项应为列表框的默认选项。只能选择一个选项作为默认选项。如果没有选项被选为默认选项,列表框将默认为第一个选项,除非指定了列表框 autoselect
关键字。注意:如果指定,则 value
参数不是可选的。<<optionsfrom>>
collection
: An expression that yields a valid collection type.
collection
: 一个产生有效集合类型的表达式。Collection type 收藏类型 | Option: label, value 选项:标签,值 |
---|---|
Arrays & Sets 数组和集合 | Member: value, value 成员:值,值 |
Generic objects 通用对象 | Property: name, value 属性:名称,值 |
Maps 映射 | Entry: key, value 条目:键,值 |
<<option>>
使用 <<option>>
The answer to the //Ultimate Question of Life, the Universe, and Everything// is?
<<listbox "$lbanswer" autoselect>>
<<option "Towel">>
<<option "π" 3.14159>>
<<option 42>>
<<option 69>>
<<option "∞" Infinity>>
<</listbox>>
<<optionsfrom>>
with an array<<optionsfrom>>
与数组→ Given: _pieOptions = ["blueberry", "cherry", "coconut cream"]
What's your favorite pie?
<<listbox "$pie" autoselect>>
<<optionsfrom _pieOptions>>
<</listbox>>
<<optionsfrom>>
with an generic object<<optionsfrom>>
与通用对象→ Given: _pieOptions = { "Blueberry" : "blueberry", "Cherry" : "cherry", "Coconut cream" : "coconut cream" }
What's your favorite pie?
<<listbox "$pie" autoselect>>
<<optionsfrom _pieOptions>>
<</listbox>>
<<numberbox receiverName defaultValue [passage] [autofocus]>>
Creates a number input box, used to modify the value of the variable with the given name, optionally forwarding the player to another passage.
创建一个数字输入框,用于修改给定名称的变量值,可选地引导玩家到另一个段落。
See:
Interactive macro warning.
查看:交互宏警告。
v2.32.0
: Introduced. v2.32.0
: 引入。receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
."$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。defaultValue
: The default value of the number box.defaultValue
: 数字框的默认值。passage
: (optional) The name of the passage to go to if the return/enter key is pressed. May be called either with the passage name or with a link markup.passage
: (可选) 按下回车键或 Enter 键将跳转到的段落名称。可以使用段落名称或链接标记进行调用。autofocus
: (optional) Keyword, used to signify that the number box should automatically receive focus. Only use the keyword once per page; attempting to focus more than one element is undefined behavior.autofocus
: (可选) 关键词,用于表示数字框应自动获得焦点。每个页面只能使用一次该关键词;尝试聚焦多个元素的行为是未定义的。→ Creates a number box that modifies $wager
Wager how much on Buttstallion in the race? <<numberbox "$wager" 100>>
→ Creates an automatically focused number box that modifies $wager
Wager how much on Buttstallion in the race? <<numberbox "$wager" 100 autofocus>>
→ Creates a number box that modifies $wager and forwards to the "Result" passage
Wager how much on Buttstallion in the race? <<numberbox "$wager" 100 "Result">>
→ Creates an automatically focused number box that modifies $wager and forwards to the "Result" passage
Wager how much on Buttstallion in the race? <<numberbox "$wager" 100 "Result" autofocus>>
<<radiobutton receiverName checkedValue [autocheck|checked]>>
Creates a radio button, used to modify the value of the variable with the given name. Multiple <<radiobutton>>
macros may be set up to modify the same variable, which makes them part of a radio button group.
创建一个单选按钮,用于修改给定名称的变量值。可以设置多个 <<radiobutton>>
宏来修改相同的变量,使它们成为单选按钮组的一部分。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.32.0
: Added autocheck
keyword.v2.32.0
: 添加了 autocheck
关键字。receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
."$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。checkedValue
: The value set by the radio button when checked.checkedValue
:单选按钮被选中时设置的值。autocheck
: (optional) Keyword, used to signify that the radio button should be automatically set to the checked state based on the current value of the receiver variable. NOTE: Automatic checking may fail on non-primitive values—i.e., on arrays and objects.autocheck
:(可选)关键字,用于表示单选按钮应根据接收器变量的当前值自动设置为选中状态。注意:自动选中可能无法在非原始值(例如数组和对象)上成功。checked
: (optional) Keyword, used to signify that the radio button should be in the checked state. NOTE: Only one radio button in a group—i.e., those using the same receiver variable—should be so checked.checked
:(可选)关键字,用于表示单选按钮应处于选中状态。注意:组中(即使用相同接收器变量的单选按钮)只能有一个单选按钮被选中。What's your favorite pie?
* <<radiobutton "$pie" "blueberry" autocheck>> Blueberry?
* <<radiobutton "$pie" "cherry" autocheck>> Cherry?
* <<radiobutton "$pie" "coconut cream" autocheck>> Coconut cream?
What's your favorite pie?
* <<radiobutton "$pie" "blueberry" checked>> Blueberry?
* <<radiobutton "$pie" "cherry">> Cherry?
* <<radiobutton "$pie" "coconut cream">> Coconut cream?
<label>
element 使用 <label>
元素Tip:
For accessibility reasons, it's recommended that you wrap each <<radiobutton>>
and its accompanying text within a <label>
element. Doing so allows interactions with the text to also trigger its <<radiobutton>>
.
提示:出于可访问性的考虑,建议将每个 <<radiobutton>>
及其伴随的文本包裹在 <label>
元素内。这样做可以使与文本的交互同时触发其 <<radiobutton>>
。
What's your favorite pie?
* <label><<radiobutton "$pie" "blueberry" autocheck>> Blueberry?</label>
* <label><<radiobutton "$pie" "cherry" autocheck>> Cherry?</label>
* <label><<radiobutton "$pie" "coconut cream" autocheck>> Coconut cream?</label>
What's your favorite pie?
* <label><<radiobutton "$pie" "blueberry" checked>> Blueberry?</label>
* <label><<radiobutton "$pie" "cherry">> Cherry?</label>
* <label><<radiobutton "$pie" "coconut cream">> Coconut cream?</label>
<<textarea receiverName defaultValue [autofocus]>>
Creates a multiline text input block, used to modify the value of the variable with the given name.
创建一个多行文本输入块,用于修改给定名称的变量的值。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
."$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。defaultValue
: The default value of the text block.defaultValue
:文本块的默认值。autofocus
: (optional) Keyword, used to signify that the text block should automatically receive focus. Only use the keyword once per page; attempting to focus more than one element is undefined behavior.autofocus
:(可选)关键字,用于表示该文本块应自动获得焦点。每个页面只能使用一次关键字;尝试聚焦多个元素是不确定的行为。→ Creates a text block that modifies $pieEssay
Write a short essay about pies:
<<textarea "$pieEssay" "">>
→ Creates an automatically focused text block that modifies $pieEssay
Write a short essay about pies:
<<textarea "$pieEssay" "" autofocus>>
<<textbox receiverName defaultValue [passage] [autofocus]>>
Creates a text input box, used to modify the value of the variable with the given name, optionally forwarding the player to another passage.
创建一个文本输入框,用于修改给定名称的变量值,可选地引导玩家跳转到另一个段落。
See:
Interactive macro warning.
查看:交互宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。receiverName
: The name of the variable to modify, which must be quoted—e.g., "$foo"
. Object and array property references are also supported—e.g., "$foo.bar"
, "$foo['bar']"
, & "$foo[0]"
."$foo"
。也支持对象和数组属性引用——例如, "$foo.bar"
, "$foo['bar']"
,& "$foo[0]"
。defaultValue
: The default value of the text box.passage
: (optional) The name of the passage to go to if the return/enter key is pressed. May be called either with the passage name or with a link markup.passage
: (可选) 按下回车键或 Enter 键将跳转到的段落名称。可以使用段落名称或链接标记进行调用。autofocus
: (optional) Keyword, used to signify that the text box should automatically receive focus. Only use the keyword once per page; attempting to focus more than one element is undefined behavior.autofocus
:(可选)关键字,用于表示文本框应自动获得焦点。每个页面只能使用一次关键字;尝试聚焦多个元素是不确定的行为。→ Creates a text box that modifies $pie
What's your favorite pie? <<textbox "$pie" "Blueberry">>
→ Creates an automatically focused text box that modifies $pie
What's your favorite pie? <<textbox "$pie" "Blueberry" autofocus>>
→ Creates a text box that modifies $pie and forwards to the "Cakes" passage
What's your favorite pie? <<textbox "$pie" "Blueberry" "Cakes">>
→ Creates an automatically focused text box that modifies $pie and forwards to the "Cakes" passage
What's your favorite pie? <<textbox "$pie" "Blueberry" "Cakes" autofocus>>
<<back [linkText [passageName]]>>
<<back linkMarkup>>
<<back imageMarkup>>
Creates a link that undoes past moments within the story history. May be called with, optional, the link text and passage name as separate arguments, a link markup, or an image markup.
创建一个链接,可以撤销故事历史中的过去时刻。可以带可选的链接文本和篇章名称作为单独的参数,也可以是链接标记或图像标记。
Note:
If you want to return to a previously visited passage, rather than undo a moment within the history, see the <<return>>
macro or the previous()
function.
备注:如果您想返回之前访问过的篇章,而不是撤销历史中的某个时刻,请参阅 <<return>>
宏或 previous()
函数。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Added optional passage name argument in separate argument form.v2.37.0
: 在单独的参数形式中添加了可选的篇章名称参数。linkText
: (optional if passageName
is not specified) The text of the link. May contain markup.linkText
:(可选,如果未指定 passageName
则有效)链接的文本。可以包含标记。passageName
: (optional) The name of the moment to undo to until it's reached.passageName
:(可选)撤销到指定时刻的名称,直到达到该时刻。linkMarkup
: The link markup to use (regular syntax only, no setters).imageMarkup
: The image markup to use (regular syntax only, no setters).Assume your story history consists of three moments:
假设你的故事历史由三个时刻组成:
A, B, [C]
N.b., the square brackets there denote the active moment.
注意,那里的方括号表示当前时刻。
Using <<back>>
once upon that history will change it to be thus:
使用 <<back>>
在那个历史中会将其更改为:
A, [B], C
I.e., the history was rolled back to the previous moment.
→ Creates a link that undoes the most recent moment, with default text
<<back>>
→ Creates a link that undoes the most recent moment, with text "Home."
<<back "Home.">>
→ Creates a link that undoes past moments until the most recent "HQ" moment is reached, with text "Home."
<<back "Home." "HQ">>
→ Creates a link that undoes past moments until the most recent "HQ" moment is reached, with default text
<<back [[HQ]]>>
→ Creates a link that undoes past moments until the most recent "HQ" moment is reached, with text "Home."
<<back [[Home.|HQ]]>>
→ Creates a link that undoes the most recent moment, with image "home.png"
<<back [img[home.png]]>>
→ Creates a link that undoes past moments until the most recent "HQ" moment is reached, with image "home.png"
<<back [img[home.png][HQ]]>>
<<return [linkText [passageName]]>>
<<return linkMarkup>>
<<return imageMarkup>>
Creates a link that navigates forward to a previously visited passage. May be called with, optional, the link text and passage name as separate arguments, a link markup, or an image markup.
创建一个导航到之前访问过的章节的链接。可以带有一个可选的链接文本和章节名称作为单独的参数,或者使用链接标记,或者使用图片标记。
Note:
If you want to undo previous moments within the history, rather than return to a passage, see the <<back>>
macro.
注意:如果您想撤销历史中的前几个时刻,而不是返回到某个章节,请参阅 <<back>>
宏。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Added optional passage name argument in separate argument form.v2.37.0
: 添加了可选的段落名称参数,以单独的参数形式。linkText
: (optional if passageName
is not specified) The text of the link. May contain markup.linkText
: (如果未指定 passageName
则为可选)链接的文本。可能包含标记。passageName
: (optional) The name of the passage to go to.passageName
:(可选)要跳转的段落名称。linkMarkup
: The link markup to use (regular syntax only, no setters).imageMarkup
: The image markup to use (regular syntax only, no setters).Note:
The versions that forward to a specific passage are largely unnecessary, as you could simply use a normal link, and exist solely for compatibility with the <<back>>
macro.
注意:将版本转发到特定段落的大多数情况都是不必要的,因为您可以直接使用普通链接,并且仅为了与 <<back>>
宏的兼容性而存在。
Assume your story history consists of three moments:
假设你的故事历史由三个时刻组成:
A, B, [C]
N.b., the square brackets there denote the active moment.
注意,那里的方括号表示当前时刻。
Using <<return>>
once upon that history will change it to be thus:
使用 <<return>>
在那个历史中会将其更改为:
A, B, C, [B]
I.e., a new moment, to the same passage as the previous moment, was added to the history.
即,在历史中添加了一个新的时刻,与上一个时刻相同。
→ Creates a link that forwards to the previous passage, with default text
<<return>>
→ Creates a link that forwards to the previous passage, with text "Home."
<<return "Home.">>
→ Creates a link that forwards to the "HQ" passage, with text "Home."
<<return "Home." "HQ">>
→ Creates a link that forwards to the "HQ" passage, with default text
<<return [[HQ]]>>
→ Creates a link that forwards to the "HQ" passage, with text "Home."
<<return [[Home.|HQ]]>>
→ Creates a link that forwards to the previous passage, with image "home.png"
<<return [img[home.png]]>>
→ Creates a link that forwards to the "HQ" passage, with image "home.png"
<<return [img[home.png][HQ]]>>
<<actions passageList>>
<<actions linkMarkupList>>
<<actions imageMarkupList>>
Deprecated:
This macro has been deprecated and should no longer be used.
已弃用:此宏已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。<<choice passageName [linkText]>>
<<choice linkMarkup>>
<<choice imageMarkup>>
Deprecated:
This macro has been deprecated and should no longer be used.
已弃用:此宏已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。
Warning:
All DOM macros require the elements to be manipulated to be on the page. As a consequence, you cannot use them directly within a passage to modify elements within said passage, since the elements they are targeting are still rendering, thus not yet on the page. You must, generally, use them with an interactive macro—e.g., <<link>>
macro—the <<done>>
macro, or within the PassageDone
special passage. Elements that are already part of the page, on the other hand, present no issues.
警告:所有 DOM 宏都需要要操作的元素在页面上。因此,您不能直接在段落中使用它们来修改段落内的元素,因为这些元素仍在渲染中,尚未在页面上。通常,您必须与交互式宏(例如, <<link>>
宏)、 <<done>>
宏或 PassageDone
特殊段落一起使用。另一方面,已经是页面一部分的元素则没有问题。
<<addclass selector classNames>>
Adds classes to the selected element(s).
添加类到所选元素(们)。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。selector
: The CSS/jQuery-style selector used to target element(s).selector
: 用于定位元素(s)的 CSS/jQuery 样式选择器。classNames
: The names of the classes, separated by spaces.classNames
: 类名,用空格分隔。<<addclass "body" "day rain">> → Add the classes "day" and "rain" to the <body> element
<<addclass "#pie" "cherry">> → Add the class "cherry" to the element with the ID "pie"
<<addclass ".joe" "angry">> → Add the class "angry" to all elements containing the class "joe"
<<append selector [transition|t8n]>> … <</append>>
Executes its contents and appends the output to the contents of the selected element(s).
执行其内容并将其输出追加到所选元素(s)的内容中。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.25.0
: Added transition
and t8n
keywords.v2.25.0
: 添加了 transition
和 t8n
关键字。selector
: The CSS/jQuery-style selector used to target element(s).selector
: 用于定位元素(s)的 CSS/jQuery 风格选择器。transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ Example setup
I saw a <span id="dog">dog</span>.
→ Append to the contents of the target element
<<link "Doing">>
<<append "#dog">> chasing a cat<</append>>
<</link>>
→ Result, after clicking
I saw a <span id="dog">dog chasing a cat</span>.
→ Example setup
I saw a <span id="dog">dog</span>.
→ Append to the contents of the target element
<<link "Doing">>
<<append "#dog" t8n>> chasing a cat<</append>>
<</link>>
→ Result, after clicking
I saw a <span id="dog">dog<span class="macro-append-insert"> chasing a cat</span></span>.
<<copy selector>>
Outputs a copy of the contents of the selected element(s).
输出所选元素的内容副本。
Warning:
Most interactive elements—e.g., passage links, interactive macros, etc.—cannot be properly copied via <<copy>>
. Attempting to do so will, usually, result in something that's non-functional.
警告:大多数交互式元素(例如,篇章链接、交互式宏等)无法通过 <<copy>>
正确复制。通常,这样做会导致无法正常工作的内容。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。selector
: The CSS/jQuery-style selector used to target element(s).→ Example setup
I'd like a <span id="snack-source">slice of Key lime pie</span>, please.
I'll have a <span id="snack-dest">breadstick</span>, thanks.
→ Replace the contents of the source target element with a copy of the destination target element
<<link "Have the same">>
<<replace "#snack-dest">><<copy "#snack-source">> too<</replace>>
<</link>>
→ Result, after the click
I'd like a <span id="snack-source">slice of Key lime pie</span>, please.
I'll have a <span id="snack-dest">slice of Key lime pie too</span>, thanks.
<<prepend selector [transition|t8n]>> … <</prepend>>
Executes its contents and prepends the output to the contents of the selected element(s).
执行其内容并将输出内容添加到所选元素(s)的内容之前。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.25.0
: Added transition
and t8n
keywords.transition
和 t8n
关键词。selector
: The CSS/jQuery-style selector used to target element(s).transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ Example setup
I saw a <span id="dog">dog</span>.
→ Prepend to the contents of the target element
<<link "Size">>
<<prepend "#dog">>big <</prepend>>
<</link>>
→ Result, after clicking
I saw a <span id="dog">big dog</span>.
→ Example setup
I saw a <span id="dog">dog</span>.
→ Prepend to the contents of the target element
<<link "Size">>
<<prepend "#dog" t8n>>big <</prepend>>
<</link>>
→ Result, after clicking
I saw a <span id="dog"><span class="macro-prepend-insert">big </span>dog</span>.
<<remove selector>>
Removes the selected element(s).
删除选定的元素(们)。
See:
DOM macro warning.
查看:DOM 宏警告。
Note:
If you simply want to empty the selected element(s), not remove them outright, you should use an empty <<replace>>
macro instead.
注意:如果您只想清空选定的元素(而不是直接删除它们),应使用一个空的 <<replace>>
宏。
v2.0.0
: Introduced. v2.0.0
: 引入。selector
: The CSS/jQuery-style selector used to target element(s).→ Given the following
I'd like a <span id="huge-cupcake">humongous </span>cupcake, please.
→ Remove the target element
<<link "Go small">>
<<remove "#huge-cupcake">>
<</link>>
→ Result, after the click
I'd like a cupcake, please.
<<removeclass selector [classNames]>>
Removes classes from the selected element(s).
从选定的元素(s)中删除类。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。selector
: The CSS/jQuery-style selector used to target element(s).classNames
: (optional) The names of the classes, separated by spaces. If no class names are given, removes all classes.<<removeclass "body" "day rain">> → Remove the classes "day" and "rain" from the <body> element
<<removeclass "#pie" "cherry">> → Remove the class "cherry" from the element with the ID "pie"
<<removeclass ".joe" "angry">> → Remove the class "angry" from all elements containing the class "joe"
<<removeclass "#begone">> → Remove all classes from the element with the ID "begone"
<<replace selector [transition|t8n]>> … <</replace>>
Executes its contents and replaces the contents of the selected element(s) with the output.
执行其内容,并用输出替换所选元素的内容。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.25.0
: Added transition
and t8n
keywords.v2.25.0
: 添加了 transition
和 t8n
关键字。selector
: The CSS/jQuery-style selector used to target element(s).transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ Example setup
I saw a <span id="dog">dog</span>.
→ Replace the contents of the target element
<<link "Breed">>
<<replace "#dog">>Catahoula Cur<</replace>>
<</link>>
→ Result, after clicking
I saw a <span id="dog">Catahoula Cur</span>.
→ Example setup
I saw a <span id="dog">dog</span>.
→ Replace the contents of the target element
<<link "Breed">>
<<replace "#dog" t8n>>Catahoula Cur<</replace>>
<</link>>
→ Result, after clicking
I saw a <span id="dog"><span class="macro-replace-insert">Catahoula Cur</span></span>.
<<toggleclass selector classNames>>
Toggles classes on the selected element(s)—i.e., adding them if they don't exist, removing them if they do.
在选定的元素上切换类——即如果它们不存在则添加,如果存在则删除。
See:
DOM macro warning.
查看:DOM 宏警告。
v2.0.0
: Introduced. v2.0.0
: 引入。selector
: The CSS/jQuery-style selector used to target element(s).classNames
: The names of the classes, separated by spaces.classNames
: 类的名称,用空格分隔。<<toggleclass "body" "day rain">> → Toggle the classes "day" and "rain" on the <body> element
<<toggleclass "#pie" "cherry">> → Toggle the class "cherry" on the element with the ID "pie"
<<toggleclass ".joe" "angry">> → Toggle the class "angry" on all elements containing the class "joe"
Warning:
The audio subsystem that supports the audio macros comes with some built-in limitations and it is strongly recommended that you familiarize yourself with them.
注意:支持音频宏的音频子系统自带一些内置限制,强烈建议您熟悉这些限制。
<<audio trackIdList actionList>>
Controls the playback of audio tracks, which must be set up via <<cacheaudio>>
.
控制音频轨道的播放,必须通过 <<cacheaudio>>
设置。
See:
Audio macro limitations.
注意:音频宏的限制。
Note:
The <<audio>>
macro cannot affect playlist tracks whose ownership has been transferred to their respective playlist. Meaning those set up via <<createplaylist>>
with its own
action, as owned playlist tracks are solely under the control of their playlist.
备注: <<audio>>
宏无法影响已将其所有权转让给各自播放列表的播放列表曲目。这意味着通过 <<createplaylist>>
及其 own
动作设置的,因为拥有播放列表曲目完全受其播放列表的控制。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) controls whether tracks that have been faded to 0
volume (silent) are automatically paused.
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)控制是否自动暂停已淡出到 0
音量(静音)的音轨。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.1.0
: Added fadeoverto
action.v2.1.0
: 添加了 fadeoverto
动作。v2.8.0
: Added group ID(s).v2.8.0
: 添加了组 ID(s)。v2.28.0
: Added load
and unload
actions.v2.28.0
: 添加了 load
和 unload
动作。v2.37.0
: Added :stopped
predefined group ID.v2.37.0
: 添加了 :stopped
预定义组 ID。trackIdList
: The list of track and/or group IDs, separated by spaces. See below for details on group IDs.actionList
: The list of actions to perform. Available actions are:
fadein
: Start playback of the selected tracks and fade them from their current volume level to 1
(loudest) over 5
seconds.1
(最响)需要 5
秒。fadeout
: Start playback of the selected tracks and fade them from their current volume level to 0
(silent) over 5
seconds.0
(静音)需要 5
秒。fadeoverto
seconds
level
: Start playback of the selected tracks and fade them from their current volume level to the specified level over the specified number of seconds.fadeoverto
seconds
level
: 从当前音量级别开始播放所选曲目,并在指定秒数内淡入到指定音量级别。fadeto
level
: Start playback of the selected tracks and fade them from their current volume level to the specified level over 5
seconds.fadeto
level
: 从当前音量级别开始播放所选曲目,并在 5
秒内淡入到指定音量级别。goto
passage
: Forwards the player to the passage with the given name when playback of the first of the selected tracks ends normally. May be called either with the passage name or with a link markup.load
: Pause playback of the selected tracks and, if they're not already in the process of loading, force them to drop any existing data and begin loading. NOTE: This should not be done lightly if your audio sources are on the network, as it forces the player to begin downloading them.loop
: Set the selected tracks to repeat playback upon ending normally.loop
: 将选定的曲目设置为正常结束时重复播放。mute
: Mute the volume of the selected tracks—effectively volume 0
, except without changing the volume level.mute
: 静音选定曲目的音量——实际上音量 0
,但不会改变音量级别。pause
: Pause playback of the selected tracks.pause
: 暂停选定曲目的播放。play
: Start playback of the selected tracks.play
: 开始选定曲目的播放。stop
: Stop playback of the selected tracks.time
seconds
: Set the current playback time of the selected tracks to the specified number of seconds. Valid values are floating-point numbers in the range 0
(start) to the maximum duration—e.g., 60
is 60
is sixty seconds in, 90.5
is ninety-point-five seconds in.unload
: Stop playback of the selected tracks and force them to drop any existing data. NOTE: Once unloaded, playback cannot occur until a load
action is issued.unloop
: Set the selected tracks to not repeat playback (this is the default).unmute
: Unmute the volume of the selected tracks (this is the default).volume
level
: Set the volume of the selected tracks to the specified level. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.Group IDs allow several tracks to be selected simultaneously without needing to specify each one individually. There are several predefined group IDs (:all
, :looped
, :muted
, :paused
, :playing
, :stopped
) and custom IDs may be defined via <<createaudiogroup>>
. The :not()
group modifier syntax (groupId:not(trackIdList)
) allows a group to have some of its tracks excluded from selection.
组 ID 允许同时选择多个轨道,而无需逐个指定。存在多个预定义的组 ID( :all
、 :looped
、 :muted
、 :paused
、 :playing
、 :stopped
)以及可以通过 <<createaudiogroup>>
定义自定义 ID。 :not()
组修饰符语法( groupId:not(trackIdList)
)允许组中的一些轨道被排除在选择之外。
→ Start playback of paused tracks
<<audio ":paused" play>>
→ Pause playback of playing tracks
<<audio ":playing" pause>>
→ Stop playback of playing tracks
<<audio ":playing" stop>>
→ Stop playback of all tracks
<<audio ":all" stop>>
→ Stop playback of playing tracks except those in the ":ui" group
<<audio ":playing:not(:ui)" stop>>
→ Change the volume of all tracks except those in the ":ui" group
→ to 40%, without changing the current playback state
<<audio ":all:not(:ui)" volume 0.40>>
→ Given the following (best done in the StoryInit special passage)
<<cacheaudio "bgm_space" "media/audio/space_quest.mp3" "media/audio/space_quest.ogg">>
→ Start playback
<<audio "bgm_space" play>>
→ Start playback at 50% volume
<<audio "bgm_space" volume 0.5 play>>
→ Start playback at 120 seconds in
<<audio "bgm_space" time 120 play>>
→ Start repeating playback
<<audio "bgm_space" loop play>>
→ Start playback and fade from 0% to 100% volume
<<audio "bgm_space" volume 0 fadein>>
→ Start playback and fade from 75% to 0% volume
<<audio "bgm_space" volume 0.75 fadeout>>
→ Start playback and fade from 25% to 75% volume
<<audio "bgm_space" volume 0.25 fadeto 0.75>>
→ Start playback and fade from 25% to 75% volume over 30 seconds
<<audio "bgm_space" volume 0.25 fadeoverto 30 0.75>>
→ Start playback and goto the "Peace Moon" passage upon ending normally
<<audio "bgm_space" play goto "Peace Moon">>
→ Pause playback
<<audio "bgm_space" pause>>
→ Stop playback
<<audio "bgm_space" stop>>
→ Mute playback, without changing the current playback state
<<audio "bgm_space" mute>>
→ Unmute playback, without changing the current playback state
<<audio "bgm_space" unmute>>
→ Change the volume to 40%, without changing the current playback state
<<audio "bgm_space" volume 0.40>>
→ Seek to 90 seconds in, without changing the current playback state
<<audio "bgm_space" time 90>>
load
and unload
actionsload
和 unload
动作Warning:
Be very careful with these if your audio sources are on the network, as you are forcing players to begin downloading them. Not everyone has
blazing fast internet with unlimited data—especially true for mobile users. Pease, do not take your players' bandwidth and data usage lightly.
警告:如果您的音频源在网络上,请务必小心使用,因为您正在强制玩家开始下载它们。并非所有人都有无限数据的超快互联网——尤其是移动用户。请勿轻视玩家的带宽和数据使用。
→ If it's not currently loading, drop existing data buffers and load the track
<<audio "bgm_space" load>>
→ Unload the track, dropping existing data buffers
<<audio "bgm_space" unload>>
<<cacheaudio trackId sourceList>>
Caches an audio track for use by the other audio macros.
缓存音频轨道以供其他音频宏使用。
Note:
The StoryInit
special passage is normally the best place to set up tracks.
备注: StoryInit
特殊段落通常是设置轨道的最佳位置。
v2.0.0
: Introduced. v2.0.0
: 引入。trackId
: The ID of the track, which will be used to reference it.trackId
: 轨迹的 ID,将用于引用它。sourceList
: A space separated list of sources for the track. Only one is required, though supplying additional sources in differing formats is recommended, as no single format is supported by all browsers. A source must be either a URL (absolute or relative) to an audio resource, the name of an audio passage, or a data URI. In rare cases where the audio format cannot be automatically detected from the source (URLs are parsed for a file extension, data URIs are parsed for the media type), a format specifier may be prepended to the front of each source to manually specify the format (syntax: formatId|
, where formatId
is the audio format—generally, whatever the file extension would normally be; e.g., mp3
, mp4
, ogg
, weba
, wav
).sourceList
: 轨迹的来源列表,空格分隔。虽然只需要一个,但推荐提供不同格式的额外来源,因为没有任何格式被所有浏览器支持。来源必须是一个指向音频资源的 URL(绝对或相对)、音频段落名称或数据 URI。在极少数情况下,无法从源(URL 解析文件扩展名,数据 URI 解析媒体类型)自动检测音频格式时,可以在每个来源前添加格式指定符以手动指定格式(语法: formatId|
,其中 formatId
是音频格式——通常是文件扩展名;例如, mp3
, mp4
, ogg
, weba
, wav
)。→ Cache a track with the ID "boom" and one source via relative URL
<<cacheaudio "boom" "media/audio/explosion.mp3">>
→ Cache a track with the ID "boom" and one source via audio passage
<<cacheaudio "boom" "explosion">>
→ Cache a track with the ID "bgm_space" and two sources via relative URLs
<<cacheaudio "bgm_space" "media/audio/space_quest.mp3" "media/audio/space_quest.ogg">>
→ Cache a track with the ID "what" and one source via URL with a format specifier
<<cacheaudio "what" "mp3|http://an-audio-service.com/a-user/a-track-id">>
<<createaudiogroup groupId>>
[<<track trackId>> …]
<</createaudiogroup>>
Collects tracks, which must be set up via <<cacheaudio>>
, into a group via its <<track>>
children. Groups are useful for applying actions to multiple tracks simultaneously and/or excluding the included tracks from a larger set when applying actions.
收集必须通过 <<cacheaudio>>
设置的轨道,并将其通过其 <<track>>
子项分组。组可用于同时应用操作到多个轨道,或者当应用操作时排除包含的轨道。
Note:
The StoryInit
special passage is normally the best place to set up groups.
注意: StoryInit
特殊段落通常是设置组的最理想位置。
v2.19.0
: Introduced. v2.19.0
: 引入。v2.37.0
: Added :stopped
predefined group ID.v2.37.0
: 添加了 :stopped
预定义组 ID。<<createaudiogroup>>
groupId
: The ID of the group that will be used to reference it and must begin with a colon. NOTE: There are several predefined group IDs (:all
, :looped
, :muted
, :paused
, :playing
, :stopped
) and the :not
group modifier that cannot be reused/overwritten.groupId
: 要引用的组 ID,必须以冒号开头。注意:有一些预定义的组 ID( :all
、 :looped
、 :muted
、 :paused
、 :playing
、 :stopped
)以及 :not
组修饰符不能被重用/覆盖。<<track>>
trackId
: The ID of the track.trackId
: 轨道的 ID。→ Given the following (best done in the StoryInit special passage)
<<cacheaudio "ui_beep" "media/audio/ui/beep.mp3">>
<<cacheaudio "ui_boop" "media/audio/ui/boop.mp3">>
<<cacheaudio "ui_swish" "media/audio/ui/swish.mp3">>
→ Set up a group ":ui" with the tracks: "ui_beep", "ui_boop", and "ui_swish"
<<createaudiogroup ":ui">>
<<track "ui_beep">>
<<track "ui_boop">>
<<track "ui_swish">>
<</createaudiogroup>>
<<createplaylist listId>>
[<<track trackId actionList>> …]
<</createplaylist>>
Collects tracks, which must be set up via <<cacheaudio>>
, into a playlist via its <<track>>
children.
收集必须通过 <<cacheaudio>>
设置,并通过其 <<track>>
子项创建播放列表的轨道。
Note:
The StoryInit
special passage is normally the best place to set up playlists.
注意: StoryInit
特殊段落通常是设置播放列表的最佳位置。
v2.8.0
: Introduced. v2.8.0
: 引入。<<createplaylist>>
listId
: The ID of the playlist, which will be used to reference it.listId
: 播单的 ID,用于引用。<<track>>
trackId
: The ID of the track.trackId
: 轨道的 ID。actionList
: The list of actions to perform. Available actions are:
volume
level
: (optional) Set the base volume of the track within the playlist to the specified level. If omitted, defaults to the track's current volume. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.volume
level
: (可选)将轨道在播单中的基本音量设置为指定级别。如果省略,则默认为轨道当前音量。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。own
: (optional) Keyword, used to signify that the playlist should create its own independent copy of the track, rather than simply referencing the existing version. Owned copies are solely under the control of their playlist—meaning <<audio>>
actions cannot affect them, even when using group IDs.own
: (可选)关键字,用于表示播单应创建其自己的独立副本的轨道,而不是简单地引用现有版本。拥有副本的轨道完全受其播单控制——这意味着 <<audio>>
操作无法影响它们,即使使用组 ID。→ Given the following setup (best done in the StoryInit special passage)
<<cacheaudio "swamped" "media/audio/Swamped.mp3">>
<<cacheaudio "heavens_a_lie" "media/audio/Heaven's_A_Lie.mp3">>
<<cacheaudio "closer" "media/audio/Closer.mp3">>
<<cacheaudio "to_the_edge" "media/audio/To_The_Edge.mp3">>
→ Create a playlist "bgm_lacuna" with the tracks: "swamped", "heavens_a_lie", "closer", and "to_the_edge"
<<createplaylist "bgm_lacuna">>
<<track "swamped" volume 1>> → Add "swamped" at 100% volume
<<track "heavens_a_lie" volume 0.5>> → Add "heavens_a_lie" at 50% volume
<<track "closer" own>> → Add an owned copy of "closer" at its current volume
<<track "to_the_edge" volume 1 own>> → Add an owned copy of "to_the_edge" at 100% volume
<</createplaylist>>
<<masteraudio actionList>>
Controls the master audio settings.
控制主音频设置。
See:
Audio macro limitations.
注意:音频宏的限制。
v2.8.0
: Introduced. v2.8.0
: 引入。v2.28.0
: Added load
, muteonhide
, nomuteonhide
, and unload
actions.load
、 muteonhide
、 nomuteonhide
和 unload
动作。actionList
: The list of actions to perform. Available actions are:
load
: Pause playback of all tracks and, if they're not already in the process of loading, force them to drop any existing data and begin loading. NOTE: This should not be done lightly if your audio sources are on the network, as it forces the player to begin downloading them.load
: 暂停所有轨道的播放,并且如果它们尚未开始加载,则强制它们丢弃任何现有数据并开始加载。注意:如果您的音频源在网络上,则不应轻率地这样做,因为这会强制播放器开始下载它们。mute
: Mute the master volume (effectively volume 0
, except without changing the volume level).mute
: 静音主音量(实际上音量 0
,但不会改变音量级别)。muteonhide
: Enable automatic muting of the master volume when losing visibility—i.e., when switched to another tab or the browser window is minimized.muteonhide
: 当失去可见性时(即切换到另一个标签页或浏览器窗口最小化时)启用自动静音主音量。nomuteonhide
: Disable automatic muting of the master volume when losing visibility (this is the default).nomuteonhide
: 禁用失去可见性时自动静音主音量(这是默认设置)。stop
: Stop playback of all tracks.stop
: 停止所有轨道的播放。unload
: Stop playback of all tracks and force them to drop any existing data. NOTE: Once unloaded, playback cannot occur until a load
action is issued for each track—either a master load
action, to affect all tracks, or an <<audio>>
/<<playlist>>
load
action, to affect only certain tracks.unload
: 停止所有轨道的播放并强制它们丢弃任何现有数据。注意:一旦卸载,播放无法进行,直到为每个轨道发出一个 load
动作——要么是一个主 load
动作,影响所有轨道,要么是一个 <<audio>>
/ <<playlist>>
load
动作,仅影响某些轨道。unmute
: Unmute the master volume (this is the default).unmute
: 解除主音量静音(这是默认设置)。volume
level
: Set the master volume to the specified level. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。→ Stop playback of all registered tracks, no exceptions
<<masteraudio stop>>
→ Change the master volume to 40%
<<masteraudio volume 0.40>>
→ Mute the master volume
<<masteraudio mute>>
→ Unmute the master volume
<<masteraudio unmute>>
→ Enable automatic muting of the master volume when losing visibility
<<masteraudio muteonhide>>
→ Disable automatic muting of the master volume when losing visibility
<<masteraudio nomuteonhide>>
load
and unload
actionsload
和 unload
动作Warning:
Be very careful with these if your audio sources are on the network, as you are forcing players to begin downloading them. Not everyone has
blazing fast internet with unlimited data—especially true for mobile users. Pease, do not take your players' bandwidth and data usage lightly.
警告:如果您的音频源在网络上,请务必小心使用,因为您正在强制玩家开始下载它们。并非所有人都有无限数据的超快互联网——尤其是移动用户。请勿轻视玩家的带宽和数据使用。
→ If they're not currently loading, drop existing data buffers and load all tracks
<<masteraudio load>>
→ Unload all tracks, dropping existing data buffers
<<masteraudio unload>>
<<playlist listId actionList>>
Controls the playback of the playlist, which must be set up via <<createplaylist>>
.
控制播放列表的播放,必须通过 <<createplaylist>>
设置。
See:
Audio macro limitations.
注意:音频宏的限制。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) controls whether tracks that have been faded to 0
volume (silent) are automatically paused.
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)控制是否自动暂停已淡出到 0
音量(静音)的音轨。
v2.0.0
: Introduced, compatible with <<setplaylist>>
.v2.0.0
: 引入,兼容于 <<setplaylist>>
。v2.1.0
: Added fadeoverto
action.v2.1.0
: 添加了 fadeoverto
动作。v2.8.0
: Added listId
argument, compatible with <<createplaylist>>
.v2.8.0
: 添加了 listId
参数,兼容于 <<createplaylist>>
。v2.28.0
: Added load
and unload
actions.v2.28.0
: 添加了 load
和 unload
动作。<<createplaylist>>
-compatible form <<createplaylist>>
- 兼容形式listId
: The ID of the playlist.listId
: 播单的 ID。actionList
: The list of actions to perform. Available actions are:
fadein
: Start playback of the playlist and fade the current track from its current volume level to 1
(loudest) over 5
seconds.fadein
: 开始播放播放列表,并将当前曲目从当前音量级别淡入至 1
(最大音量)需要 5
秒。fadeout
: Start playback of the playlist and fade the current track from its current volume level to 0
(silent) over 5
seconds.fadeout
: 开始播放播放列表,并将当前曲目从当前音量级别淡入至 0
(静音)需要 5
秒。fadeoverto
seconds
level
: Start playback of the playlist and fade the current track from its current volume level to the specified level over the specified number of seconds.fadeoverto
seconds
level
: 开始播放播放列表,并将当前曲目从当前音量级别淡入至指定音量,需要指定的时间数秒。fadeto
level
: Start playback of the playlist and fade the current track from its current volume level to the specified level over 5
seconds.fadeto
level
: 开始播放播放列表,并将当前曲目从当前音量级别淡入至指定音量,需要 5
秒。load
: Pause playback of the playlist and, if its tracks are not already in the process of loading, force them to drop any existing data and begin loading. NOTE: This should not be done lightly if your audio sources are on the network, as it forces the player to begin downloading them.loop
: Set the playlist to repeat playback upon ending.loop
: 将播放列表设置为循环播放。mute
: Mute the volume of the playlist (effectively volume 0
, except without changing the volume level).mute
: 静音播放列表的音量(实际上音量 0
,但不会改变音量级别)。pause
: Pause playback of the playlist.pause
: 暂停播放列表的播放。play
: Start playback of the playlist.play
: 开始播放播放列表。shuffle
: Set the playlist to randomly shuffle.skip
: Skip ahead to the next track in the queue. An empty queue will not be refilled unless repeat playback has been set.skip
: 跳过队列中的下一首曲目。除非已设置重复播放,否则空队列不会重新填充。stop
: Stop playback of the playlist.stop
: 停止播放播放列表。unload
: Stop playback of the playlist and force its tracks to drop any existing data. NOTE: Once unloaded, playback cannot occur until a load
action is issued.unload
: 停止播放播放列表并强制其曲目丢弃任何现有数据。注意:一旦卸载,除非发出 load
操作,否则无法播放。unloop
: Set the playlist to not repeat playback (this is the default).unloop
: 将播放列表设置为不重复播放(这是默认设置)。unmute
: Unmute the volume of the playlist (this is the default).unmute
: 解除播放列表音量静音(这是默认设置)。unshuffle
: Set the playlist to not randomly shuffle (this is the default).unshuffle
: 将播放列表设置为不随机播放(这是默认设置)。volume
level
: Set the volume of the playlist to the specified level. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.volume
level
: 将播放列表音量设置为指定级别。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。<<setplaylist>>
-compatible form <<setplaylist>>
-兼容格式actionList
: Identical to the <<createplaylist>>
-compatible form.<<createplaylist>>
兼容形式相同。<<createplaylist>>
-compatible form shown)<<createplaylist>>
兼容形式)→ Given the following (best done in the StoryInit special passage)
<<cacheaudio "swamped" "media/audio/Swamped.mp3">>
<<cacheaudio "heavens_a_lie" "media/audio/Heaven's_A_Lie.mp3">>
<<cacheaudio "closer" "media/audio/Closer.mp3">>
<<cacheaudio "to_the_edge" "media/audio/To_The_Edge.mp3">>
<<createplaylist "bgm_lacuna">>
<<track "swamped" volume 1>>
<<track "heavens_a_lie" volume 1>>
<<track "closer" volume 1>>
<<track "to_the_edge" volume 1>>
<</createplaylist>>
→ Start playback
<<playlist "bgm_lacuna" play>>
→ Start playback at 50% volume
<<playlist "bgm_lacuna" volume 0.5 play>>
→ Start non-repeating playback
<<playlist "bgm_lacuna" unloop play>>
→ Start playback with a randomly shuffled playlist
<<playlist "bgm_lacuna" shuffle play>>
→ Start playback and fade from 0% to 100% volume
<<playlist "bgm_lacuna" volume 0 fadein>>
→ Start playback and fade from 75% to 0% volume
<<playlist "bgm_lacuna" volume 0.75 fadeout>>
→ Start playback and fade from 25% to 75% volume
<<playlist "bgm_lacuna" volume 0.25 fadeto 0.75>>
→ Start playback and fade from 25% to 75% volume over 30 seconds
<<playlist "bgm_lacuna" volume 0.25 fadeoverto 30 0.75>>
→ Pause playback
<<playlist "bgm_lacuna" pause>>
→ Stop playback
<<playlist "bgm_lacuna" stop>>
→ Mute playback, without changing the current playback state
<<playlist "bgm_lacuna" mute>>
→ Unmute playback, without changing the current playback state
<<playlist "bgm_lacuna" unmute>>
→ Change the volume to 40%, without changing the current playback state
<<playlist "bgm_lacuna" volume 0.40>>
→ Set the playlist to randomly shuffle, without changing the current playback state
<<playlist "bgm_lacuna" shuffle>>
load
and unload
actionsload
和 unload
动作Warning:
Be very careful with these if your audio sources are on the network, as you are forcing players to begin downloading them. Not everyone has
blazing fast internet with unlimited data—especially true for mobile users. Pease, do not take your players' bandwidth and data usage lightly.
警告:如果您的音频源在网络上,请务必小心使用,因为您正在强制玩家开始下载它们。并非所有人都有无限数据的超快互联网——尤其是移动用户。请勿轻视玩家的带宽和数据使用。
→ If they're not currently loading, drop existing data buffers and load all of the playlist's tracks
<<playlist "bgm_lacuna" load>>
→ Unload all of the playlist's tracks, dropping existing data buffers
<<playlist "bgm_lacuna" unload>>
<<removeaudiogroup groupId>>
Removes the audio group with the given ID.
移除具有给定 ID 的音频组。
Note:
You may not remove the predefined group IDs (:all
, :looped
, :muted
, :paused
, :playing
, :stopped
) or the :not
group modifier.
注意:您不能移除预定义的组 ID( :all
、 :looped
、 :muted
、 :paused
、 :playing
、 :stopped
)或 :not
组修饰符。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.37.0
: Added :stopped
predefined group ID.v2.37.0
: 添加了 :stopped
预定义组 ID。groupId
: The ID of the group.groupId
:组的 ID。→ Given a group set up via <<createaudiogroup ":ui">>…<</createplaylist>>
<<removeaudiogroup ":ui">>
<<removeplaylist listId>>
Removes the playlist with the given ID.
移除具有给定 ID 的播放列表。
v2.8.0
: Introduced. v2.8.0
: 引入。listId
: The ID of the playlist.listId
: 播单的 ID。→ Given a playlist set up via <<createplaylist "bgm_lacuna">>…<</createplaylist>>
<<removeplaylist "bgm_lacuna">>
<<waitforaudio>>
Displays the loading screen until all currently registered audio has either loaded to a playable state or aborted loading due to errors. Requires tracks to be set up via <<cacheaudio>>
.
显示加载界面,直到所有已注册的音频加载到可播放状态或由于错误而加载失败。需要通过 <<cacheaudio>>
设置音轨。
Note:
This macro should be invoked once following any invocations of <<cacheaudio>>
and <<createplaylist>>
, if any <<track>>
definitions used the copy
keyword, for which you want the loading screen displayed.
注意:如果使用了 copy
关键字,并且需要显示加载界面,则应在调用 <<cacheaudio>>
和 <<createplaylist>>
之后(如果有的话)调用此宏一次。
v2.8.0
: Introduced. v2.8.0
: 引入。<<cacheaudio "a" "a_track.…">>
<<cacheaudio "b" "b_track.…">>
<<cacheaudio "c" "c_track.…">>
<<cacheaudio "d" "d_track.…">>
<<waitforaudio>>
→ First, register the tracks that will be needed soon
<<cacheaudio "a" "a_track.…">>
<<cacheaudio "b" "b_track.…">>
→ Next, load all currently registered tracks (meaning: "a" and "b")
<<waitforaudio>>
→ Finally, register any tracks that won't be needed until later
<<cacheaudio "c" "c_track.…">>
<<cacheaudio "d" "d_track.…">>
<<done>> … <</done>>
Silently executes its contents when the incoming passage is done rendering and has been added to the page. Generally, only really useful for running code that needs to manipulate elements from the incoming passage, since you must wait until they've been added to the page.
静默执行其内容,当传入的段落渲染完成并被添加到页面时。通常,仅对需要操作传入段落元素的代码真正有用,因为必须等待它们被添加到页面。
Tip:
If you need to run the same code on multiple passages, consider using the PassageDone
special passage or, for a JavaScript/TwineScript solution, a :passagedisplay
event instead. They serve the same basic purpose as the <<done>>
macro, but are run each time passage navigation occurs.
提示:如果您需要在多个段落上运行相同的代码,请考虑使用 PassageDone
特殊段落,或者对于 JavaScript/TwineScript 解决方案,使用 :passagedisplay
事件。它们与 <<done>>
宏具有相同的基本功能,但在每次段落导航时都会运行。
v2.35.0
: Introduced. v2.35.0
: 引入。v2.36.0
: Changed delay mechanism to improve waiting on the DOM.v2.36.0
:将延迟机制更改为提高对 DOM 的等待。@@#spy;@@
<<done>>
<<replace "#spy">>I spy with my little eye, a crab rangoon.<</replace>>
<</done>>
<<goto passageName>>
<<goto linkMarkup>>
Immediately forwards the player to the passage with the given name. May be called either with the passage name or with a link markup.
立即将玩家转发到具有给定名称的段落。可以使用段落名称或链接标记来调用。
Note:
In most cases, you will not need to use <<goto>>
as there are often better and easier ways to forward the player. For example, a common use of <<link>>
is to perform various actions before forwarding the player to another passage. In that case, unless you need to dynamically determine the destination passage within the <<link>>
body, <<goto>>
is unnecessary as <<link>>
already includes the ability to forward the player.
注意:在大多数情况下,您不需要使用 <<goto>>
,因为通常有更好、更简单的方法来转发玩家。例如, <<link>>
的一个常见用途是在将玩家转发到另一个段落之前执行各种操作。在这种情况下,除非您需要在 <<link>>
体中动态确定目标段落,否则 <<goto>>
是不必要的,因为 <<link>>
已经包括了转发玩家的能力。
Warning:
Using <<goto>>
to automatically forward players from one passage to another with no input from them will both create junk moments within the story history and make it extremely difficult for players to navigate the history. It is strongly recommended that you look into other methods to achieve your goals instead—e.g., Config.navigation.override
.
警告:使用 <<goto>>
自动将玩家从一条段落转发到另一条段落而无需他们输入,这将在故事历史中创建垃圾时刻,并使玩家难以导航历史。强烈建议您考虑其他方法来实现您的目标——例如, Config.navigation.override
。
Warning:
<<goto>>
does not terminate passage rendering in the passage where it was encountered, so care must be taken to ensure that no unwanted state modifications occur after its call.
警告: <<goto>>
在遇到它的段落中未终止段落渲染,因此在使用后必须小心,以确保不会发生不希望的状态更改。
v2.0.0
: Introduced. v2.0.0
: 引入。passageName
: The name of the passage to go to.linkMarkup
: The link markup to use (regular syntax only, no setters).→ Passage name form
<<goto "Somewhere over yonder">>
<<goto $selectedPassage>>
→ Link markup form
<<goto [[Somewhere over yonder]]>>
<<goto [[$selectedPassage]]>>
<<repeat delay [transition|t8n]>> … <</repeat>>
Repeatedly executes its contents after the given delay, inserting any output into the passage in its place. May be terminated by a <<stop>>
macro.
在给定延迟后重复执行其内容,并将任何输出插入到其位置。可以通过 <<stop>>
宏终止。
Note:
Passage navigation terminates all pending timed executions.
注意:段落导航将终止所有挂起的定时执行。
v2.0.0
: Introduced. v2.0.0
: 引入。delay
: The amount of time to delay, as a valid CSS time value—e.g., 5s
and 500ms
. The minimum delay is 40ms
.delay
:延迟时间,作为有效的 CSS 时间值——例如, 5s
和 500ms
。最小延迟为 40ms
。transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。→ A countdown timer
<<set $seconds to 10>>\
Countdown: <span id="countdown">$seconds seconds remaining</span>!\
<<silent>>
<<repeat 1s>>
<<set $seconds to $seconds - 1>>
<<if $seconds gt 0>>
<<replace "#countdown">>$seconds seconds remaining<</replace>>
<<else>>
<<replace "#countdown">>Too Late<</replace>>
/* do something useful here */
<<stop>>
<</if>>
<</repeat>>
<</silent>>
<<stop>>
Used within <<repeat>>
macros. Terminates the execution of the current <<repeat>>
.
在 <<repeat>>
宏中使用。终止当前 <<repeat>>
的执行。
v2.0.0
: Introduced. v2.0.0
: 引入。<<timed delay [transition|t8n]>> …
[<<next [delay]>> …]
<</timed>>
Executes its contents after the given delay, inserting any output into the passage in its place. Additional timed executions may be chained via <<next>>
.
在给定延迟后执行其内容,将任何输出插入到段落中。可以通过 <<next>>
. 连接多个定时执行。
Note:
Passage navigation terminates all pending timed executions.
注意:段落导航将终止所有挂起的定时执行。
v2.0.0
: Introduced. v2.0.0
: 引入。<<timed>>
delay
: The amount of time to delay, as a valid CSS time value—e.g., 5s
and 500ms
. The minimum delay is 40ms
.delay
: 延迟时间,作为有效的 CSS 时间值——例如, 5s
和 500ms
。最小延迟为 40ms
。transition
: (optional) Keyword, used to signify that a CSS transition should be applied to the incoming insertions.transition
:(可选)关键字,用于表示应将 CSS 过渡应用于传入的插入内容。t8n
: (optional) Keyword, alias for transition
.t8n
:(可选)关键词, transition
的别名。<<next>>
delay
: (optional) The amount of time to delay, as a valid CSS time value—e.g., 5s
and 500ms
. The minimum delay is 40ms
. If omitted, the last delay specified, from a <<next>>
or the parent <<timed>>
, will be used.5s
和 500ms
。最小延迟为 40ms
。如果省略,则使用最后一个指定的延迟,来自 <<next>>
或父 <<timed>>
。→ Insert some text after 5 seconds with a transition
I want to go to…<<timed 5s t8n>> WONDERLAND!<</timed>>
→ Replace some text after 10 seconds
I like green <span id="eggs">eggs</span> and ham!\
<<timed 10s>><<replace "#eggs">>pancakes<</replace>><</timed>>
→ A execute <<goto>> after 10 seconds
<<timed 10s>><<goto "To the Moon, Alice">><</timed>>
→ Insert some text in 2 second intervals three times (at: 2s, 4s, 6s)
<<timed 2s>>Hi! Ho!
<<next>>Hi! Ho!
<<next>>It's off to work we go!
<</timed>>
→ Set a $variable after 4 seconds, 3 seconds, 2 seconds, and 1 second
<<silent>>
<<set $choice to 0>>
<<timed 4s>>
<<set $choice to 1>>
<<next 3s>>
<<set $choice to 2>>
<<next 2s>>
<<set $choice to 3>>
<<next 1s>>
<<set $choice to 4>>
<</timed>>
<</silent>>
→ Replace some text with a variable interval
→ Given: _delay is "2s" the interval will be 2 seconds
I'll have <span id="drink">some water</span>, please.\
<<timed _delay>><<replace "#drink">>a glass of milk<</replace>>\
<<next>><<replace "#drink">>a can of soda<</replace>>\
<<next>><<replace "#drink">>a cup of coffee<</replace>>\
<<next>><<replace "#drink">>tea, southern style, sweet<</replace>>\
<<next>><<replace "#drink">>a scotch, neat<</replace>>\
<<next>><<replace "#drink">>a bottle of your finest absinthe<</replace>>\
<</timed>>
<<widget widgetName [container]>> … <</widget>>
Creates a new widget macro (henceforth, widget) with the given name. Widgets allow you to create macros by using the standard macros and markup that you use normally within your story. All widgets may access arguments passed to them via the _args
special variable. Block widgets may access the contents they enclose via the _contents
special variable.
创建一个新的具有给定名称的小部件宏(以下简称小部件)。小部件允许您通过使用您通常在故事中使用的标准宏和标记来创建宏。所有小部件都可以通过 _args
特殊变量访问传递给它们的参数。块小部件可以通过 _contents
特殊变量访问它们包含的内容。
Warning:
Widgets should always be defined within a widget
-tagged passage—any widgets that are not may be lost on page reload—and you may use as few or as many such passages as you desire. Do not add a widget
tag to any of the specially named passages and attempt to define your widgets there.
警告:小部件应始终在标记为 widget
的段落内定义——否则在页面重新加载时可能会丢失——并且您可以按需使用尽可能少或尽可能多的此类段落。不要在任何特别命名的段落中添加 widget
标签并尝试在那里定义小部件。
Warning:
The array-like object stored in the _args
variable should be treated as though it were immutable—i.e., unable to be modified—because in the future it will be made thus, so any attempt to modify it will cause an error.
警告:存储在 _args
变量中的类似数组的对象应被视为不可变——即无法修改——因为将来它将被这样处理,所以任何修改它的尝试都将导致错误。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.36.0
: Added the container
keyword, _args
variable, and _contents
variable. Deprecated the $args
variable in favor of _args
.v2.36.0
: 添加了 container
关键字、 _args
变量和 _contents
变量。废弃了 $args
变量,改用 _args
。v2.37.0
: Added the _args.name
property.v2.37.0
: 添加了 _args.name
属性。widgetName
: The name of the created widget, which should not contain whitespace or angle brackets (<
, >
). If the name of an existing widget is chosen, the new widget will overwrite the older version. NOTE: The names of existing macros are invalid widget names and any attempts to use such a name will cause an error.<
, >
)。如果选择了现有部件的名称,新部件将覆盖旧版本。注意:现有宏的名称是无效的部件名称,任何尝试使用此类名称的操作都将导致错误。container
: (optional) Keyword, used to signify that the widget should be created as a container widget—i.e., non-void, requiring a closing tag; e.g., <<foo>>…<</foo>>
.<<foo>>…<</foo>>
。_args
& _contents
:_args
& _contents
:The _args
special variable is used internally to store arguments passed to the widget—as zero-based indices; i.e., _args[0]
is the first parsed argument, _args[1]
is the second, etc—the full argument string in raw and parsed forms—accessed via the _args.raw
and _args.full
properties—and the widgets' name via the _args.name
property.
_args
特殊变量用于内部存储传递给部件的参数——即零基于索引;即 _args[0]
是第一个解析参数, _args[1]
是第二个,等等——完整参数字符串的原始和解析形式——通过 _args.raw
和 _args.full
属性访问——以及部件的名称通过 _args.name
属性访问。
The _contents
special variable is used internally, by container widgets, to store the contents they enclose.
_contents
特殊变量由容器小部件内部使用,用于存储它们包含的内容。
When a widget is called, any existing _args
variable, and for container widgets _contents
, is stored for the duration of the call and restored after. This means that non-widget uses of these special variable are completely safe, though this does have the effect that uses external to widgets are inaccessible within them unless passed in as arguments.
当一个组件被调用时,任何现有的 _args
变量,以及对于容器组件 _contents
,都会在调用期间被存储并在调用后恢复。这意味着这些特殊变量的非组件使用是完全安全的,但这确实有这样一个效果,即除非作为参数传递,否则外部组件的使用在组件内部是不可访问的。
When calling one container widget directly from within another container widget, the _contents
special variable of the outer widget must not be included within the body of the call of the inner widget. Doing so will cause uncontrolled recursion. E.g.,
_contents
特殊变量不得包含在内部小部件调用体中。这样做将导致不受控制的递归。例如:
<<widget "inner" container>>
_contents
<</widget>>
<<widget "outer" container>>
<<inner>>_contents<</inner>>
<</widget>>
<<outer>>ford<</outer>>
Warning:
Unless localized by use of the <<capture>>
macro, any story or other temporary variables used within widgets are part of a story's normal variable store, so care must be taken not to accidentally either overwrite or pick up an existing value.
警告:除非使用 <<capture>>
宏进行本地化,否则在部件中使用的任何故事或其他临时变量都是故事正常变量存储的一部分,因此必须小心,以免意外覆盖或获取现有值。
Note:
No line-break control mechanisms are used in the following examples for readability. In practice, you'll probably want to use either line continuations or one of the no-break methods: Config.passages.nobr
setting, nobr
special tag, <<nobr>>
macro.
注意:以下示例中未使用换行控制机制以提高可读性。在实际应用中,您可能希望使用行续或以下无换行方法之一: Config.passages.nobr
设置, nobr
特殊标签, <<nobr>>
宏。
→ Creating a gender pronoun widget
<<widget "he">>
<<if $pcSex eq "male">>
he
<<elseif $pcSex eq "female">>
she
<<else>>
it
<</if>>
<</widget>>
→ Using it
"Are you sure that <<he>> can be trusted?"
→ Creating a silly print widget
<<widget "pm">>
<<if _args[0]>>
<<print _args[0]>>
<<else>>
Mum's the word!
<</if>>
<</widget>>
→ Using it
<<pm>> → Outputs: Mum's the word!
<<pm "Hi!">> → Outputs: Hi!
→ Creating a simple dialog box widget
<<widget "say" container>>
<div class="say-box">
<img class="say-image" @src="'images/' + _args[0].toLowerCase() + '.png'">
<p class="say-text">_contents</p>
</div>
<</widget>>
→ Using it
<<say "Chapel">>Tweego is a pathway to many abilities some consider to be… unnatural.<</say>>
clone(original)
→ any
Returns a deep copy of the given value.
返回给定值的深拷贝。
Only primitives, generic objects, Array
, Date
, Map
, RegExp
, and Set
are supported by default. Unsupported object types, either native or custom, will need to implement a .clone()
method to be properly supported by the clone()
function—when called on such an object, it will defer to the local method; see the Non-generic object types (classes) guide for more information.
仅支持原语、通用对象、 Array
、 Date
、 Map
、 RegExp
和 Set
。不支持的对象类型(无论是原生还是自定义的)需要实现一个 .clone()
方法,以便由 clone()
函数正确支持——当调用此类对象时,它将委托给本地方法;有关更多信息,请参阅非通用对象类型(类)指南。
Warning:
Referential relationships between objects are not maintained—i.e., after cloning multiple references to an object will refer to seperate yet equivalent objects, as each reference receives its own clone of the original.
警告:对象之间的引用关系不被维护——即,在克隆多个对象引用后,每个引用将指向单独但等效的对象,因为每个引用都接收了原始对象的克隆副本。
Warning:
Generic objects have only their own enumerable properties copied. Non-enumerable properties and property descriptors are not duplicated. In particular, this means that getters/setters are not properly duplicated. If you need getters/setters, then you'll need to use a non-generic object/class.
警告:通用对象仅复制其自身的可枚举属性。不可枚举属性和属性描述符不会被复制。特别是,这意味着获取器/设置器不会被正确复制。如果您需要获取器/设置器,那么您需要使用非通用对象/类。
v2.0.0
: Introduced. v2.0.0
: 引入。original
: (any
) The value to clone.original
: ( any
) 要复制的值。A deep copy (any
) of the original value.
原值的深度副本( any
)。
// Without clone(); given the generic object: $foo = { id : 1 }
<<set $bar to $foo>>
<<set $bar.id to 5>>
$foo.id → Returns: 5
$bar.id → Returns: 5
// With clone(); given the generic object: $foo = { id : 1 }
<<set $bar to clone($foo)>>
<<set $bar.id to 5>>
$foo.id → Returns: 1
$bar.id → Returns: 5
either(list…)
→ any
Returns a random value from its given arguments.
返回其给定参数的随机值。
v2.0.0
: Introduced. v2.0.0
: 引入。list
: (any
) The list of values to operate on. May be any combination of singular values, actual arrays, or array-like objects. All values will be concatenated into a single list for selection. NOTE: Does not flatten nested arrays—if this is required, the <Array>.flat()
method may be used to flatten the nested arrays prior to passing them to either()
.list
: ( any
) 要操作的值列表。可以是任何组合的单个值、实际数组或类似数组的对象。所有值将连接成一个单独的列表以进行选择。注意:不会展平嵌套数组——如果需要,可以在传递给 either()
之前使用 <Array>.flat()
方法来展平嵌套数组。A random value from its given arguments.
从其给定的参数中返回一个随机值。
// Using singular values
either("Blueberry", "Cherry", "Pecan") → Returns a random pie from the whole list
// Using arrays; given: $pies = ["Blueberry", "Cherry", "Pecan"]
either($pies) → Returns a random pie from the whole array
// Using singular values and arrays; given: $letters = ["A", "B"]
either($letters, "C", "D") → Returns a random value from the whole list—i.e., "A", "B", "C", "D"
// Using multiple arrays; given: $letters = ["A", "B"] & $numerals = ["1", "2"]
either($letters, $numerals) → Returns a random value from the whole list—i.e., "A", "B", "1", "2"
forget(key)
Removes the specified key, and its associated value, from the story metadata store.
从故事元数据存储中删除指定的键及其关联的值。
See Also:
memorize()
, recall()
.
参见: memorize()
, recall()
。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string
) The key to remove.key
: ( string
) 要删除的键。An Error
or TypeError
instance.
一个 Error
或 TypeError
实例。
<<run forget('achievements')>>
hasVisited(passages…)
→ boolean
Returns whether the passage with the given name occurred within the story history. If multiple passage names are given, returns the logical-AND aggregate of the set—i.e., true
if all were found, false
if any were not found.
返回给定名称的段落是否在故事历史中出现过。如果给出了多个段落名称,则返回该集合的逻辑-AND 聚合——即,如果所有名称都找到,则返回 true
,如果任何名称未找到,则返回 false
。
v2.7.0
: Introduced. v2.7.0
: 引入。passages
: (string
| Array<string>
) The name(s) of the passage(s) to search for. May be a list or an array of passages.passages
: ( string
| Array<string>
) 要搜索的段落名称(们)。可能是一个列表或数组。Boolean true
if all were found, elsewise false
.
布尔值 true
如果全部找到,否则 false
。
An Error
instance. 一个 Error
实例。
<<if hasVisited("Bar")>>…has been to the Bar…<</if>>
<<if not hasVisited("Bar")>>…has never been to the Bar…<</if>>
<<if hasVisited("Bar", "Café")>>…has been to both the Bar and Café<</if>>
<<if not hasVisited("Bar", "Café")>>…has never been to either the Bar, Café, or both…<</if>>
lastVisited(passages…)
→ integer
Returns the number of turns that have passed since the last instance of the passage with the given name occurred within the story history or -1
if it does not exist. If multiple passage names are given, returns the lowest count (which can be -1
).
返回自上次在故事历史中发生给定名称的段落实例以来经过的回合数,如果不存在则返回 -1
。如果给出了多个段落名称,则返回最低计数(可以是 -1
)。
v2.0.0
: Introduced. v2.0.0
: 引入。passages
: (string
| Array<string>
) The name(s) of the passage(s) to search for. May be a list or an array of passages.passages
: ( string
| Array<string>
) 要搜索的段落名称。可以是列表或数组。The lowest count (integer
), elsewise -1
.
最小计数( integer
),否则 -1
。
An Error
instance. 一个 Error
实例。
<<if lastVisited("Bar") is -1>>…has never been to the Bar…<</if>>
<<if lastVisited("Bar") is 0>>…is currently in the Bar…<</if>>
<<if lastVisited("Bar") is 1>>…was in the Bar one turn ago…<</if>>
<<if lastVisited("Bar", "Café") is -1>>…has never been to the Bar, Café, or both…<</if>>
<<if lastVisited("Bar", "Café") is 2>>…has been to both the Bar and Café, most recently two turns ago…<</if>>
importScripts(urls…)
→ Promise
Load and integrate external JavaScript scripts.
加载并集成外部 JavaScript 脚本。
Note:
Loading is done asynchronously at run time, so if the script must be available within a tight time frame, then you should use the Promise
returned by the function to ensure that the script is loaded before it is needed.
注意:加载是在运行时异步进行的,因此如果脚本必须在很紧的时间内可用,那么您应该使用函数返回的 Promise
来确保在需要之前脚本已加载。
Note:
Your project's JavaScript section (Twine 2: the Story JavaScript; Twine 1/Twee: a script
-tagged passage) is normally the best place to call importScripts()
.
注意:您的项目中的 JavaScript 部分(Twine 2:故事 JavaScript;Twine 1/Twee:带有 script
-标签的段落)通常是调用 importScripts()
的最佳位置。
v2.16.0
: Introduced. v2.16.0
: 引入。v2.37.0
: Added the ability to load JS Modules.v2.37.0
: 增加了加载 JS 模块的功能。urls
: (string
| object
| Array<string | object>
) The URLs of the external scripts to import. Loose URLs are imported concurrently, arrays of URLs are imported sequentially. URLs may also be specified as objects with a type
and a src
property.urls
: ( string
| object
| Array<string | object>
) 导入外部脚本的 URL。松散 URL 并发导入,URL 数组依次导入。URL 也可以指定为具有 type
和 src
属性的对象。Note:
URLs ending in .mjs
are imported as modules.
注意:以 .mjs
结尾的 URL 作为模块导入。
A Promise
that simply resolves, or rejects with an error if the script could not be loaded.
一个简单的解析器,如果脚本无法加载,则拒绝并报错。
An Error
instance. 一个 Error
实例。
// Import scripts a.js as normal, b.mjs as a module, and c.js as a
// module
importScripts(
"https://somesite/a/path/a.js",
"https://somesite/a/path/b.mjs",
{
type : "module",
src : "https://somesite/a/path/c.js"
}
);
// Import all scripts concurrently
importScripts(
"https://somesite/a/path/a.js",
"https://somesite/a/path/b.js",
"https://somesite/a/path/c.js",
"https://somesite/a/path/d.js"
);
// Import all scripts sequentially
importScripts([
"https://somesite/a/path/a.js",
"https://somesite/a/path/b.js",
"https://somesite/a/path/c.js",
"https://somesite/a/path/d.js"
]);
// Import scripts a.js, b.js, and the c.js/d.js group concurrently,
// while importing c.js and d.js sequentially relative to each other
importScripts(
"https://somesite/a/path/a.js",
"https://somesite/a/path/b.js",
[
"https://somesite/a/path/c.js",
"https://somesite/a/path/d.js"
]
);
Promise
objectPromise
对象// Import a script while using the returned Promise to ensure that
// the script has been fully loaded before executing dependent code
importScripts("https://somesite/a/path/a.js")
.then(function () {
// Code that depends on the script goes here
})
.catch(function (err) {
// There was an error loading the script, log it to the console
console.log(err);
});
Promise
object for later usePromise
对象以供以后使用// Import a script while saving the returned Promise so it may be used later
setup.aScriptImport = importScripts("https://somesite/a/path/aScript.js");
// Use the returned Promise later on to ensure that the script has been fully
// loaded before executing dependent code
setup.aScriptImport
.then(function () {
// Code that depends on the script goes here
})
.catch(function (err) {
// There was an error loading the script, log it to the console
console.log(err);
});
importStyles(urls…)
→ Promise
Load and integrate external CSS stylesheets.
加载并集成外部 CSS 样式表。
Note:
Loading is done asynchronously at run time, so if the stylesheet must be available within a tight time frame, then you should use the Promise
returned by the function to ensure that the stylesheet is loaded before it is needed.
注意:加载是在运行时异步进行的,因此如果样式表必须在很紧的时间内可用,那么您应该使用函数返回的 Promise
来确保在需要之前加载样式表。
Note:
Your project's JavaScript section (Twine 2: the Story JavaScript; Twine 1/Twee: a script
-tagged passage) is normally the best place to call importStyles()
.
注意:您的项目中的 JavaScript 部分(Twine 2:故事 JavaScript;Twine 1/Twee:带有 script
-标签的段落)通常是调用 importStyles()
的最佳位置。
v2.16.0
: Introduced. v2.16.0
: 引入。urls
: (string
| Array<string>
) The URLs of the external stylesheets to import. Loose URLs are imported concurrently, arrays of URLs are imported sequentially.A Promise
that simply resolves, or rejects with an error if the style could not be loaded.
一个简单的解析器,如果样式无法加载,则拒绝并返回错误。
An Error
instance. 一个 Error
实例。
// Import all stylesheets concurrently
importStyles(
"https://somesite/a/path/a.css",
"https://somesite/a/path/b.css",
"https://somesite/a/path/c.css",
"https://somesite/a/path/d.css"
);
// Import all stylesheets sequentially
importStyles([
"https://somesite/a/path/a.css",
"https://somesite/a/path/b.css",
"https://somesite/a/path/c.css",
"https://somesite/a/path/d.css"
]);
// Import stylesheets a.css, b.css, and the c.css/d.css group concurrently,
// while importing c.css and d.css sequentially relative to each other
importStyles(
"https://somesite/a/path/a.css",
"https://somesite/a/path/b.css",
[
"https://somesite/a/path/c.css",
"https://somesite/a/path/d.css"
]
);
Promise
objectPromise
对象// Grab a loading screen lock
var lsLockId = LoadScreen.lock();
// Import a stylesheet while using the returned Promise to ensure that the
// stylesheet has been fully loaded before unlocking the loading screen
importStyles("https://somesite/a/path/a.css")
.then(function () {
// The stylesheet has been loaded, release the loading screen lock
LoadScreen.unlock(lsLockId);
})
.catch(function (err) {
// There was an error loading the stylesheet, log it to the console
console.log(err);
});
memorize(key, value)
Sets the specified key and value within the story metadata store, which causes them to persist over story and browser restarts. To update the value associated with a key, simply set it again.
设置故事元数据存储中的指定键和值,使它们在故事和浏览器重启后持续存在。要更新与键关联的值,只需再次设置它即可。
Note:
The story metadata, like saves, is tied to the specific story it was generated with. It is not a mechanism for moving data between stories.
注意:故事元数据,如存档,与特定生成的故事相关联。它不是在故事之间移动数据的一种机制。
Warning:
The story metadata store is not, and should not be used as, a replacement for saves. Examples of good uses: achievement tracking, new game+ data, playthrough statistics, etc.
警告:故事元数据存储不应,也不应作为保存的替代品使用。示例:成就跟踪、新游戏+数据、游玩统计等。
Warning:
This feature is largely incompatible with private browsing modes, which cause all in-browser storage mechanisms to either persist only for the lifetime of the browsing session or fail outright.
警告:此功能与私密浏览模式大部分不兼容,可能导致所有浏览器存储机制只能持续浏览会话的生命周期,或者完全失败。
See Also:
forget()
, recall()
.
参见: forget()
, recall()
。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string
) The key that should be set.key
: ( string
) 应设置的关键字。value
: (any
) The value to set.value
: ( any
) 要设置的值。An TypeError
instance. 一个 TypeError
实例。
// Sets 'achievements', with the given value, in the metadata store.
<<run memorize('achievements', { ateYellowSnow : true })>>
// Sets 'ngplus', with the given value, in the metadata store.
<<run memorize('ngplus', true)>>
passage()
→ string
Returns the name of the active (present) passage.
返回活动(存在)的段落名称。
v2.0.0
: Introduced. v2.0.0
: 引入。The name (string
) of the passage.
过渡名称( string
)。
<<if passage() is "Café">>…the active passage is the Café passage…<</if>>
previous()
→ string
Returns the name of the most recent previous passage whose name does not match that of the active passage or an empty string, if there is no such passage.
返回名称与当前过渡名称不匹配的最最近的前一个过渡的名称,如果没有这样的过渡则返回空字符串。
v2.0.0
: Introduced. v2.0.0
: 引入。The name (string
) of the passage, elsewise an empty string (''
).
段落名称( string
),否则为空字符串( ''
)。
<<if previous() is "Café">>…the most recent non-active passage is the Café passage…<</if>>
→ Commonly used as part of a link to return to the most recent non-active passage
[[Return|previous()]]
random([min ,] max)
→ integer
Returns a pseudo-random whole number (integer) within the range of the given bounds (inclusive)—i.e., [min, max].
返回给定范围(包含)内的伪随机整数(整数)——即 [min, max]。
Note:
By default, it uses Math.random()
as its source of (non-deterministic) randomness, however, when the seedable PRNG has been enabled, via State.prng.init()
, it uses that (deterministic) seeded PRNG instead.
注意:默认情况下,它使用 Math.random()
作为其(非确定性)随机性的来源,然而,当通过 State.prng.init()
启用了可播种的 PRNG 时,它将使用那个(确定性)播种的 PRNG 代替。
v2.0.0
: Introduced. v2.0.0
: 引入。min
: (optional, integer
) The lower bound of the random number (inclusive). If omitted, will default to 0
.min
: (可选, integer
)随机数的下限(包含)。如果省略,将默认为 0
。max
: (integer
) The upper bound of the random number (inclusive).A random whole number (integer
).
一个随机整数( integer
)。
An Error
or TypeError
instance.
一个 Error
或 TypeError
实例。
random(5) → Returns a number in the range 0–5
random(1, 6) → Returns a number in the range 1–6
randomFloat([min ,] max)
→ decimal
Returns a pseudo-random decimal number (floating-point) within the range of the given bounds (inclusive for the minimum, exclusive for the maximum)—i.e., [min, max).
返回给定范围(最小值包含,最大值不包含)内的伪随机十进制数(浮点数)——即[min, max)。
Note:
By default, it simply returns non-deterministic results from Math.random()
, however, when the seedable PRNG has been enabled, via State.prng.init()
, it returns deterministic results from the seeded PRNG instead.
注意:默认情况下,它仅从 Math.random()
返回非确定性结果,然而,当启用可播种的伪随机数生成器后,通过 State.prng.init()
,它将返回从播种的伪随机数生成器得到的确定性结果。
v2.0.0
: Introduced. v2.0.0
: 引入。min
: (optional, decimal
) The lower bound of the random number (inclusive). If omitted, will default to 0.0
.min
: (可选, decimal
)随机数的下限(包含)。如果省略,将默认为 0.0
。max
: (decimal
) The upper bound of the random number (exclusive).A random floating-point number (decimal
).
一个随机的浮点数( decimal
)。
An Error
or TypeError
instance.
一个 Error
或 TypeError
实例。
randomFloat(5.0) → Returns a number in the range 0.0–4.9999999…
randomFloat(1.0, 6.0) → Returns a number in the range 1.0–5.9999999…
recall(key [, defaultValue])
→ any
Returns the value associated with the specified key from the story metadata store or, if no such key exists, the specified default value, if any.
返回从故事元数据存储中与指定键关联的值,如果不存在这样的键,则返回指定的默认值(如果有的话)。
See Also:
forget()
, memorize()
.
参见: forget()
, memorize()
。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string
) The key whose value should be returned.key
: ( string
) 应返回其值的键。defaultValue
: (optional, any
) The value to return if the key doesn't exist.any
)如果键不存在则返回的值。A value (any
) from the specified key, elsewise the default value if specified.
来自指定键的值( any
),否则返回指定的默认值。
A TypeError
instance. 一个 TypeError
实例。
// Set setup.achievements to the 'achievements' metadata or an empty generic object.
<<set setup.achievements to recall('achievements', {})>>
// Set setup.ngplus to the 'ngplus' metadata, with no default.
<<set setup.ngplus to recall('ngplus')>>
setPageElement(idOrElement , passages [, defaultText])
→ HTMLElement
| null
Renders the selected passage into the target element, replacing any existing content, and returns the element. If no passages are found and default text is specified, it will be used instead.
将所选段落渲染到目标元素中,替换任何现有内容,并返回该元素。如果没有找到段落且指定了默认文本,则将使用该默认文本。
v2.0.0
: Introduced. v2.0.0
: 引入。idOrElement
: (string
| HTMLElement
) The ID of the element or the element itself.idOrElement
: ( string
| HTMLElement
) 元素或元素本身的 ID。passages
: (string
| Array<string>
) The name(s) of the passage(s) to search for. May be a single passage or an array of passages. If an array of passage names is specified, the first passage to be found is used.defaultText
: (optional, string
) The default text to use if no passages are found.An HTMLElement
, elsewise null
.
一个 HTMLElement
,否则 null
。
Note:
As it is highly unlikely that either an array of passage names or default text will be needed in the vast majority of cases, only a few basic examples will be given.
注意:由于在绝大多数情况下,不需要使用段落名称数组或默认文本,因此这里只给出几个基本示例。
// Using an ID; given an existing element on the page: <div id="my-display"></div>
setPageElement("my-display", "MyPassage");
// Using an element; given a reference to an existing element: myElement
setPageElement(myElement, "MyPassage");
tags([passages…])
→ Array<string>
Returns a new array consisting of all of the tags of the given passages.
返回一个包含给定段落所有标签的新数组。
v2.0.0
: Introduced. v2.0.0
: 引入。passages
: (optional, string
| Array<string>
) The passages from which to collect tags. May be a list or an array of passages. If omitted, will default to the active (present) passage—included passages do not count for this purpose; e.g., passages pulled in via <<include>>
, PassageHeader
, etc.string
| Array<string>
)收集标签的段落。可以是段落列表或数组。如果省略,则默认为活动(当前)段落——包含的段落不计入此目的;例如,通过 <<include>>
、 PassageHeader
等拉入的段落。The tags (Array<string>
).
标签( Array<string>
)。
<<if tags().includes("forest")>>…the active passage is part of the forest…<</if>>
<<if tags("Lonely Glade").includes("forest")>>…the Lonely Glade passage is part of the forest…<</if>>
temporary()
→ object
Returns a reference to the current temporary variables store (equivalent to: State.temporary
). This is only really useful within pure JavaScript code, as within TwineScript you may simply access temporary variables natively.
返回当前临时变量存储的引用(相当于: State.temporary
)。这仅在纯 JavaScript 代码中非常有用,因为在 TwineScript 中,您可以直接访问临时变量。
v2.19.0
: Introduced. v2.19.0
: 引入。A reference to the temporary variable store (object
).
暂时变量存储的引用( object
)。
// Given: _selection is 'Zagnut Bar'
if (temporary().selection === 'Zagnut Bar') {
/* Do something… */
}
time()
→ integer
Returns the number of milliseconds that have passed since the current passage was rendered to the page.
返回自当前段落渲染到页面以来经过的毫秒数。
v2.0.0
: Introduced. v2.0.0
: 引入。The number of milliseconds (integer
) since the passage was rendered.
段落渲染以来的毫秒数( integer
)。
→ Links that vary based on the time
In the darkness, something wicked this way comes. Quickly! Do you \
<<link "try to run back into the light">>
<<if time() lt 5000>>
/% The player clicked the link in under 5s, so they escape %/
<<goto "Well lit passageway">>
<<else>>
/% Else, they're eaten by a grue %/
<<goto "Eaten by a grue">>
<</if>>
<</link>> \
or [[stand your ground|Eaten by a grue]]?
triggerEvent(name [, targets [, options]])
Dispatches a synthetic event with the given name, optionally on the given targets and with the given options.
发送具有给定名称的合成事件,可选地在给定的目标上,并带有给定的选项。
v2.37.0
: Introduced. v2.37.0
: 引入。Tip:
If dispatching custom events, it is recommended that you limit your custom event names to the following characters: letters, digits, periods (.), hyphens (-), underscores (_), and colons (:).
提示:如果发送自定义事件,建议将自定义事件名称限制为以下字符:字母、数字、点( . )、连字符( - )、下划线( _ )和冒号( : )。
name
: (string
) The name of the event to trigger. Both native and custom events are supported.targets
: (optional, Document
| HTMLElement
| jQuery
| NodeList
| Array<HTMLElement>
) The target(s) to trigger the event on. If omitted, will default to document
.Document
| HTMLElement
| jQuery
| NodeList
| Array<HTMLElement>
)。如果省略,则默认为 document
。options
: (optional, object
) The options to be used when dispatching the event. See below for details.object
)。详细信息请见下文。Warning:
Adding additional properties directly to event options objects is not recommended. Instead, use the detail
property.
警告:不建议直接向事件选项对象添加额外属性。相反,请使用 detail
属性。
An event options object should have some of the following properties:
事件选项对象应包含以下一些属性:
bubbles
: (optional, boolean
) Whether the event bubbles (default: true
).bubbles
(可选, boolean
) 事件是否冒泡(默认: true
)。cancelable
: (optional, boolean
) Whether the event is cancelable (default: true
).cancelable
(可选, boolean
) 事件是否可取消(默认: true
)。composed
: (optional, boolean
) Whether the event triggers listeners outside of a shadow root (default: false
).composed
:(可选, boolean
)是否在阴影根之外触发监听器(默认: false
)。detail
: (optional, any
) Custom data sent with the event (default: undefined
). Although any type is allowable, an object is often the most practical.detail
:(可选, any
)与事件一起发送的自定义数据(默认: undefined
)。尽管任何类型都是允许的,但对象通常是最实用的。fnord
event on document
document
上派发自定义的 fnord
事件triggerEvent('fnord');
click
event on the element bearing the ID some-menu
some-menu
的元素上派发 click
事件triggerEvent('click', document.getElementById('some-menu'));
update-meter
event on document
while specifying some optionsdocument
上派发自定义 update-meter
事件,并指定一些选项。triggerEvent('update-meter', document, {
detail : {
tags : ['health', 'magick']
}
});
mouseover
event on all elements bearing the class flippable
flippable
的元素上派发 mouseover
事件的多种方式。triggerEvent('mouseover', document.getElementsByClassName('flippable'));
triggerEvent('mouseover', document.querySelectorAll('.flippable'));
triggerEvent('mouseover', jQuery('.flippable'));
turns()
→ integer
Returns the total number (count) of played turns currently in effect—i.e., the number of played moments up to the present moment; future (rewound/undone) moments are not included within the total.
返回当前生效的已播放回合总数(计数)——即,截至当前时刻已播放的瞬间数量;未来的(回放/撤销)瞬间不包括在总数内。
v2.0.0
: Introduced. v2.0.0
: 引入。The turn count (integer
).
轮数( integer
)。
<<print "This is turn #" + turns()>>
variables()
→ object
Returns a reference to the active (present) story variables store (equivalent to: State.variables
). This is only really useful within pure JavaScript code, as within TwineScript you may simply access story variables natively.
返回对活动(当前)故事变量存储的引用(相当于: State.variables
)。这仅在纯 JavaScript 代码中非常有用,因为在 TwineScript 中,您可以直接访问故事变量。
v2.0.0
: Introduced. v2.0.0
: 引入。A reference to the story variable store (object
).
参考故事变量存储( object
)的引用。
// Given: $hasGoldenKey is true
if (variables().hasGoldenKey) {
/* Do something… */
}
visited([passages…])
→ integer
Returns the number of times that the passage with the given title occurred within the story history. If multiple passage titles are given, returns the lowest count.
返回给定标题的篇章在故事历史中出现的次数。如果给出多个篇章标题,则返回最低计数。
v2.0.0
: Introduced. v2.0.0
: 引入。passages
: (optional, string
| Array<string>
) The title(s) of the passage(s) to search for. May be a list or an array of passages. If omitted, will default to the current passage.string
| Array<string>
)要搜索的段落标题。可以是段落列表或数组。如果省略,则默认为当前段落。The passage count (integer
).
段落数量( integer
)。
<<if visited() is 3>>…this is the third visit to the current passage…<</if>>
<<if visited("Bar")>>…has been to the Bar at least once…<</if>>
<<if visited("Café") is 1>>…has been to the Café exactly once…<</if>>
<<if visited("Bar", "Café") is 4>>…has been to both the Bar and Café at least four times…<</if>>
visitedTags(tags…)
→ integer
Returns the number of passages within the story history that are tagged with all of the given tags.
返回故事历史中所有给定标签的段落数量。
v2.0.0
: Introduced. v2.0.0
: 引入。tags
: (string
| Array<string>
) The tags to search for. May be a list or an array of tags.tags
: ( string
| Array<string>
) 要搜索的标签。可以是标签列表或标签数组。The number (integer
) of passages that are tagged with the given tags.
标记给定标签的段落数量( integer
)。
An Error
instance. 一个 Error
实例。
<<if visitedTags("forest")>>…has been to some part of the forest at least once…<</if>>
<<if visitedTags("forest", "haunted") is 1>>…has been to the haunted part of the forest exactly once…<</if>>
<<if visitedTags("forest", "burned") is 3>>…has been to the burned part of the forest three times…<</if>>
Most of the methods listed below are SugarCube extensions, with the rest being either JavaScript natives or bundled library methods that are listed here for their utility—though, this is not an exhaustive list.
下面的大多数方法都是 SugarCube 扩展,其余的是 JavaScript 原生方法或捆绑的库方法,这里列出它们是为了它们的实用性——尽管这不是一个详尽的列表。
For more information see:
更多信息请参阅:
Additionally. SugarCube includes polyfills for virtually all JavaScript (ECMAScript) 5 & 6 native object methods—via the es5-shim and es6-shim polyfill libraries (shims only, no shams)—so they may be safely used even if your project will be played in ancient browsers that do not natively support them.
此外,SugarCube 包括几乎所有 JavaScript(ECMAScript)5 & 6 原生对象方法的 polyfills——通过 es5-shim 和 es6-shim polyfill 库(仅提供 shims,不提供 shams)——因此即使在那些不支持它们的古老浏览器中运行项目,也可以安全地使用它们。
<Array>.concat(members…)
→ Array<any> Concatenates one or more members to the end of the base array and returns the result as a new array. Does not modify the original.
连接一个或多个成员到数组的末尾,并返回一个新数组。不会修改原始数组。
members
: (any…) The members to concatenate. Members that are arrays will be merged—i.e., their members will be concatenated, rather than the array itself.members
: (任何类型...) 要连接的成员。如果成员是数组,则合并它们的成员,而不是数组本身。// Given: $fruits1 = ["Apples", "Oranges"], $fruits2 = ["Pears", "Plums"]
$fruits1.concat($fruits2) → Returns ["Apples", "Oranges", "Pears", "Plums"]
$fruits1.concat($fruits2, $fruits2) → Returns ["Apples", "Oranges", "Pears", "Plums", "Pears", "Plums"]
$fruits1.concat("Pears") → Returns ["Apples", "Oranges", "Pears"]
$fruits1.concat("Pears", "Pears") → Returns ["Apples", "Oranges", "Pears", "Pears"]
$fruits1.concat($fruits2, "Pears") → Returns ["Apples", "Oranges", "Pears", "Plums", "Pears"]
<Array>.concatUnique(members…)
→ Array<any> Concatenates one or more unique members to the end of the base array and returns the result as a new array. Does not modify the original.
将一个或多个唯一的成员连接到基本数组的末尾,并返回一个新数组。不会修改原始数组。
v2.21.0
: Introduced. v2.21.0
: 引入。members
: (any…) The members to concatenate. Members that are arrays will be merged—i.e., their members will be concatenated, rather than the array itself.members
: (任何类型...) 要连接的成员。如果成员是数组,则合并它们的成员,而不是数组本身。// Given: $fruits1 = ["Apples", "Oranges"], $fruits2 = ["Pears", "Plums"]
$fruits1.concatUnique($fruits2) → Returns ["Apples", "Oranges", "Pears", "Plums"]
$fruits1.concatUnique($fruits2, $fruits2) → Returns ["Apples", "Oranges", "Pears", "Plums"]
$fruits1.concatUnique("Pears") → Returns ["Apples", "Oranges", "Pears"]
$fruits1.concatUnique("Pears", "Pears") → Returns ["Apples", "Oranges", "Pears"]
$fruits1.concatUnique($fruits2, "Pears") → Returns ["Apples", "Oranges", "Pears", "Plums"]
<Array>.count(needle [, position])
→ integer <Array>.count(needle [, position])
→ 整数 Returns the number of times that the given member was found within the array, starting the search at position
.
返回给定成员在数组中出现的次数,从 position
开始搜索。
v2.0.0
: Introduced. v2.0.0
: 引入。needle
: (any) The member to count.needle
: (任何类型) 要计数的成员。position
: (optional, integer) The zero-based index at which to begin searching for needle
. If omitted, will default to 0
.position
: (可选,整数) 从 needle
开始搜索 0
的零基索引。如果省略,则默认为 0
。// Given: $fruits = ["Apples", "Oranges", "Plums", "Oranges"]
$fruits.count("Oranges") → Returns 2
$fruits.count("Oranges", 2) → Returns 1
<Array>.countWith(predicate [, thisArg])
→ integer <Array>.countWith(predicate [, thisArg])
→ 整数 Returns the number of times that members within the array pass the test implemented by the given predicate function.
返回数组中成员通过给定谓词函数实现的测试的次数。
v2.36.0
: Introduced. v2.36.0
: 引入。predicate
: (function) The function used to test each member. It is called with three arguments:
value
: (any) The member being processed.value
: (任何) 正在处理的成员。index
: (optional, integer) The index of member being processed.index
:(可选,整数)正在处理的成员索引。array
: (optional, array) The array being processed.thisArg
: (optional, any) The value to use as this
when executing predicate
.this
的值(可选,任何类型)// Given: $fruits = ["Apples", "Oranges", "Plums", "Oranges"]
$fruits.countWith(function (fruit) { return fruit === "Oranges"; }) → Returns 2
// Given: $numbers = [1, 2.3, 4, 76, 3.1]
$numbers.countWith(Number.isInteger) → Returns 3
// Given: $items = [
// { name : 'Healing potion', kind : 'potion' },
// { name : 'Longsword', kind : 'weapon' },
// { name : 'Mana potion', kind : 'potion' },
// { name : 'Dead rat', kind : 'junk' },
// { name : 'Endurance potion', kind : 'potion' },
// { name : 'Shortbow', kind : 'weapon' }
// ]
$items.countWith(function (item) { return item.kind === 'junk'; }) → Returns 1
<Array>.deleteAll(needles…)
→ Array<any> Removes all instances of the given members from the array and returns a new array containing the removed members.
移除数组中所有指定的成员,并返回包含已移除成员的新数组。
v2.37.0
: Introduced. v2.37.0
: 引入。needles
: (any… | Array<any>) The members to remove. May be a list of members or an array.needles
: (任何… | Array) 要删除的成员。可能是一个成员列表或一个数组。// Given: $fruits = ["Apples", "Oranges", "Plums", "Oranges"]
$fruits.deleteAll("Oranges") → Returns ["Oranges", "Oranges"]; $fruits ["Apples", "Plums"]
$fruits.deleteAll("Apples", "Plums") → Returns ["Apples", "Plums"]; $fruits ["Oranges", "Oranges"]
<Array>.deleteAt(indices…)
→ Array<any> Removes all of the members at the given indices from the array and returns a new array containing the removed members.
删除给定索引处的所有成员,并返回一个包含已删除成员的新数组。
v2.5.0
: Introduced. v2.5.0
: 引入。indices
: (integer… | Array<integer>) The indices of the members to remove. May be a list or array of indices.indices
: (整数… | Array) 要删除的成员的索引。可能是一个索引列表或数组。// Given: $fruits = ["Apples", "Oranges", "Plums", "Oranges"]
$fruits.deleteAt(2) → Returns ["Plums"]; $fruits ["Apples", "Oranges", "Oranges"]
$fruits.deleteAt(1, 3) → Returns ["Oranges", "Oranges"]; $fruits ["Apples", "Plums"]
$fruits.deleteAt(0, 2) → Returns ["Apples", "Plums"]; $fruits ["Oranges", "Oranges"]
<Array>.deleteFirst(needles…)
→ Array<any> Removes the first instance of the given members from the array and returns a new array containing the removed members.
移除数组中首次出现的指定成员,并返回包含已移除成员的新数组。
v2.37.0
: Introduced. v2.37.0
: 引入。needles
: (any… | Array<any>) The members to remove. May be a list of members or an array.needles
: (任何… | Array) 要删除的成员。可能是一个成员列表或一个数组。// Given: $fruits = ["Apples", "Oranges", "Plums", "Oranges"]
$fruits.deleteFirst("Oranges") → Returns ["Oranges"]; $fruits ["Apples", "Plums", "Oranges"]
$fruits.deleteFirst("Apples", "Plums") → Returns ["Apples", "Plums"]; $fruits ["Oranges", "Oranges"]
<Array>.deleteLast(needles…)
→ Array<any> Removes the last instance of the given members from the array and returns a new array containing the removed members.
从数组中移除给定成员的最后一个实例,并返回包含已移除成员的新数组。
v2.37.0
: Introduced. v2.37.0
: 引入。needles
: (any… | Array<any>) The members to remove. May be a list of members or an array.needles
: (任何… | Array) 要删除的成员。可能是一个成员列表或一个数组。// Given: $fruits = ["Apples", "Oranges", "Plums", "Oranges"]
$fruits.deleteLast("Oranges") → Returns ["Oranges"]; $fruits ["Apples", "Oranges", "Plums"]
$fruits.deleteLast("Apples", "Plums") → Returns ["Apples", "Plums"]; $fruits ["Oranges", "Oranges"]
<Array>.deleteWith(predicate [, thisArg])
→ Array<any> Removes all of the members from the array that pass the test implemented by the given predicate function and returns a new array containing the removed members.
从数组中移除所有通过给定谓词函数测试的成员,并返回包含已移除成员的新数组。
v2.25.0
: Introduced. v2.25.0
: 引入。predicate
: (function) The function used to test each member. It is called with three arguments:
predicate
: (函数) 用于测试每个成员的函数。它使用三个参数调用:value
: (any) The member being processed.value
: (任何类型) 正在处理的成员。index
: (optional, integer) The index of member being processed.index
: (可选,整数) 正在处理的成员的索引。array
: (optional, array) The array being processed.thisArg
: (optional, any) The value to use as this
when executing predicate
.this
的值(可选,任何类型)// Given: $fruits = ["Apples", "Apricots", "Oranges"]
→ Returns ["Apricots"]; $fruits ["Apples", "Oranges"]
$fruits.deleteWith(function (val) {
return val === "Apricots";
})
→ Returns ["Apples", "Apricots"]; $fruits ["Oranges"]
$fruits.deleteWith(function (val) {
return val.startsWith("Ap");
})
// Given: $fruits = [{ name : "Apples" }, { name : "Apricots" }, { name : "Oranges" }]
→ Returns [{ name : "Apricots" }]; $fruits [{ name : "Apples" }, { name : "Oranges" }]
$fruits.deleteWith(function (val) {
return val.name === "Apricots";
})
→ Returns [{ name : "Apples" }, { name : "Apricots" }]; $fruits [{ name : "Oranges" }]
$fruits.deleteWith(function (val) {
return val.name.startsWith("Ap");
})
<Array>.first()
→ any <Array>.first()
→ 任何 Returns the first member from the array. Does not modify the original.
返回数组的第一个成员。不会修改原始数组。
v2.27.0
: Introduced. v2.27.0
: 引入。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.first() → Returns "Blueberry"
<Array>.flat(depth)
→ Array<any> Returns a new array consisting of the source array with all sub-array elements concatenated into it recursively up to the given depth. Does not modify the original.
返回一个新的数组,该数组由源数组组成,其中递归地连接了所有子数组的元素,直到达到指定的深度。不会修改原始数组。
depth
: (optional, integer) The number of nested array levels should be flattened. If omitted, will default to 1
.depth
:(可选,整数)应扁平化的嵌套数组层级数。如果省略,则默认为 1
。// Given: $npa = [["Alfa", "Bravo"], [["Charlie", "Delta"], ["Echo"]], "Foxtrot"]
$npa.flat() → Returns ["Alfa", "Bravo", ["Charlie", "Delta"], ["Echo"], "Foxtrot"]
$npa.flat(1) → Returns ["Alfa", "Bravo", ["Charlie", "Delta"], ["Echo"], "Foxtrot"]
$npa.flat(2) → Returns ["Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot"]
<Array>.flatMap(callback [, thisArg])
→ Array<any> Returns a new array consisting of the result of calling the given mapping function on every element in the source array and then concatenating all sub-array elements into it recursively up to a depth of 1
. Does not modify the original.
返回一个新数组,该数组由对源数组中的每个元素调用给定的映射函数的结果组成,并将所有子数组元素递归地连接到它中,直到深度为 1
。不修改原始数组。
Note:
Identical to calling <Array>.map(…).flat()
.
注意:等同于调用 <Array>.map(…).flat()
。
callback
: (function) The function used to produce members of the new array. It is called with three arguments:
value
: (any) The member being processed.value
:(任何)正在处理的成员。index
: (optional, integer) The index of member being processed.index
: (可选,整数)正在处理的成员索引。array
: (optional, array) The array being processed.thisArg
: (optional, any) The value to use as this
when executing callback
.this
的值(可选,任何类型)// Given: $npa = ["Alfa", "Bravo Charlie", "Delta Echo Foxtrot"]
→ Returns ["Alfa", "Bravo", "Charlie", "Delta", "Echo", "Foxtrot"]
$npa.flatMap(function (val) {
return val.split(" ");
})
<Array>.includes(needle [, position])
→ boolean <Array>.includes(needle [, position])
→ 布尔值 Returns whether the given member was found within the array, starting the search at position
.
返回给定成员是否在数组中找到,从 position
开始搜索。
needle
: (any) The member to find.needle
: (任何) 要查找的成员。position
: (optional, integer) The zero-based index at which to begin searching for needle
. If omitted, will default to 0
.needle
。如果省略,则默认为 0
。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
<<if $pies.includes("Cherry")>>…found Cherry pie…<</if>>
<<if $pies.includes("Pecan", 3)>>…found Pecan pie within ["Pecan", "Pumpkin"]…<</if>>
<Array>.includesAll(needles…)
→ boolean <Array>.includesAll(needles…)
→ 布尔值 Returns whether all of the given members were found within the array.
返回是否在数组中找到了所有指定的成员。
v2.10.0
: Introduced. v2.10.0
: 引入。needles
: (any… | Array<any>) The members to find. May be a list of members or an array.needles
: (任何… | Array)要查找的成员。可以是成员列表或数组。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
<<if $pies.includesAll("Cherry", "Pecan")>>…found Cherry and Pecan pies…<</if>>
// Given: $search = ["Blueberry", "Pumpkin"]
<<if $pies.includesAll($search)>>…found Blueberry and Pumpkin pies…<</if>>
<Array>.includesAny(needles…)
→ boolean <Array>.includesAny(needles…)
→ 布尔值 Returns whether any of the given members were found within the array.
返回是否在数组中找到了给定的任何成员。
v2.10.0
: Introduced. v2.10.0
: 引入。needles
: (any… | Array<any>) The members to find. May be a list of members or an array.// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
<<if $pies.includesAny("Cherry", "Pecan")>>…found Cherry or Pecan pie…<</if>>
// Given: $search = ["Blueberry", "Pumpkin"]
<<if $pies.includesAny($search)>>…found Blueberry or Pumpkin pie…<</if>>
<Array>.last()
→ any → any Returns the last member from the array. Does not modify the original.
返回数组的最后一个成员。不会修改原始数组。
v2.27.0
: Introduced. v2.27.0
: 引入。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.last() → Returns "Pumpkin"
<Array>.pluck()
→ any → any Removes and returns a random member from the base array.
移除并返回基本数组中的一个随机成员。
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.pluck() → Removes and returns a random pie from the array
<Array>.pluckMany(want)
→ Array<any> Randomly removes the given number of members from the base array and returns the removed members as a new array.
随机移除基础数组中的指定数量成员,并返回被移除成员的新数组。
v2.20.0
: Introduced. v2.20.0
: 引入。want
: (integer) The number of members to pluck. Cannot pluck more members than the base array contains.// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.pluckMany(3) → Removes three random pies from the array and returns them as a new array
<Array>.pop()
→ any → 任何类型 Removes and returns the last member from the array, or undefined
if the array is empty.
移除并返回数组的最后一个成员,如果数组为空则返回 undefined
。
// Given: $fruits = ["Apples", "Oranges", "Pears"]
$fruits.pop() → Returns "Pears"; $fruits ["Apples", "Oranges"]
<Array>.push(members…)
→ number <Array>.push(members…)
→ 数字 Appends one or more members to the end of the base array and returns its new length.
将一个或多个成员追加到基础数组的末尾,并返回其新长度。
members
: (any…) The members to append.members
: (任何类型...) 要追加的成员。// Given: $fruits = ["Apples", "Oranges"]
$fruits.push("Apples") → Returns 3; $fruits ["Apples", "Oranges", "Apples"]
// Given: $fruits = ["Apples", "Oranges"]
$fruits.push("Plums", "Plums") → Returns 4; $fruits ["Apples", "Oranges", "Plums", "Plums"]
<Array>.pushUnique(members…)
→ number <Array>.pushUnique(members…)
→ 数字 Appends one or more unique members to the end of the base array and returns its new length.
向基本数组末尾追加一个或多个唯一成员,并返回其新长度。
v2.21.0
: Introduced. v2.21.0
: 引入。members
: (any…) The members to append.members
: (任何类型...) 要追加的成员。// Given: $fruits = ["Apples", "Oranges"]
$fruits.pushUnique("Apples") → Returns 2; $fruits ["Apples", "Oranges"]
// Given: $fruits = ["Apples", "Oranges"]
$fruits.pushUnique("Plums", "Plums") → Returns 3; $fruits ["Apples", "Oranges", "Plums"]
<Array>.random()
→ any <Array>.random()
→ 任何类型 Returns a random member from the base array. Does not modify the original.
从基本数组中返回一个随机成员。不会修改原始数组。
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.random() → Returns a random pie from the array
<Array>.randomMany(want)
→ Array<any> Randomly selects the given number of unique members from the base array and returns the selected members as a new array. Does not modify the original.
随机从基础数组中选择指定数量的唯一成员,并将所选成员作为新数组返回。不修改原始数组。
v2.20.0
: Introduced. v2.20.0
: 引入。want
: (integer) The number of members to select. Cannot select more members than the base array contains.// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.randomMany(3) → Returns a new array containing three unique random pies from the array
<Array>.shift()
→ any → 任何类型 Removes and returns the first member from the array, or undefined
if the array is empty.
移除并返回数组中的第一个成员,如果数组为空,则返回 undefined
。
// Given: $fruits = ["Apples", "Oranges", "Pears"]
$fruits.shift() → Returns "Apples"; $fruits ["Oranges", "Pears"]
<Array>.shuffle()
→ Array<any> Randomly shuffles the array.
随机打乱数组。
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.shuffle() → Randomizes the order of the pies in the array
<Array>.toShuffled()
→ Array<any> Returns a new copy of the base array created by shuffling the array. Does not modify the original.
返回一个新副本,该副本通过打乱数组创建,不会修改原始数组。
v2.37.0
: Introduced. v2.37.0
: 引入。// Given: $pies = ["Blueberry", "Cherry", "Cream", "Pecan", "Pumpkin"]
$pies.toShuffled() → Randomizes the order of the pies in the array w/o modifying the original
<Array>.toUnique()
→ Array<any> Returns a new copy of the base array created by removing all duplicate members. Does not modify the original.
返回一个新副本的基数组,通过删除所有重复成员创建。不会修改原始数组。
v2.37.0
: Introduced. v2.37.0
: 引入。// Given: $fruits = ["Apples", "Oranges", "Plums", "Plums", "Apples"]
$fruits.toUnique() → Returns ["Apples", "Oranges", "Plums"]
<Array>.unshift(members…)
→ number <Array>.unshift(members…)
→ 数字 Prepends one or more members to the beginning of the base array and returns its new length.
在基础数组开头添加一个或多个成员,并返回其新长度。
members
: (any…) The members to append.members
: (任何类型...) 要追加的成员。// Given: $fruits = ["Oranges", "Plums"]
$fruits.unshift("Oranges") → Returns 3; $fruits ["Oranges", "Oranges", "Plums"]
// Given: $fruits = ["Oranges", "Plums"]
$fruits.unshift("Apples", "Apples") → Returns 4; $fruits ["Apples", "Apples", "Oranges", "Plums"]
<Array>.unshiftUnique(members…)
→ number <Array>.unshiftUnique(members…)
→ 数字 Prepends one or more unique members to the beginning of the base array and returns its new length.
在基础数组开头添加一个或多个唯一成员,并返回其新长度。
v2.21.0
: Introduced. v2.21.0
: 引入。members
: (any…) The members to append.members
: (任何类型...) 要追加的成员。// Given: $fruits = ["Oranges", "Plums"]
$fruits.unshiftUnique("Oranges") → Returns 2; $fruits ["Oranges", "Plums"]
// Given: $fruits = ["Oranges", "Plums"]
$fruits.unshiftUnique("Apples", "Apples") → Returns 3; $fruits ["Apples", "Oranges", "Plums"]
<Array>.delete(needles…)
→ Array<any> Deprecated:
This instance method has been deprecated and should no longer be used. See the <Array>.deleteAll()
instance method.
已弃用:此实例方法已被弃用,不应再使用。请参阅 <Array>.deleteAll()
实例方法。
v2.5.0
: Introduced. v2.5.0
: 引入。v2.37.0
: Deprecated in favor of <Array>.deleteAll()
.<Array>.deleteAll()
。<jQuery>.ariaClick([options ,] handler)
→ jQuery
object <jQuery>.ariaClick([options ,] handler)
→ jQuery
对象 Makes the target element(s) WAI-ARIA-compatible clickables—meaning that various accessibility attributes are set and, in addition to mouse clicks, enter/return and spacebar key presses also activate them. Returns a reference to the current jQuery
object for chaining.
使目标元素(或元素组)成为 WAI-ARIA 兼容的可点击元素——这意味着设置了各种无障碍属性,除了鼠标点击外,回车键和空格键的按下也能激活它们。返回当前 jQuery
对象的引用以实现链式调用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Add tabindex
option.v2.37.0
: 添加 tabindex
选项。options
: (optional, object) The options to be used when creating the clickables. See below for details.handler
: (function) The callback to invoke when the target element(s) are activated.An options object should have some of the following properties:
选项对象应包含以下一些属性:
namespace
: (string) A period-separated list of event namespaces.one
: (boolean) Whether the clickables are single-use—i.e., the handler callback runs only once and then removes itself. If omitted, defaults to false
.false
。selector
: (string) A selector applied to the target element(s) to filter the descendants that triggered the event. If omitted or null
, the event is always handled when it reaches the target element(s).null
,则事件始终在到达目标元素(们)时被处理。data
: (any) Data to be passed to the handler in event.data
when an event is triggered.data
: (任何) 当触发事件时传递给处理器 event.data
的数据。tabindex
: (integer) Value for the tabindex
attribute. If omitted, defaults to 0
.tabindex
: (整数) tabindex
属性的值。如果省略,则默认为 0
。controls
: (string) Value for the aria-controls
attribute.controls
: (字符串) aria-controls
属性的值。pressed
: (string) Value for the aria-pressed
attribute (valid values: "true"
, "false"
).pressed
: (字符串) aria-pressed
属性的值(有效值: "true"
, "false"
)。label
: (string) Value for the aria-label
and title
attributes.label
: (字符串) aria-label
和 title
属性的值。// Given an existing element: <a id="so-clicky">Click me</a>
$('#so-clicky').ariaClick(function (event) {
/* do stuff */
});
// Creates a basic link and appends it to the `output` element
$('<a>Click me</a>')
.ariaClick(function (event) {
/* do stuff */
})
.appendTo(output);
// Creates a basic button and appends it to the `output` element
$('<button>Click me</button>')
.ariaClick(function (event) {
/* do stuff */
})
.appendTo(output);
// Creates a link with options and appends it to the `output` element
$('<a>Click me</a>')
.ariaClick({
one : true,
label : 'This single-use link does stuff.'
}, function (event) {
/* do stuff */
})
.appendTo(output);
<jQuery>.ariaDisabled(state)
→ jQuery
object <jQuery>.ariaDisabled(state)
→ jQuery
对象 Changes the disabled state of the target WAI-ARIA-compatible clickable element(s). Returns a reference to the current jQuery
object for chaining.
改变目标 WAI-ARIA 兼容的可点击元素(组)的禁用状态。返回当前 jQuery
对象的引用以实现链式调用。
Note:
This method is meant to work with clickables created via <jQuery>.ariaClick()
and may not work with clickables from other sources. SugarCube uses <jQuery>.ariaClick()
internally to handle all of its various link markup and macros.
注意:此方法旨在与通过 <jQuery>.ariaClick()
创建的可点击元素一起使用,可能不适用于来自其他来源的可点击元素。SugarCube 内部使用 <jQuery>.ariaClick()
来处理其各种链接标记和宏。
v2.26.0
: Introduced. v2.26.0
: 引入。state
: (boolean) The disabled state to apply. Truthy to disable the element(s), falsy to enable them.// Given an existing WAI-ARIA-compatible clickable element with the ID "so-clicky"
$('#so-clicky').ariaDisabled(true) → Disables the target element
$('#so-clicky').ariaDisabled(false) → Enables the target element
<jQuery>.ariaIsDisabled()
→ boolean
Returns whether any of the target WAI-ARIA-compatible clickable element(s) are disabled.
返回目标 WAI-ARIA 兼容的可点击元素是否被禁用。
Note:
This method is meant to work with clickables created via <jQuery>.ariaClick()
and may not work with clickables from other sources. SugarCube uses <jQuery>.ariaClick()
internally to handle all of its various link markup and macros.
注意:此方法旨在与通过 <jQuery>.ariaClick()
创建的可点击元素一起使用,可能不适用于来自其他来源的可点击元素。SugarCube 内部使用 <jQuery>.ariaClick()
来处理其各种链接标记和宏。
v2.26.0
: Introduced. v2.26.0
: 引入。// Given an existing WAI-ARIA-compatible clickable element with the ID "so-clicky"
// If "#so-clicky" is disabled:
$('#so-clicky').ariaIsDisabled() → Returns true
// If "#so-clicky" is enabled:
$('#so-clicky').ariaIsDisabled() → Returns false
jQuery.wiki(sources…)
Wikifies the given content source(s) and discards the result. If there were errors, an exception is thrown. This is only really useful when you want to invoke a macro for its side-effects and aren't interested in its output.
将给定的内容源进行维基化处理并丢弃结果。如果出现错误,将抛出异常。这仅在您只想调用宏以产生副作用而不关心其输出时才真正有用。
v2.17.0
: Introduced. v2.17.0
: 引入。sources
: (string…) The list of content sources.sources
: (字符串...) 内容源列表。$.wiki('<<somemacro>>'); → Invokes the <<somemacro>> macro, discarding any output
jQuery.wikiPassage(name)
Wikifies the passage by the given name and discards the result. If there were errors, an exception is thrown. This is only really useful when you want to invoke a macro for its side-effects and aren't interested in its output.
通过给定的名称对段落进行维基化处理并丢弃结果。如果出现错误,将抛出异常。这仅在您只想调用宏以产生副作用而不关心其输出时才真正有用。
v2.37.0
: Introduced. v2.37.0
: 引入。name
: (string) The name of the passage.name
: (字符串) 段落名称。$.wikiPassage('Fight Init'); → Renders the passage, discarding any output
<jQuery>.wiki(sources…)
→ jQuery
object <jQuery>.wiki(sources…)
→ jQuery
对象 Wikifies the given content source(s) and appends the result to the target element(s). Returns a reference to the current jQuery
object for chaining.
将给定内容源进行维基化,并将结果追加到目标元素中。返回当前 jQuery
对象的引用以进行链式调用。
v2.0.0
: Introduced. v2.0.0
: 引入。sources
: (string…) The list of content sources.sources
: (字符串...) 内容源列表。// Given an element: <div id="the-box"></div>
$('#the-box').wiki('Who //are// you?'); → Appends "Who <em>are</em> you?" to the target element
<jQuery>.wikiPassage(name)
→ jQuery
object <jQuery>.wikiPassage(name)
→ jQuery
对象 Wikifies the passage by the given name and appends the result to the target element(s). Returns a reference to the current jQuery
object for chaining.
将给定名称的段落进行维基化,并将结果附加到目标元素中。返回当前 jQuery
对象的引用以进行链式调用。
v2.37.0
: Introduced. v2.37.0
: 引入。name
: (string) The name of the passage.name
: (字符串) 段落名称。// Given an element: <div id="notebook"></div>
$('#notebook').wikiPassage('Notes'); → Appends the rendered passage to the target element
JSON.reviveWrapper(code [, data])
→ array JSON.reviveWrapper(code [, data])
→ 数组 Deprecated:
This static method has been deprecated and should no longer be used. See the Serial.createReviver()
static method.
已废弃:此静态方法已被废弃,不应再使用。请参阅 Serial.createReviver()
静态方法。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.9.0
: Added data
parameter.data
参数。v2.37.0
: Deprecated in favor of Serial.createReviver()
.Serial.createReviver()
。Math.clamp(num , min , max)
→ number Math.clamp(num , min , max)
→ 数字 Returns the given number clamped to the specified bounds. Does not modify the original.
返回给定数字的限定值,不修改原始值。
v2.0.0
: Introduced. v2.0.0
: 引入。num
: (number) The number to clamp. May be an actual number or a numerical string.num
: (数字) 要限定的数字。可以是实际数字或数值字符串。min
: (number) The lower bound of the number.min
: (数字) 数字的下限。max
: (number) The upper bound of the number.max
: (数字) 数字的上限。Math.clamp($stat, 0, 200) → Clamps $stat to the bounds 0–200 and returns the new value
Math.clamp($stat, 1, 6.6) → Clamps $stat to the bounds 1–6.6 and returns the new value
Math.trunc(num)
→ integer Math.trunc(num)
→ 整数 Returns the whole (integer) part of the given number by removing its fractional part, if any. Does not modify the original.
返回给定数字的整数部分,如果有的话,移除其小数部分。不会修改原始值。
num
: (number) The number to truncate to an integer.Math.trunc(12.7) → Returns 12
Math.trunc(-12.7) → Returns -12
<Number>.clamp(min , max)
→ number <Number>.clamp(min , max)
→ 数字 Deprecated:
This static method has been deprecated and should no longer be used. See the Math.clamp()
static method.
已弃用:此静态方法已被弃用,不应再使用。请参阅 Math.clamp()
静态方法。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。RegExp.escape(text)
→ string RegExp.escape(text)
→ 字符串 Returns the given string with all regular expression metacharacters escaped. Does not modify the original.
返回给定字符串中所有正则表达式元字符的转义形式。不修改原始字符串。
v2.0.0
: Introduced. v2.0.0
: 引入。text
: (string) The string to escape.RegExp.escape('That will be $5 (cash only)') → Returns 'That will be \$5 \(cash only\)'
Serial
Methods 方法Serial.createReviver(code [, data])
→ ArrayReturns the given code string, and optional data, wrapped within the deserialization reviver. Intended to allow authors to easily create the reviver required to revive their custom object types (classes). The reviver should be returned from an object instance's .toJSON()
method, so that the instance may be properly revived upon deserialization.
返回给定代码字符串和可选数据,并包裹在反序列化恢复器中。旨在允许作者轻松创建恢复自定义对象类型(类)所需的恢复器。恢复器应从对象实例的 .toJSON()
方法返回,以便在反序列化时正确恢复实例。
See:
The Non-generic object types (classes) guide for more detailed information.
查看更多详细信息,请参阅非通用对象类型(类)指南。
v2.37.0
: Introduced. v2.37.0
: 引入。code
: (string) The revival code string.code
: (字符串)复活代码字符串。data
: (optional, any) The data that should be made available to the evaluated revival code during deserialization via the special $ReviveData$
variable. WARNING: Attempting to pass the value of an object instance's this
directly as the reviveData
parameter will trigger out of control recursion in the serializer, so a clone of the instance's own data must be passed instead.$ReviveData$
提供给评估恢复代码的数据。警告:直接将对象实例的 this
值作为 reviveData
参数传递将触发序列化器中的无限递归,因此必须传递实例自身数据的副本。Serial.createReviver( /* valid JavaScript code string */ ); → Without data chunk
Serial.createReviver( /* valid JavaScript code string */ , myOwnData); → With data chunk
// E.g., Assume that you're attempting to revive an instance of a custom class named
// `Character`, which is assigned to a story variable named `$pc`. The call
// to `Serial.createReviver()` might look something like the following.
var ownData = {};
Object.keys(this).forEach(function (pn) { ownData[pn] = clone(this[pn]); }, this);
return Serial.createReviver('new Character($ReviveData$)', ownData);
Note:
Strings in TwineScript/JavaScript are Unicode, however, due to historic reasons they are comprised of, and indexed by, individual UTF-16 code units rather than code points. This means that some code points may span multiple code units—e.g., the emoji 💩 is one code point, but two code units.
注意:TwineScript/JavaScript 中的字符串是 Unicode,但由于历史原因,它们由单个 UTF-16 代码单元组成,而不是代码点。这意味着一些代码点可能跨越多个代码单元——例如,表情符号 💩 是一个代码点,但由两个代码单元组成。
<String>.count(needle [, position])
→ integer <String>.count(needle [, position])
→ 整数 Returns the number of times that the given substring was found within the string, starting the search at position
.
返回给定子字符串在字符串中出现的次数,搜索从 position
开始。
v2.0.0
: Introduced. v2.0.0
: 引入。needle
: (any) The substring to count.needle
: (任意) 要计数的子串。position
: (optional, integer) The zero-based index at which to begin searching for needle
. If omitted, will default to 0
.needle
。如果省略,则默认为 0
。// Given: $text = "How now, brown cow."
$text.count("ow") → Returns 4
$text.count("ow", 8) → Returns 2
<String>.first()
→ string <String>.first()
→ 字符串 Returns the first Unicode code point within the string. Does not modify the original.
返回字符串中的第一个 Unicode 码点。不修改原始字符串。
See:
String methods note.
查看:字符串方法说明。
v2.27.0
: Introduced. v2.27.0
: 引入。// Given: $text = "abc"
$text.first() → Returns "a"
// Given: $text = "🙈🙉🙊"
$text.first() → Returns "🙈"
String.format(format , arguments…)
→ string String.format(format , arguments…)
→ 字符串 Returns a formatted string, after replacing each format item in the given format string with the text equivalent of the corresponding argument's value.
返回一个格式化后的字符串,将给定格式字符串中的每个格式项替换为相应参数值的文本等效项。
v2.0.0
: Introduced. v2.0.0
: 引入。format
: (string) The format string, which consists of normal text and format items.format
: (字符串) 由普通文本和格式项组成的格式字符串。arguments
: (any… | Array<any>) Either a list of arguments, which correspond by-index to the format items within the format string, or an array, whose members correspond by-index.arguments
: (any… | Array) 可以是一个与格式字符串中的格式项按索引对应参数列表,或者一个数组,其成员按索引对应。A format item has the syntax {index[,alignment]}
, square-brackets denoting optional elements.
格式项的语法为 {index[,alignment]}
,方括号表示可选元素。
index
: (integer) The (zero-based) index of the argument whose string representation will replace the format item.index
: (整数) 要替换格式项的参数字符串表示形式的(基于 0 的)索引。alignment
: (optional, integer) The total length of the field into which the argument is inserted, and whether it's right- or left-aligned (positive aligns right, negative aligns left).alignment
: (可选,整数) 将参数插入的字段的总长度,以及它是右对齐还是左对齐(正数右对齐,负数左对齐)。String.format("{0}, {1}!", "Hello", "World") → List of arguments; Returns "Hello, World!"
String.format("{0}, {1}!", [ "Hello", "World" ]) → Array argument; Returns "Hello, World!"
String.format("{0,6}", "foo") → Returns " foo"
String.format("{0,-6}", "foo") → Returns "foo "
<String>.includes(needle [, position])
→ boolean <String>.includes(needle [, position])
→ 布尔值 Returns whether the given substring was found within the string, starting the search at position
.
返回是否在字符串中找到了指定的子串,搜索从 position
开始。
needle
: (any) The substring to find.needle
: (任何) 要查找的子串。position
: (optional, integer) The zero-based index at which to begin searching for needle
. If omitted, will default to 0
.needle
。如果省略,则默认为 0
。// Given: $text = "How now, brown cow."
$text.includes("row") → Returns true
$text.includes("row", 14) → Returns false
$text.includes("cow", 14) → Returns true
$text.includes("pow") → Returns false
<String>.last()
→ string <String>.last()
→ 字符串 Returns the last Unicode code point within the string. Does not modify the original.
返回字符串中的最后一个 Unicode 码点。不修改原始字符串。
See:
String methods note.
查看:字符串方法说明。
v2.27.0
: Introduced. v2.27.0
: 引入。// Given: $text = "abc"
$text.last() → Returns "c"
// Given: $text = "🙈🙉🙊"
$text.last() → Returns "🙊"
<String>.toLocaleUpperFirst()
→ string <String>.toLocaleUpperFirst()
→ 字符串 Returns the string with its first Unicode code point converted to upper case, according to any locale-specific rules. Does not modify the original.
返回将字符串的第一个 Unicode 码点根据任何区域设置规则转换为大写的字符串,而不修改原始字符串。
See:
String methods note.
查看:字符串方法说明。
v2.9.0
: Introduced. v2.9.0
: 引入。// Using the Turkish (Türkçe) locale and given: $text = "ışık"
$text.toLocaleUpperFirst() → Returns "Işık"
// Using the Turkish (Türkçe) locale and given: $text = "iki"
$text.toLocaleUpperFirst() → Returns "İki"
<String>.toUpperFirst()
→ string <String>.toUpperFirst()
→ 字符串 Returns the string with its first Unicode code point converted to upper case. Does not modify the original.
将字符串的第一个 Unicode 码点转换为大写。不会修改原始字符串。
See:
String methods note.
查看:字符串方法说明。
v2.9.0
: Introduced. v2.9.0
: 引入。// Given: $text = "hello."
$text.toUpperFirst() → Returns "Hello."
// Given: $text = "χαίρετε."
$text.toUpperFirst() → Returns "Χαίρετε."
Passage, tag, and variable names that have special meaning to SugarCube.
SugarCube 中具有特殊意义的段落、标签和变量名称。
Passages that are used only as code and should not be navigated to. They exist simply to fill in parts of the UI—e.g., StoryCaption
—or execute code at specific times—e.g., PassageReady
—or both—e.g., PassageHeader
.
仅用作代码且不应进行导航的段落。它们仅存在于填充 UI 的部分——例如, StoryCaption
——或执行特定时间的代码——例如, PassageReady
——或两者兼而有之——例如, PassageHeader
。
PassageDone
Used for post-passage-display tasks, like redoing dynamic changes (happens after the rendering and display of each passage). Generates no output.
用于段落显示后的任务,如重新执行动态更改(在每个段落渲染和显示后发生)。不生成任何输出。
Roughly equivalent to the :passagedisplay
event.
大约等同于 :passagedisplay
事件。
v2.0.0
: Introduced. v2.0.0
: 引入。PassageFooter
Appended to each rendered passage.
追加到每个渲染段落之后。
Roughly equivalent to the :passagerender
event.
大约等同于 :passagerender
事件。
v2.0.0
: Introduced. v2.0.0
: 引入。PassageHeader
Prepended to each rendered passage.
预加到每个渲染段落之前。
Roughly equivalent to the :passagestart
event.
大约等同于 :passagestart
事件。
v2.0.0
: Introduced. v2.0.0
: 引入。PassageReady
Used for pre-passage-display tasks, like redoing dynamic changes (happens before the rendering of each passage). Generates no output.
用于段落显示前的任务,如重新执行动态更改(在每个段落渲染前发生)。不生成任何输出。
Roughly equivalent to the :passagestart
event.
大约等同于 :passagestart
事件。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryAuthor
Used to populate the authorial byline area in the UI bar (element ID: story-author
).
用于填充 UI 栏中的作者署名区域(元素 ID: story-author
)。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryBanner
Used to populate the story's banner area in the UI bar (element ID: story-banner
).
用于填充 UI 栏中的故事横幅区域(元素 ID: story-banner
)。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryCaption
Used to populate the story's caption area in the UI bar (element ID: story-caption
). May also be, and often is, used to add additional story UI elements and content to the UI bar.
用于填充 UI 栏中的故事标题区域(元素 ID: story-caption
)。也可能,并且经常用于,向 UI 栏添加额外的故事 UI 元素和内容。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryDisplayTitle
Sets the story's display title in the browser's titlebar and the UI bar (element ID: story-title
). If omitted, the story title will be used instead.
设置故事在浏览器标题栏和 UI 栏中的显示标题(元素 ID: story-title
)。如果省略,则使用故事标题。
v2.31.0
: Introduced. v2.31.0
: 引入。StoryInit
Used for pre-story-start initialization tasks, like variable initialization (happens at the beginning of story initialization). Generates no output.
用于故事开始前的初始化任务,如变量初始化(在故事初始化开始时发生)。不产生输出。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryInterface
Used to replace SugarCube's default UI. Its contents are treated as raw HTML markup—i.e., none of SugarCube's special HTML processing is performed. The markup is contained within a <div id="story" role="main">
element and must itself contain, at least, an element with the ID passages
that will be the main passage display area. For example:
用于替换 SugarCube 的默认 UI。其内容被视为原始 HTML 标记——即,不执行 SugarCube 的特殊 HTML 处理。标记包含在 <div id="story" role="main">
元素中,并且必须本身包含至少一个具有 ID passages
的元素,该元素将是主要段落显示区域。例如:
<div id="story" role="main">
<!-- StoryInterface elements added here -->
</div>
Additional elements, aside from the #passages
element, may include either the data-init-passage
or data-passage
content attribute, whose value is the name of the passage used to populate the element—the passage will be processed as normal, meaning that markup and macros will work as expected. The data-init-passage
attribute causes the element to be updated once at initialization, while the data-passage
attribute causes the element to be updated upon each passage navigation.
除了 #passages
元素外,还可能包括 data-init-passage
或 data-passage
内容属性,其值是用于填充元素的段落名称——该段落将按正常方式处理,即标记和宏将按预期工作。 data-init-passage
属性会导致元素在初始化时更新一次,而 data-passage
属性会导致元素在每次段落导航时更新。
Warning:
Elements that include either a data-init-passage
or data-passage
content attribute should not themselves contain additional elements. This is because such elements' contents are replaced via their associated passage, so any child elements will be lost.
警告:包含 data-init-passage
或 data-passage
内容属性的元素本身不应包含其他元素。这是因为此类元素的 内容将通过其关联的段落进行替换,因此任何子元素都将丢失。
v2.18.0
: Introduced. v2.18.0
: 引入。v2.28.0
: Added processing of the data-passage
content attribute.v2.28.0
: 添加了对 data-passage
内容属性的解析处理。v2.36.0
: Added processing of the data-init-passage
content attribute.v2.36.0
: 添加了对 data-init-passage
内容属性的解析处理。v2.37.0
: Fixed processing of the data-init-passage
content attribute. Added the <div#story>
container element.v2.37.0
: 修复了对 data-init-passage
内容属性的解析处理。添加了 <div#story>
容器元素。<div id="passages"></div>
Combined with the built-in wrapper:
结合内置包装器:
<div id="story" role="main">
<div id="passages"></div>
</div>
data-init-passage
and data-passage
content attributesdata-init-passage
和 data-passage
内容属性<div id="menu" data-init-passage="Menu"></div>
<div id="notifications" data-passage="Notifications"></div>
<div id="passages"></div>
Combined with the built-in wrapper:
结合内置包装器:
<div id="story" role="main">
<div id="menu" data-init-passage="Menu"></div>
<div id="notifications" data-passage="Notifications"></div>
<div id="passages"></div>
</div>
StoryMenu
Used to populate the story's menu items in the UI bar (element ID: menu-story
).
用于填充故事菜单项在 UI 栏中(元素 ID: menu-story
)。
Note:
The story menu only displays links—specifically, anything that creates an anchor element (<a>
). While it renders content just as any other passage does, instead of displaying the rendered output as-is, it sifts through the output and builds its menu from the generated links contained therein.
注意:故事菜单仅显示链接——具体来说,任何创建锚点元素( <a>
)的内容。虽然它渲染内容的方式与任何其他段落相同,但它不会直接显示渲染后的输出,而是从生成的链接中筛选并构建菜单。
v2.0.0
: Introduced. v2.0.0
: 引入。[[Inventory]]
<<link "Schedule">>…<</link>>
StorySettings
Warning:
Twine 1.4 code passage unused by SugarCube. The Config
API serves the same basic purpose.
警告:Twine 1.4 代码段落在 SugarCube 中未使用。 Config
API 具有相同的基本功能。
StorySubtitle
Sets the story's subtitle in the UI bar (element ID: story-subtitle
).
在 UI 栏中设置故事的副标题(元素 ID: story-subtitle
)。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryTitle
Warning:
The story title is used to create the storage ID that is used to store all player data, both temporary and persistent. It should be plain text, containing no code, markup, or macros of any kind.
警告:故事标题用于创建存储 ID,该 ID 用于存储所有玩家数据,包括临时数据和持久数据。它应该是纯文本,不包含任何代码、标记或宏。
Tip:
If you want to set a title for display that contains code, markup, or macros, see the StoryDisplayTitle
code passage.
提示:如果您想设置包含代码、标记或宏的显示标题,请参阅第 0#代码段落。
Twine 2: Unused, not a code passage. The story's title is part of the story project.
Twine 2:未使用,不是代码段落。故事标题是故事项目的一部分。
Twine 1/Twee: Required. Sets the story's title.
Twine 1/Twee:必需。设置故事的标题。
v2.0.0
: Introduced. v2.0.0
: 引入。StoryShare
Deprecated:
This special passage has been deprecated and should no longer be used.
已弃用:此特殊段落已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Passages that receive some kind of special treatment from the engine.
段落收到来自引擎的特殊处理。
Note:
Some special passages are conditional and may not always be special passages. The conditions will be noted within each such passsge's entry.
注意:某些特殊段落是条件性的,并不总是特殊段落。条件将在每个此类段落的条目中注明。
Start
Twine 2: Not a special passage. Any passage may be chosen as the starting passage by selecting it via the Start Story Here passage context-menu item—n.b. older versions of Twine 2 used a icon for the same purpose.
Twine 2:不是特殊段落。任何段落都可以通过选择“从这里开始故事”的段落上下文菜单项来作为起始段落——请注意,Twine 2 的旧版本用于此目的的是图标。
Twine 1/Twee: Required. The starting passage, the first passage displayed. Configurable, see Config.passages.start
for more information.
Twine 1/Twee:必需。起始段落,第一个显示的段落。可配置,见 Config.passages.start
获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。Passages tagged with code tags are used only as code or data and cannot be navigated to.
带有代码标签的段落仅用作代码或数据,不能进行导航。
Note:
Some code tags are conditional and may not always act as code tags. The conditions will be noted within each such tag's entry.
备注:某些代码标签是条件性的,不一定总是作为代码标签使用。这些标签的条件将在每个此类标签的条目中注明。
init
Registers the passage as an initialization passage. Used for pre-story-start initialization tasks, like variable initialization (happens at the beginning of story initialization). Generates no output.
注册为初始化段落。用于故事开始前的初始化任务,如变量初始化(在故事初始化开始时发生)。不产生输出。
Note:
This is chiefly intended for use by add-ons/libraries. For normal projects, authors are strongly encouraged to continue to use the StoryInit
special named passage.
注意:本指南主要面向插件/库的使用。对于常规项目,强烈建议作者继续使用 StoryInit
特殊命名段落。
v2.36.0
: Introduced. v2.36.0
: 引入。script
Twine 2: Unused, not a code tag. Use the Edit Story JavaScript story editor menu item for scripts.
Twine 2:未使用,不是一个代码标签。请使用“编辑故事”JavaScript 故事编辑菜单项进行脚本编辑。
Twine 1/Twee: Registers the passage as JavaScript code, which is executed during startup.
Twine 1/Twee:将段落注册为 JavaScript 代码,在启动时执行。
v2.0.0
: Introduced. v2.0.0
: 引入。stylesheet
Twine 2: Unused, not a code tag. Use the Edit Story Stylesheet story editor menu item for styles.
Twine 2:未使用,不是一个代码标签。请使用“编辑故事”样式表故事编辑菜单项进行样式编辑。
Twine 1/Twee: Registers the passage as a CSS stylesheet, which is loaded during startup. It is strongly recommended that you use only one stylesheet passage. Additionally, see the tagged stylesheet warning.
Twine 1/Twee:将段落注册为 CSS 样式表,在启动时加载。强烈建议您只使用一个样式表段落。另外,请参阅带标签的样式表警告。
v2.0.0
: Introduced. v2.0.0
: 引入。Twine.audio
Registers the passage as an audio passage. See Guide: Media Passages for more information.
将段落注册为音频段落。请参阅指南:媒体段落以获取更多信息。
v2.24.0
: Introduced. v2.24.0
: 引入。Twine.image
Registers the passage as an image passage. See Guide: Media Passages for more information.
将段落注册为图片段落。请参阅指南:媒体段落以获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。Twine.video
Registers the passage as a video passage. See Guide: Media Passages for more information.
注册段落为视频段落。请参阅指南:媒体段落获取更多信息。
v2.24.0
: Introduced. v2.24.0
: 引入。Twine.vtt
Registers the passage as a VTT passage. See Guide: Media Passages for more information.
注册段落为 VTT 段落。请参阅指南:媒体段落以获取更多信息。
v2.24.0
: Introduced. v2.24.0
: 引入。widget
Registers the passage as <<widget>>
macro definitions, which are loaded during startup.
注册段落为 <<widget>>
宏定义,这些定义在启动时加载。
v2.0.0
: Introduced. v2.0.0
: 引入。nobr
Causes leading/trailing newlines to be removed and all remaining sequences of newlines to be replaced with single spaces before the passage is rendered. Equivalent to wrapping the entire passage in a <<nobr>>
macro. See the Config.passages.nobr
setting for a way to apply the same processing to all passages at once.
导致首尾换行符被删除,并在渲染段落之前将所有剩余的换行序列替换为单个空格。相当于将整个段落包裹在 <<nobr>>
宏中。请参阅 Config.passages.nobr
设置,了解如何一次性将相同的处理应用于所有段落。
Note:
Does not affect script
or stylesheet
tagged passages, for Twine 1/Twee.
注意:不影响 script
或 stylesheet
标记的段落,对于 Twine 1/Twee。
v2.0.0
: Introduced. v2.0.0
: 引入。bookmark
Deprecated:
This special tag has been deprecated and should no longer be used.
已弃用:此特殊标签已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。$
Alias for jQuery
, by default. NOTE: This should not be confused with story variables, which start with a $
—e.g., $foo
.
jQuery
的别名,默认情况下。注意:这不应与以 $
开头的剧情变量混淆——例如, $foo
。
v2.0.0
: Introduced. v2.0.0
: 引入。_args
Widget arguments array (only inside widgets). See <<widget>>
for more information.
小部件参数数组(仅在小部件内部)。有关更多信息,请参阅 <<widget>>
。
v2.36.0
: Introduced. v2.36.0
: 引入。_contents
Widget contents string (only inside block widgets). See <<widget>>
for more information.
小部件内容字符串(仅在小部件块内部)。有关更多信息,请参阅 <<widget>>
。
v2.36.0
: Introduced. v2.36.0
: 引入。Config
Configuration API. See Config
API for more information.
配置 API。有关更多信息,请参阅 Config
API。
v2.0.0
: Introduced. v2.0.0
: 引入。Dialog
Dialog API. See Dialog
API for more information.
对话 API。更多信息请参阅 Dialog
API。
v2.0.0
: Introduced. v2.0.0
: 引入。Engine
Engine API. See Engine
API for more information.
引擎 API。更多信息请参阅 Engine
API。
v2.0.0
: Introduced. v2.0.0
: 引入。Fullscreen
Fullscreen API. See Fullscreen
API for more information.
全屏 API。更多信息请参阅 Fullscreen
API。
v2.31.0
: Introduced. v2.31.0
: 引入。jQuery
jQuery library function.
jQuery 库函数。
v2.0.0
: Introduced. v2.0.0
: 引入。l10nStrings
Strings localization object. See Localization for more information.
字符串本地化对象。请参阅本地化获取更多信息。
v2.10.0
: Introduced. v2.10.0
: 引入。LoadScreen
LoadScreen API. See LoadScreen
API for more information.
加载屏幕 API。请参阅 LoadScreen
API 获取更多信息。
v2.15.0
: Introduced. v2.15.0
: 引入。Macro
Macro API. See Macro
API for more information.
宏 API。请参阅 Macro
API 获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。Passage
Passage API. See Passage
API for more information.
Passage API。请参阅 Passage
API 获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。Save
Save API. See Save
API for more information.
保存 API。请参阅 Save
API 获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。Setting
Setting API. See Setting
API for more information.
设置 API。请参阅 Setting
API 获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。settings
Player settings object, set up by the author/developer. See Setting
API for more information.
玩家设置对象,由作者/开发者设置。请参阅 Setting
API 获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。setup
Object that authors/developers may use to set up various bits of static data. Generally, you would use this for data that does not change and should not be stored within story variables, which would make it part of the history.
对象,作者/开发者可以使用它来设置各种静态数据。通常,您会使用此对象来存储不更改且不应存储在故事变量中的数据,这样它就会成为历史的一部分。
v2.0.0
: Introduced. v2.0.0
: 引入。SimpleAudio
SimpleAudio API. See SimpleAudio
API for more information.
简单音频 API。查看 SimpleAudio
API 获取更多信息。
v2.28.0
: Introduced. v2.28.0
: 引入。State
State API. See State
API for more information.
状态 API。更多信息请参阅 State
API。
v2.0.0
: Introduced. v2.0.0
: 引入。Story
Story API. See Story
API for more information.
故事 API。查看 Story
API 获取更多信息。
v2.0.0
: Introduced. v2.0.0
: 引入。Template
Template API. See Template
API for more information.
模板 API。查看 Template
API 获取更多信息。
v2.29.0
: Introduced. v2.29.0
: 引入。UI
UI API. See UI
API for more information.
UI API。更多信息请参阅 UI
API。
v2.0.0
: Introduced. v2.0.0
: 引入。UIBar
UIBar API. See UIBar
API for more information.
UIBar API。更多信息请参阅 UIBar
API。
v2.17.0
: Introduced. v2.17.0
: 引入。$args
Deprecated:
The $args
special variable has been deprecated and should no longer be used. See the _args
special variable for its replacement.
已弃用:特殊变量 $args
已被弃用,不应再使用。请使用 _args
特殊变量作为替代。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.36.0
: Deprecated. v2.36.0
: 已废弃。postdisplay
Deprecated:
postdisplay
tasks have been deprecated and should no longer be used. See the :passagedisplay
event for its replacement.
已弃用: postdisplay
任务已被弃用,不应再使用。请参阅 :passagedisplay
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。postrender
Deprecated:
postrender
tasks have been deprecated and should no longer be used. See the :passagerender
event for its replacement.
已弃用: postrender
任务已被弃用,不应再使用。请参阅 :passagerender
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。predisplay
Deprecated:
predisplay
tasks have been deprecated and should no longer be used. See the :passagestart
event for its replacement.
已弃用: predisplay
任务已被弃用,不应再使用。请参阅 :passagestart
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。prehistory
Deprecated:
prehistory
tasks have been deprecated and should no longer be used. See the :passageinit
event for its replacement.
已弃用: prehistory
任务已被弃用,不应再使用。请参阅 :passageinit
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。prerender
Deprecated:
prerender
tasks have been deprecated and should no longer be used. See the :passagestart
event for its replacement.
已弃用: prerender
任务已被弃用,不应再使用。请参阅 :passagestart
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。IDs and classes automatically generated from passage names and tags are normalized to kebab case with all lowercase letters—which entails: removing characters that are not alphanumerics, underscores, hyphens, en-/em-dashes, or whitespace, then replacing any remaining non-alphanumeric characters with hyphens, one per group, and finally converting the result to lowercase.
从段落名称和标签自动生成的 ID 和类会被转换为短横线命名法,全部小写——具体操作包括:移除非字母数字、下划线、短横线、破折号或空格的字符,然后将任何剩余的非字母数字字符替换为短横线,每组一个,最后将结果转换为小写。
Passage names have passage-
prepended to their converted forms and are converted both into IDs and classes depending on how the passage is used—an ID for the active passage, classes for included (via <<include>>
) passages.
段落名称会在其转换形式前添加 passage-
前缀,并根据段落的使用方式转换为 ID 和类——ID 用于活动段落,类用于包含的(通过 <<include>>
)段落。
For example, if the passage name was Gone fishin'
, then:
例如,如果段落名称是 Gone fishin'
,那么:
passage-gone-fishin
(selector: #passage-gone-fishin
).passage-gone-fishin
(选择器: #passage-gone-fishin
)。passage-gone-fishin
(selector: .passage-gone-fishin
).passage-gone-fishin
(选择器: .passage-gone-fishin
)。When displaying a passage, its tags are:
当显示段落时,其标签为:
<html>
element, and <body>
element as a space separated list within the data-tags
attribute.<html>
元素和 <body>
元素中,作为 data-tags
属性内的空格分隔列表。<body>
element as classes. The following special tags are excluded from this mapping:
<body>
元素中作为类。以下特殊标签不包括在此映射中:Twine 2: Twine 2: | debug , nobr , passage , widget , and any tag starting with twine. debug 、 nobr 、 passage 、 widget 以及以 twine. 开头的任何标签。 |
---|---|
Twine 1/Twee: Twine 1/Twee: | debug , nobr , passage , script , stylesheet , widget , and any tag starting with twine. debug , nobr , passage , script , stylesheet , widget 以及任何以 twine. 开头的标签 |
For example, if the tag name was Sector_42
, then it would become both the data-tags
attribute member Sector_42
(selector: [data-tags~="Sector_42"]
) and the class sector-42
(selector: .sector-42
).
例如,如果标签名称是 Sector_42
,那么它将同时成为 data-tags
属性成员 Sector_42
(选择器: [data-tags~="Sector_42"]
)和类 sector-42
(选择器: .sector-42
)。
Selector 选择器 | Description 描述 |
---|---|
html |
The document element. The default font stack is set here. The active passage's tags will be added to its |
body |
The body of the page. The default foreground and background colors are set here. The active passage's tags will be added to its |
#story |
Selects the story element. 选择故事元素。 |
#passages |
Selects the element that contains passage elements. All created passage elements will be children of this element. 选择包含段落元素的元素。所有创建的段落元素都将成为该元素的子元素。 |
.passage |
Selects the passage element. Normally, there will be only one such passage per turn, however, during passage navigation there may briefly be two—the incoming (a.k.a. active) and outgoing passages. The active passage's name will be added as its ID (see: Passage Conversions). The active passage's tags will be added to its |
.passage a |
Selects all <a> elements within the passage element.选择段落元素内的所有 <a> 元素。 |
.passage a:hover |
Selects <a> elements within the passage element that are being hovered over.选择段落元素内被悬停的 <a> 元素。 |
.passage a:active |
Selects <a> elements within the passage element that are being clicked on.选择段落元素内被点击的 <a> 元素。 |
.passage .link-broken |
Selects all internal link elements within the passage element whose passages do not exist within the story. 选择段落元素中所有内部链接元素,这些段落元素中的段落在故事中不存在。 |
.passage .link-disabled |
Selects all internal link elements within the passage element who have been disabled—e.g., already chosen <<choice>> macro links.选择段落元素内所有已被禁用的内部链接元素——例如,已选择的 <<choice>> 宏链接。 |
.passage .link-external |
Selects all external link elements within the passage element—e.g., links to other pages and websites. 选择段落元素内的所有外部链接元素——例如,指向其他页面和网站的链接。 |
.passage .link-internal |
Selects all internal link elements within the passage element—e.g., passage and macro links. 选择段落元素内的所有内部链接元素——例如段落和宏链接。 |
.passage .link-visited1 |
Selects all internal link elements within the passage element whose passages are within the in-play story history—i.e., passages the player has been to before. 选择段落元素内的所有内部链接元素,这些链接的段落位于游戏故事历史中——即玩家之前访问过的段落。 |
.passage .link-internal:not(.link-visited)1 |
Selects all internal link elements within the passage element whose passages are not within the in-play story history—i.e., passages the player has never been to before. 选择所有在段落元素内的内部链接元素,这些段落元素的内容不在游戏故事历史中——即玩家从未去过的地方的段落。 |
.link-visited
class is not enabled by default, see the Config
API's Config.addVisitedLinkClass
property for more information..link-visited
类默认未启用,请参阅 Config
API 的 Config.addVisitedLinkClass
属性获取更多信息。When using Twine 1/Twee, it is strongly recommended that you use only a single stylesheet
tagged passage. CSS styles cascade in order of load, so if you use multiple stylesheet
tagged passages, then it is all too easy for your styles to be loaded in the wrong order, since Twine 1/Twee gives you no control over the order that multiple stylesheet
tagged passages load.
当使用 Twine 1/Twee 时,强烈建议您只使用一个 stylesheet
标记的段落。CSS 样式按加载顺序级联,因此如果您使用多个 stylesheet
标记的段落,那么您的样式很容易被加载到错误的顺序,因为 Twine 1/Twee 无法控制多个 stylesheet
标记的段落加载的顺序。
SugarCube does not support the Twine 1.4+ vanilla story formats' tagged stylesheets. In SugarCube, you would instead simply prefix the selectors of your styles with the appropriate tag-based selectors—e.g., either [data-tags~="…"]
attribute selectors or class selectors.
SugarCube 不支持 Twine 1.4+ 原生故事格式的标签样式表。在 SugarCube 中,您只需在您的样式选择器前加上适当的基于标签的选择器即可——例如,使用 [data-tags~="…"]
属性选择器或类选择器。
For example, if some story passages were tagged with forest
, then styles for those forest passages might look like this:
例如,如果某些故事段落被标记为 forest
,那么这些段落对应的样式可能如下所示:
/* Using [data-tags~="…"] attribute selectors on <html> */
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> */
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> */
body.forest { background-image: url(forest-bg.jpg); }
body.forest .passage { color: darkgreen; }
body.forest a { color: green; }
body.forest a:hover { color: lime; }
These are SugarCube's built-in stylesheets, in order of load/cascade. The most interesting of which, from an end-user's standpoint, are 5–13. The links go to the most recent release versions of each in SugarCube's source code repository.
这些是 SugarCube 的内置样式表,按加载/层叠顺序排列。其中,从最终用户的角度来看,最有趣的是 5-13 号。链接指向 SugarCube 源代码仓库中每个的最新发布版本。
normalize.css
init-screen.css
font-icons.css
font-emoji.css
core.css
core-display.css
core-passage.css
core-macro.css
ui-dialog.css
ui-dialog-saves.css
ui-dialog-settings.css
ui-dialog-legacy.css
ui-bar.css
ui-debug-bar.css
ui-debug-views.css
The hierarchy of the document body, including associated HTML IDs and class names is as follows.
文档体的层次结构,包括相关的 HTML ID 和类名如下。
…
) signify data that is dynamically generated at run time.…
)表示在运行时动态生成的数据。#story-title-separator
element is normally unused.#story-title-separator
元素通常不使用。#menu-story
, will only exist if the StoryMenu
special passage is used.StoryMenu
特殊段落,则存在故事菜单 #menu-story
。#menu-item-continue
, will only exist if a browser save (auto or slot) exists.#menu-item-continue
仅在存在浏览器保存(自动或槽)时存在。#menu-item-settings
, will only exist if the Setting
API is used.#menu-item-settings
仅在使用了 Setting
API 时存在。<body class="…">
<div id="init-screen"></div>
<div id="ui-overlay" class="ui-close"></div>
<div id="ui-dialog" tabindex="0" role="dialog" aria-labelledby="ui-dialog-title">
<div id="ui-dialog-titlebar">
<h1 id="ui-dialog-title"></h1>
<button id="ui-dialog-close" class="ui-close" tabindex="0" aria-label="…"></button>
</div>
<div id="ui-dialog-body"></div>
</div>
<div id="ui-bar">
<div id="ui-bar-tray">
<button id="ui-bar-toggle" tabindex="0" title="…" aria-label="…"></button>
<div id="ui-bar-history">
<button id="history-backward" tabindex="0" title="…" aria-label="…">…</button>
<button id="history-jumpto" tabindex="0" title="…" aria-label="…">…</button>
<button id="history-forward" tabindex="0" title="…" aria-label="…">…</button>
</div>
</div>
<div id="ui-bar-body">
<header id="title" role="banner">
<div id="story-banner"></div>
<h1 id="story-title"></h1>
<div id="story-subtitle"></div>
<div id="story-title-separator"></div>
<p id="story-author"></p>
</header>
<div id="story-caption"></div>
<nav id="menu" role="navigation">
<ul id="menu-story">…<ul>
<ul id="menu-core">
<li id="menu-item-continue"><a tabindex="0">…</a></li>
<li id="menu-item-saves"><a tabindex="0">…</a></li>
<li id="menu-item-settings"><a tabindex="0">…</a></li>
<li id="menu-item-restart"><a tabindex="0">…</a></li>
</ul>
</nav>
</div>
</div>
<div id="story" role="main">
<div id="passages">
<div class="passage …" id="…" data-passage="…">
<!-- The active (present) passage content -->
</div>
</div>
</div>
<!-- The story data chunk, which depends on the compiler release (see below) -->
<script id="script-sugarcube" type="text/javascript"><!-- The main SugarCube module --></script>
</body>
Periods of ellipsis (…
) signify data that is generated at compile time.
省略号( …
)表示在编译时生成的数据。
<tw-storydata name="…" startnode="…" creator="…" creator-version="…"
ifid="…" zoom="…" format="…" format-version="…" options="…" hidden>
<!-- Passage data nodes… -->
</tw-storydata>
<div id="store-area" data-size="…" hidden>
<!-- Passage data nodes… -->
</div>
Events are messages that are sent (a.k.a.: fired, triggered) to notify code that something has taken place, from player interactions to automated happenings. Each event is represented by an object that has properties that may be used to get additional information about what happened.
事件是发送(即:触发、引发)的消息,用于通知代码发生了某些事情,从玩家交互到自动发生的事件。每个事件都由一个具有可能用于获取有关发生情况额外信息的属性的对象表示。
This section offers a list of SugarCube-specific events, triggered at various points during story operation.
本节提供了 SugarCube 特有的事件列表,这些事件在故事操作的不同阶段被触发。
See Also:
For standard browser/DOM events, see the Event reference @MDN.
参考以下内容:有关标准浏览器/DOM 事件,请参阅 MDN 的事件参考。
Dialog
Events 事件Dialog
events allow the execution of JavaScript code at specific points during the opening and closing of dialogs.
Dialog
事件允许在对话框打开和关闭的特定点执行 JavaScript 代码。
See:
Dialog
API.
查看: Dialog
API。
:dialogclosed
event :dialogclosed
事件 Global event triggered as the last step in closing the dialog when Dialog.close()
is called.
当调用 Dialog.close()
时,作为关闭对话框的最后一步触发的全局事件。
Warning:
You cannot obtain data about the closing dialog from the dialog itself—e.g., title or classes—when using the :dialogclosed
event, as the dialog has already closed and been reset by the time the event is fired. If you need that kind of information from the dialog itself, then you may use the :dialogclosing
event instead.
警告:在使用 :dialogclosed
事件时,您无法从对话框本身获取关于关闭对话框的数据(例如标题或类),因为对话框在事件触发时已经关闭并被重置。如果您需要从对话框本身获取此类信息,则可以使用 :dialogclosing
事件。
v2.29.0
: Introduced. v2.29.0
: 引入。Note:
While there are no custom properties, the event is fired from the dialog's body, thus the target
property will refer to its body element—i.e., #ui-dialog-body
.
注意:虽然没有自定义属性,但事件是从对话框的主体触发的,因此 target
属性将指向其主体元素——即 #ui-dialog-body
。
/* Execute the handler function when the event triggers. */
$(document).on(':dialogclosed', function (ev) {
/* JavaScript code */
});
/* Execute the handler function exactly once. */
$(document).one(':dialogclosed', function (ev) {
/* JavaScript code */
});
:dialogclosing
event :dialogclosing
事件 Global event triggered as the first step in closing the dialog when Dialog.close()
is called.
作为调用 Dialog.close()
时关闭对话框的第一步触发的全局事件。
v2.29.0
: Introduced. v2.29.0
: 引入。Note:
While there are no custom properties, the event is fired from the dialog's body, thus the target
property will refer to its body element—i.e., #ui-dialog-body
.
注意:虽然没有自定义属性,但事件是从对话框的主体触发的,因此 target
属性将指向其主体元素——即 #ui-dialog-body
。
/* Execute the handler function when the event triggers. */
$(document).on(':dialogclosing', function (ev) {
/* JavaScript code */
});
/* Execute the handler function exactly once. */
$(document).one(':dialogclosing', function (ev) {
/* JavaScript code */
});
:dialogopened
event :dialogopened
事件 Global event triggered as the last step in opening the dialog when Dialog.open()
is called.
作为调用 Dialog.open()
时打开对话框的最后一步触发的全局事件。
v2.29.0
: Introduced. v2.29.0
: 引入。Note:
While there are no custom properties, the event is fired from the dialog's body, thus the target
property will refer to its body element—i.e., #ui-dialog-body
.
注意:虽然没有自定义属性,但事件是从对话框的主体触发的,因此 target
属性将指向其主体元素——即 #ui-dialog-body
。
/* Execute the handler function when the event triggers. */
$(document).on(':dialogopened', function (ev) {
/* JavaScript code */
});
/* Execute the handler function exactly once. */
$(document).one(':dialogopened', function (ev) {
/* JavaScript code */
});
:dialogopening
event :dialogopening
事件 Global event triggered as the first step in opening the dialog when Dialog.open()
is called.
作为调用 Dialog.open()
时打开对话框的第一步触发的全局事件。
v2.29.0
: Introduced. v2.29.0
: 引入。Note:
While there are no custom properties, the event is fired from the dialog's body, thus the target
property will refer to its body element—i.e., #ui-dialog-body
.
注意:虽然没有自定义属性,但事件是从对话框的主体触发的,因此 target
属性将指向其主体元素——即 #ui-dialog-body
。
/* Execute the handler function when the event triggers. */
$(document).on(':dialogopening', function (ev) {
/* JavaScript code */
});
/* Execute the handler function exactly once. */
$(document).one(':dialogopening', function (ev) {
/* JavaScript code */
});
Navigation events allow the execution of JavaScript code at specific points during passage navigation.
导航事件允许在过程导航的特定点执行 JavaScript 代码。
In order of processing: (for reference, this also shows tasks and various special passages)
处理顺序:(仅供参考,此部分也显示了任务和各种特殊段落)
:passageinit
event. :passageinit
事件。PassageReady
special passage. PassageReady
特殊过程。:passagestart
event. :passagestart
事件。PassageHeader
special passage. PassageHeader
特殊段落。PassageFooter
special passage. PassageFooter
特殊段落。:passagerender
event. :passagerender
事件。PassageDone
special passage. PassageDone
特殊段落。:passagedisplay
event. :passagedisplay
事件。StoryBanner
special passage. StoryBanner
特殊段落。StoryDisplayTitle
special passage. StoryDisplayTitle
特殊段落。StorySubtitle
special passage. StorySubtitle
特殊段落。StoryAuthor
special passage. StoryAuthor
特殊段落。StoryCaption
special passage. StoryCaption
特殊段落。StoryMenu
special passage. StoryMenu
特殊段落。:passageend
event. :passageend
事件。:passageinit
event :passageinit
事件 Triggered before the modification of the state history.
在修改状态历史之前触发。
v2.20.0
: Introduced. v2.20.0
: 引入。v2.37.0
: Moved custom properties into the event's detail
object.v2.37.0
: 将自定义属性移动到事件的 detail
对象中。detail
object properties:detail
对象属性::passageinit
events have a detail
property whose value is an object with the following properties:
:passageinit
事件具有一个 detail
属性,其值是一个具有以下属性的对象:
passage
: (Passage
object) The incoming passage object. See the Passage
API for more information.passage
: ( Passage
对象) 进入的段落对象。请参阅 Passage
API 获取更多信息。/* Execute the handler function each time the event triggers. */
$(document).on(':passageinit', function (ev) {
/* Log details about the current moment. */
console.group('Details about the current moment');
console.log('passage name:', ev.detail.passage.name);
console.log('passage tags:', ev.detail.passage.tags);
console.groupEnd();
/* Do something useful here. */
});
/* Execute the handler function exactly once. */
$(document).one(':passageinit', function (ev) {
/* Do something useful here. */
});
:passagestart
event :passagestart
事件 Triggered before the rendering of the incoming passage.
在渲染进入的段落之前触发。
v2.20.0
: Introduced. v2.20.0
: 引入。v2.37.0
: Moved custom properties into the event's detail
object.detail
对象中。detail
object properties:detail
对象属性::passagestart
events have a detail
property whose value is an object with the following properties:
:passagestart
事件具有一个 detail
属性,其值是一个包含以下属性的对象:
content
: (HTMLElement
object) The, currently, empty element that will eventually hold the rendered content of the incoming passage.content
: ( HTMLElement
对象) 目前为空的元素,最终将包含传入段落的渲染内容。passage
: (Passage
object) The incoming passage object. See the Passage
API for more information.passage
: ( Passage
对象) 进入的段落对象。请参阅 Passage
API 获取更多信息。/* Execute the handler function each time the event triggers. */
$(document).on(':passagestart', function (ev) {
/* Log details about the current moment. */
console.group('Details about the current moment');
console.log('buffer:', ev.detail.content);
console.log('passage name:', ev.detail.passage.name);
console.log('passage tags:', ev.detail.passage.tags);
console.groupEnd();
/* Do something useful here. */
});
/* Execute the handler function exactly once. */
$(document).one(':passagestart', function (ev) {
/* Do something useful here. */
});
/*
Process the given markup and append the result to the incoming
passage's element.
*/
$(document).on(':passagestart', function (ev) {
$(ev.detail.content).wiki("In the //beginning//.");
});
:passagerender
event :passagerender
事件 Triggered after the rendering of the incoming passage.
触发于渲染传入段落之后。
v2.20.0
: Introduced. v2.20.0
: 引入。v2.37.0
: Moved custom properties into the event's detail
object.detail
对象中。detail
object properties:detail
对象属性::passagerender
events have a detail
property whose value is an object with the following properties:
:passagerender
事件具有一个 detail
属性,其值是一个具有以下属性的对象:
content
: (HTMLElement
object) The element holding the fully rendered content of the incoming passage.content
: ( HTMLElement
对象) 包含传入段落完整渲染内容的元素。passage
: (Passage
object) The incoming passage object. See the Passage
API for more information.passage
: ( Passage
对象) 传入的段落对象。有关更多信息,请参阅 Passage
API。/* Execute the handler function each time the event triggers. */
$(document).on(':passagerender', function (ev) {
/* Log details about the current moment. */
console.group('Details about the current moment');
console.log('buffer:', ev.detail.content);
console.log('passage name:', ev.detail.passage.name);
console.log('passage tags:', ev.detail.passage.tags);
console.groupEnd();
/* Do something useful here. */
});
/* Execute the handler function exactly once. */
$(document).one(':passagerender', function (ev) {
/* Do something useful here. */
});
/*
Process the given markup and append the result to the incoming
passage's element.
*/
$(document).on(':passagerender', function (ev) {
$(ev.detail.content).wiki("At the //end// of some renderings.");
});
:passagedisplay
event :passagedisplay
事件 Triggered after the display—i.e., output—of the incoming passage.
触发在显示传入段落之后,即输出之后。
v2.20.0
: Introduced. v2.20.0
: 引入。v2.31.0
: Added content
property to event object.content
属性。v2.37.0
: Moved custom properties into the event's detail
object.detail
对象中。detail
object properties:detail
对象属性::passagedisplay
events have a detail
property whose value is an object with the following properties:
:passagedisplay
事件具有一个 detail
属性,其值是一个包含以下属性的对象:
content
: (HTMLElement
object) The element holding the fully rendered content of the incoming passage.content
: ( HTMLElement
对象) 包含传入段落完整渲染内容的元素。passage
: (Passage
object) The incoming passage object. See the Passage
API for more information.passage
: ( Passage
对象) 进入的段落对象。请参阅 Passage
API 获取更多信息。/* Execute the handler function each time the event triggers. */
$(document).on(':passagedisplay', function (ev) {
/* Log details about the current moment. */
console.group('Details about the current moment');
console.log('buffer:', ev.detail.content);
console.log('passage name:', ev.detail.passage.name);
console.log('passage tags:', ev.detail.passage.tags);
console.groupEnd();
/* Do something useful here. */
});
/* Execute the handler function exactly once. */
$(document).one(':passagedisplay', function (ev) {
/* Do something useful here. */
});
/*
Process the given markup and append the result to the incoming
passage's element.
*/
$(document).on(':passagedisplay', function (ev) {
$(ev.detail.content).wiki("It's //showtime//!");
});
:passageend
event :passageend
事件 Triggered at the end of passage navigation.
触发于段落导航结束时。
v2.20.0
: Introduced. v2.20.0
: 引入。v2.31.0
: Added content
property to event object.content
属性。v2.37.0
: Moved custom properties into the event's detail
object.detail
对象中。detail
object properties:detail
对象属性::passageend
events have a detail
property whose value is an object with the following properties:
:passageend
事件具有一个 detail
属性,其值是一个包含以下属性的对象:
content
: (HTMLElement
object) The element holding the fully rendered content of the incoming passage.content
: ( HTMLElement
对象) 包含传入段落完整渲染内容的元素。passage
: (Passage
object) The incoming passage object. See the Passage
API for more information.passage
: ( Passage
对象) 进入的段落对象。请参阅 Passage
API 获取更多信息。/* Execute the handler function each time the event triggers. */
$(document).on(':passageend', function (ev) {
/* Log details about the current moment. */
console.group('Details about the current moment');
console.log('buffer:', ev.detail.content);
console.log('passage name:', ev.detail.passage.name);
console.log('passage tags:', ev.detail.passage.tags);
console.groupEnd();
/* Do something useful here. */
});
/* Execute the handler function exactly once. */
$(document).one(':passageend', function (ev) {
/* Do something useful here. */
});
/*
Process the given markup and append the result to the incoming
passage's element.
*/
$(document).on(':passageend', function (ev) {
$(ev.detail.content).wiki("So long and //thanks for all the fish//!");
});
prehistory
tasks prehistory
任务 Deprecated:
prehistory
tasks have been deprecated and should no longer be used. See the :passageinit
event for its replacement.
已弃用: prehistory
任务已被弃用,不应再使用。请参阅 :passageinit
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。predisplay
tasks predisplay
任务 Deprecated:
predisplay
tasks have been deprecated and should no longer be used. See the :passagestart
event for its replacement.
已弃用: predisplay
任务已被弃用,不应再使用。请参阅 :passagestart
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。prerender
tasks prerender
任务 Deprecated:
prerender
tasks have been deprecated and should no longer be used. See the :passagestart
event for its replacement.
已弃用: prerender
任务已被弃用,不应再使用。请参阅 :passagestart
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。postrender
tasks postrender
任务 Deprecated:
postrender
tasks have been deprecated and should no longer be used. See the :passagerender
event for its replacement.
已弃用: postrender
任务已被弃用,不应再使用。请参阅 :passagerender
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。postdisplay
tasks postdisplay
任务 Deprecated:
postdisplay
tasks have been deprecated and should no longer be used. See the :passagedisplay
event for its replacement.
已弃用: postdisplay
任务已被弃用,不应再使用。请参阅 :passagedisplay
事件了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.31.0
: Deprecated. v2.31.0
: 已废弃。SimpleAudio
Events 事件SimpleAudio
events allow the execution of JavaScript code at specific points during audio playback.
事件允许在音频播放的特定点执行 JavaScript 代码。
SimpleAudio
API see:
SimpleAudio
API 管理的音频轨道的事件监听器,请参阅:AudioTrack
API methods: <AudioTrack>.off()
, <AudioTrack>.on()
, <AudioTrack>.one()
.AudioTrack
API 方法: <AudioTrack>.off()
, <AudioTrack>.on()
, <AudioTrack>.one()
。AudioRunner
API methods: <AudioRunner>.off()
, <AudioRunner>.on()
, <AudioRunner>.one()
.AudioRunner
API 方法: <AudioRunner>.off()
, <AudioRunner>.on()
, <AudioRunner>.one()
。:faded
event :faded
事件 Track event triggered when a fade completes normally.
正常完成淡入时触发的事件跟踪。
v2.29.0
: Introduced. v2.29.0
: 引入。/* Execute the handler function when the event triggers for one track via <AudioTrack>. */
aTrack.on(':faded', function (ev) {
/* JavaScript code */
});
/* Execute the handler function when the event triggers for multiple tracks via <AudioRunner>. */
someTracks.on(':faded', function (ev) {
/* do something */
});
:fading
event :fading
事件 Track event triggered when a fade starts.
淡入开始时触发的事件跟踪。
v2.29.0
: Introduced. v2.29.0
: 引入。/* Execute the handler function when the event triggers for one track via <AudioTrack>. */
aTrack.on(':fading', function (ev) {
/* JavaScript code */
});
/* Execute the handler function when the event triggers for multiple tracks via <AudioRunner>. */
someTracks.on(':fading', function (ev) {
/* do something */
});
:stopped
event :stopped
事件 Track event triggered when playback is stopped after <AudioTrack>.stop()
or <AudioRunner>.stop()
is called—either manually or as part of another process.
播放停止后触发的事件,当调用 <AudioTrack>.stop()
或 <AudioRunner>.stop()
时——无论是手动还是作为其他过程的一部分。
See Also:
ended
and pause
for information on somewhat similar native events.
参见: ended
和 pause
了解类似原生事件的详细信息。
v2.29.0
: Introduced. v2.29.0
: 引入。/* Execute the handler function when the event triggers for one track via <AudioTrack>. */
aTrack.on(':stopped', function (ev) {
/* JavaScript code */
});
/* Execute the handler function when the event triggers for multiple tracks via <AudioRunner>. */
someTracks.on(':stopped', function (ev) {
/* do something */
});
System events allow the execution of JavaScript code at specific points during story startup and teardown.
系统事件允许在故事启动和关闭期间在特定点执行 JavaScript 代码。
:enginerestart
event :enginerestart
事件 Global event triggered once just before the page is reloaded when Engine.restart()
is called.
当调用 Engine.restart()
时,全局事件在页面重新加载之前触发一次。
v2.23.0
: Introduced. v2.23.0
: 引入。/* Execute the handler function when the event triggers. */
$(document).one(':enginerestart', function (ev) {
/* JavaScript code */
});
:storyready
event :storyready
事件Global event triggered once just before the dismissal of the loading screen at startup.
启动时在加载屏幕消失之前触发的全局事件。
v2.31.0
: Introduced. v2.31.0
: 引入。/* Execute the handler function exactly once, since it's only fired once. */
$(document).one(':storyready', function (ev) {
/* JavaScript code */
});
:uiupdate
event :uiupdate
事件Global event triggered when the built-in user interface is being updated.
当内置用户界面正在更新时触发的全局事件。
v2.37.0
: Introduced. v2.37.0
: 引入。/* Execute the handler function when the event triggers. */
$(document).on(':uiupdate', function (ev) {
/* JavaScript code */
});
<<type>>
Events 事件<<type>>
macro events allow the execution of JavaScript code at specific points during typing.
<<type>>
宏事件允许在输入过程中特定点执行 JavaScript 代码。
:typingcomplete
event :typingcomplete
事件Global event triggered when all <<type>>
macros within a passage have completed.
当段落中所有 <<type>>
宏完成时触发的全局事件。
Note:
Injecting additional <<type>>
macro invocations after a :typingcomplete
event has been fired will cause another event to eventually be generated, since you're creating a new sequence of typing.
注意:在触发 :typingcomplete
事件之后注入额外的 <<type>>
宏调用将最终导致另一个事件被生成,因为您正在创建一个新的输入序列。
v2.32.0
: Introduced. v2.32.0
: 引入。/* Execute the handler function when the event triggers. */
$(document).on(':typingcomplete', function (ev) {
/* JavaScript code */
});
:typingstart
event :typingstart
事件Local event triggered on the typing wrapper when the typing of a section starts.
本地事件在开始输入一个章节时在输入包装器上触发。
v2.32.0
: Introduced v2.32.0
: 引入v2.33.0
: Changed to a local event that bubbles up the DOM tree.v2.33.0
: 改为本地事件,该事件在 DOM 树中冒泡。/* Execute the handler function when the event triggers. */
$(document).on(':typingstart', function (ev) {
/* JavaScript code */
});
:typingstop
event :typingstop
事件Local event triggered on the typing wrapper when the typing of a section stops.
本地事件在输入包装器上的某个部分停止输入时触发。
v2.32.0
: Introduced v2.32.0
: 引入v2.33.0
: Changed to a local event that bubbles up the DOM tree.v2.33.0
: 更改为冒泡到 DOM 树中的本地事件。/* Execute the handler function when the event triggers. */
$(document).on(':typingstop', function (ev) {
/* JavaScript code */
});
Config
API The Config
object controls various aspects of SugarCube's behavior.
Config
对象控制 SugarCube 的各种行为。
Note:
Config
object settings should be placed within your project's JavaScript section (Twine 2: the Story JavaScript; Twine 1/Twee: a script
-tagged passage).
注意: Config
对象设置应放置在您的项目 JavaScript 部分(Twine 2:故事 JavaScript;Twine 1/Twee:一个带有 script
标签的段落)。
Config.addVisitedLinkClass
↔ boolean (default: false
) Config.addVisitedLinkClass
双向布尔值(默认: false
)Determines whether the link-visited
class is added to internal passage links that go to previously visited passages—i.e., the passage already exists within the story history.
判断是否将 link-visited
类添加到指向已访问段落的内部链接中——即该段落已存在于故事历史中。
Note:
You must provide your own styling for the link-visited
class as none is provided by default.
注意:您必须提供自己的 link-visited
样式,默认不提供。
v2.0.0
: Introduced. v2.0.0
: 引入。Config.addVisitedLinkClass = true;
You will also need to specify a .link-visited
style that defines the properties visited links should have. For example:
您还需要指定一个 .link-visited
样式,以定义已访问链接应具有的属性。例如:
.link-visited {
color: purple;
}
Config.cleanupWikifierOutput
↔ boolean (default: false
) Config.cleanupWikifierOutput
↔ 布尔值(默认: false
)Determines whether the output of the Wikifier is post-processed into more sane markup—i.e., where appropriate, it tries to transition the plethora of <br>
elements into <p>
elements.
确定 Wikifier 的输出是否经过后处理,使其成为更合理的标记——即,在适当的地方,尝试将大量的 <br>
元素转换为 <p>
元素。
v2.0.0
: Introduced. v2.0.0
: 引入。Config.cleanupWikifierOutput = true;
Config.debug
↔ boolean (default: false
) Config.debug
↔ 布尔值(默认: false
)Indicates whether SugarCube is running in test mode, which enables debug views and various optional debugging errors and warnings. See the Test Mode guide for more information.
表示 SugarCube 是否以测试模式运行,这会启用调试视图以及各种可选的调试错误和警告。有关更多信息,请参阅测试模式指南。
Note:
This setting is automatically set based on whether you're using a testing mode in a Twine compiler—i.e., Test mode in Twine 2, Test Play From Here in Twine 1, or the test mode option (-t
, --test
) in Tweego. You may, however, forcibly enable it if you need to for some reason—e.g., if you're using another compiler, which doesn't offer a way to enable test mode.
注意:此设置会根据您是否在 Twine 编译器中使用测试模式自动设置——即 Twine 2 中的测试模式,Twine 1 中的“从此处测试播放”,或 Tweego 中的测试模式选项( -t
, --test
)。但是,如果您有需要,可以强制启用它——例如,如果您使用的是不提供启用测试模式方式的编译器。
See Also:
Config.enableOptionalDebugging
setting.
参见: Config.enableOptionalDebugging
设置。
v2.2.0
: Introduced. v2.2.0
: 引入。// Forcibly enable test mode
Config.debug = true;
if (Config.debug) {
/* do something debug related */
}
<<if Config.debug>>
/* do something debug related */
<</if>>
Config.enableOptionalDebugging
↔ boolean (default: false
) Config.enableOptionalDebugging
↔ 布尔值(默认: false
)Determines whether various optional debugging errors and warnings are enabled outside of test mode.
确定是否在测试模式之外启用了各种可选的调试错误和警告
See Also:
Config.debug
setting.
参见: Config.debug
设置。
List of optional errors and warnings: (not exhaustive)
可选错误和警告列表:(非详尽)
<<if>>
macro assignment error. If enabled, returns an error when the =
assignment operator is used within its conditional—e.g., <<if $suspect = "Bob">>
. Does not flag other assignment operators.<<if>>
宏赋值错误。如果启用,当在条件中使用 =
赋值运算符时返回错误——例如 <<if $suspect = "Bob">>
。不会标记其他赋值运算符。v2.37.0
: Introduced. v2.37.0
: 引入。Config.enableOptionalDebugging = true;
Config.loadDelay
↔ integer (default: 0
) Config.loadDelay
整数(默认: 0
)Sets the integer delay (in milliseconds) before the loading screen is dismissed, once the document has signaled its readiness. Not generally necessary, however, some browsers render slower than others and may need a little extra time to get a media-heavy page done. This allows you to fine tune for those cases.
设置整数延迟(以毫秒为单位),在文档发出准备就绪信号后,加载屏幕被关闭。然而,通常情况下并不需要,但是一些浏览器的渲染速度比其他浏览器慢,可能需要额外的时间来完成媒体密集型页面。这允许您针对这些情况进行微调。
v2.0.0
: Introduced. v2.0.0
: 引入。// Delay the dismissal of the loading screen by 2000ms (2s)
Config.loadDelay = 2000;
Config.audio.pauseOnFadeToZero
↔ boolean (default: true
) Config.audio.pauseOnFadeToZero
↔ 布尔值(默认: true
)Determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
判断音频子系统是否自动暂停音量淡化为 0
(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。Config.audio.pauseOnFadeToZero = false;
Config.audio.preloadMetadata
↔ boolean (default: true
) Config.audio.preloadMetadata
↔ 布尔值(默认: true
)Determines whether the audio subsystem attempts to preload track metadata—meaning information about the track (e.g., duration), not its audio frames.
判断音频子系统是否尝试预加载曲目元数据——即关于曲目(例如,时长)的信息,而不是其音频帧。
Note:
It is unlikely that you will ever want to disable this setting.
注意:您不太可能想要禁用此设置。
v2.28.0
: Introduced. v2.28.0
: 引入。Config.audio.preloadMetadata = false;
Config.history.controls
↔ boolean (default: true
) Config.history.controls
双向布尔值(默认: true
)Determines whether the story's history controls (Backward, Jump To, & Forward buttons) are enabled within the UI bar.
确定故事的历史控制(后退、跳转到、前进按钮)是否在 UI 栏中启用。
v2.0.0
: Introduced. v2.0.0
: 引入。Config.history.controls = false;
Config.history.maxStates
↔ integer (default: 40
) Config.history.maxStates
整数(默认: 40
)Sets the maximum number of states (moments) to which the history is allowed to grow. Should the history exceed the limit, states will be dropped from the past (oldest first).
设置历史记录允许增长的最大状态(时刻)数。如果历史记录超过限制,则将删除过去的状态(最旧的先删除)。
Tip:
For game-oriented projects, as opposed to more story-oriented interactive fiction, a setting of 1
is strongly recommended.
TIP:对于以游戏为导向的项目,而不是更注重故事性的互动小说,强烈建议设置为 1
。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.36.0
: Reduced the default to 40
.v2.36.0
:将默认值降低到 40
。// Limit the history to a single state (recommended for games)
Config.history.maxStates = 1;
// Limit the history to 25 states
Config.history.maxStates = 25;
Config.macros.maxLoopIterations
↔ integer (default: 1000
) Config.macros.maxLoopIterations
整数(默认: 1000
)Sets the maximum number of iterations allowed before the <<for>>
macro conditional forms are terminated with an error.
设置在 <<for>>
宏条件表单因错误而终止之前允许的最大迭代次数。
Note:
This setting exists to prevent a misconfigured loop from making the browser unresponsive.
注意:此设置存在是为了防止配置错误的循环使浏览器无响应。
v2.0.0
: Introduced. v2.0.0
: 引入。// Allow only 5000 iterations
Config.macros.maxLoopIterations = 5000;
Config.macros.typeSkipKey
↔ string (default: " "
, space) Config.macros.typeSkipKey
字符串(默认: " "
,空格)Sets the default KeyboardEvent.key
value that causes the currently running <<type>>
macro instance to finish typing its content immediately.
设置默认的 KeyboardEvent.key
值,使当前运行的 <<type>>
宏实例立即完成内容输入。
v2.33.1
: Introduced. v2.33.1
: 引入。// Change the default skip key to Control (CTRL)
Config.macros.typeSkipKey = "Control";
Config.macros.typeVisitedPassages
↔ boolean (default: true
) Config.macros.typeVisitedPassages
双向布尔值(默认: true
)Determines whether the <<type>>
macro types out content on previously visited passages or simply outputs it immediately.
确定宏 <<type>>
是否在访问过的段落中输出内容,还是直接输出。
v2.32.0
: Introduced. v2.32.0
: 引入。// Do not type on previously visited passages
Config.macros.typeVisitedPassages = false;
Config.macros.ifAssignmentError
↔ boolean (default: true
)Config.macros.ifAssignmentError
↔ 布尔值(默认: true
) Deprecated:
This setting has been deprecated and should no longer be used. See the Config.enableOptionalDebugging
setting for its replacement.
已弃用:此设置已被弃用,不应再使用。有关替代方案,请参阅 Config.enableOptionalDebugging
设置。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Config.enableOptionalDebugging
setting.v2.37.0
:已被 Config.enableOptionalDebugging
设置取代。Config.navigation.override
↔ function (default: none) Config.navigation.override
↔ 函数(默认:无)Allows the destination of passage navigation to be overridden. The callback is passed one parameter, the original destination passage title. If its return value is falsy, the override is cancelled and navigation to the original destination continues unperturbed. If its return value is truthy, the override succeeds and that value is used as the new destination of the navigation.
允许覆盖段落导航的目标。回调函数传递一个参数,即原始目标段落的标题。如果其返回值是假的,则取消覆盖,并继续不受干扰地导航到原始目标。如果其返回值是真的,则覆盖成功,并且该值用作新的导航目标。
v2.13.0
: Introduced. v2.13.0
: 引入。Config.navigation.override = function (destinationPassage) {
/* code that returns a passage name or a falsy value */
};
// Force the player to the "You Died" passage if they let $health get too low.
Config.navigation.override = function (dest) {
var sv = State.variables;
// If $health is less-than-or-equal to 0, go to the "You Died" passage instead.
if (sv.health <= 0) {
return "You Died";
}
};
Config.passages.displayTitles
↔ boolean (default: false
) Config.passages.displayTitles
双向布尔值(默认: false
)Determines whether passage titles are combined with the story title, within the browser's/tab's titlebar, when passages are displayed.
确定在显示段落时,段落标题是否与故事标题结合,显示在浏览器的/标签的标题栏中。
v2.0.0
: Introduced. v2.0.0
: 引入。Config.passages.displayTitles = true;
Config.passages.nobr
↔ boolean (default: false
) Config.passages.nobr
双向布尔值(默认: false
)Determines whether rendering passages have their leading/trailing newlines removed and all remaining sequences of newlines replaced with single spaces before they're rendered. Equivalent to including the nobr
special tag on every passage.
确定渲染的段落在渲染前是否移除首尾换行符,并将所有剩余的换行符序列替换为单个空格。相当于在每一个段落中包含 nobr
特殊标签。
Note:
Does not affect script
or stylesheet
tagged passages, for Twine 1/Twee, or the Story JavaScript or Story Stylesheet sections, for Twine 2.
注意:不影响 script
或 stylesheet
标签的段落,对于 Twine 1/Twee,或者 Twine 2 的 Story JavaScript 或 Story Stylesheet 部分。
v2.19.0
: Introduced. v2.19.0
: 引入。Config.passages.nobr = true;
Config.passages.onProcess
↔ function (default: none) Config.passages.onProcess
↔ 函数(默认:无)Allows custom processing of passage text. The function is invoked each time the <Passage>.processText()
method is called. It is passed an abbreviated version of the associated passage's Passage
instance—containing only the tags
, text
, and title
properties. Its return value should be the post-processed text.
允许自定义处理段落文本。每次调用 <Passage>.processText()
方法时都会调用该函数。它接收关联段落 Passage
实例的简略版本——仅包含 tags
、 text
和 title
属性。其返回值应该是处理后的文本。
Note:
Does not affect script
or stylesheet
tagged passages, for Twine 1/Twee, or the Story JavaScript or Story Stylesheet sections, for Twine 2.
注意:不影响 script
或 stylesheet
标记的段落,对于 Twine 1/Twee,或 Twine 2 的故事 JavaScript 或故事样式表部分。
Note:
The function will be called just before the built-in no-break passage processing if you're also using that—see the Config.passages.nobr
setting and nobr
special tag.
注意:如果同时使用内置的不可断行段落处理,则函数将在该处理之前被调用——请参阅 Config.passages.nobr
设置和 nobr
特殊标记。
v2.30.0
: Introduced. v2.30.0
: 引入。// Change instancess of "cat" to "dog"
Config.passages.onProcess = function (p) {
return p.text.replace(/\bcat(s?)\b/g, "dog$1");
};
Config.passages.start
↔ string (Twine 2 default: user-selected; Twine 1/Twee default: "Start"
) Config.passages.start
↔ 字符串(Twine 2 默认:用户选择;Twine 1/Twee 默认: "Start"
)Sets the starting passage, the very first passage that will be displayed.
设置起始篇章,即第一个将被显示的篇章。
v2.0.0
: Introduced. v2.0.0
: 引入。Config.passages.start = "That Other Starting Passage";
Config.passages.transitionOut
↔ string | integer (default: none) Config.passages.transitionOut
字符串 | 整数(默认:无)Determines whether outgoing passage transitions are enabled. Valid values are the name of the property being animated, which causes the outgoing passage element to be removed once that transition animation is complete, or an integer delay (in milliseconds), which causes the outgoing passage element to be removed once the delay has expired. You will also need some CSS styles to make this work—examples given below.
确定是否启用输出篇章的过渡。有效值是正在动画化的属性的名称,这将在过渡动画完成后移除输出篇章元素,或者是一个整数延迟(以毫秒为单位),这将在延迟过期后移除输出篇章元素。您还需要一些 CSS 样式来实现这一点——以下给出示例。
Note:
If using an integer delay, ideally, it should probably be slightly longer than the outgoing transition delay that you intend to use—e.g., an additional 10ms or so should be sufficient.
注意:如果使用整数延迟,理想情况下,它可能应该比您打算使用的输出过渡延迟稍长一些——例如,额外 10 毫秒左右应该足够了。
v2.0.0
: Introduced. v2.0.0
: 引入。// Remove outgoing elements when their opacity animation ends
Config.passages.transitionOut = "opacity";
// Remove outgoing elements after 1010ms (1.01s)
Config.passages.transitionOut = 1010;
At the very least you will need to specify a .passage-out
style that defines the transition's end state. For example:
至少您需要指定一个 .passage-out
风格来定义过渡的结束状态。例如:
.passage-out {
opacity: 0;
}
That probably won't be very pleasing to the eye, however, so you will likely need several styles to make something that looks half-decent. For example, the following will give you a basic crossfade:
然而,这很可能不会很吸引人,因此您可能需要几个样式才能做出看起来还过得去的东西。例如,以下将为您提供基本的淡入淡出效果:
#passages {
position: relative;
}
.passage {
left: 0;
position: absolute;
top: 0;
transition: opacity 1s ease;
}
.passage-out {
opacity: 0;
}
Config.passages.descriptions
↔ boolean | object | function (default: none)Config.passages.descriptions
↔ 布尔值 | 对象 | 函数(默认:无) Deprecated:
This setting has been deprecated and should no longer be used. See the Config.saves.descriptions
setting for its replacement.
已弃用:此设置已被弃用,不应再使用。有关替代方案,请参阅 Config.saves.descriptions
设置。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Config.saves.descriptions
setting.v2.37.0
:已被 Config.saves.descriptions
设置取代。Config.saves.descriptions
↔ function (default: none) Config.saves.descriptions
↔ 函数(默认:无)Sets browser saves descriptions. If unset, a brief description of the current turn is used. If a callback function is assigned, it is passed one parameter, the type of save being attempted. If its return value is truthy, the returned description is used, elsewise the default description is used.
设置浏览器保存描述。如果未设置,则使用当前回合的简要描述。如果分配了回调函数,则传递一个参数,即尝试保存的类型。如果其返回值为真,则使用返回的描述,否则使用默认描述。
See:
Save.Type
pseudo-enumeration for more information on save types.
参考: Save.Type
了解更多保存类型的信息。
v2.37.0
: Introduced. v2.37.0
: 引入。Config.saves.descriptions = function (saveType) {
return passage();
};
var saveDescriptions = {
"passage_title_a" : "description text a…",
"passage_title_b" : "description text b…",
"passage_title_c" : "description text c…"
};
Config.saves.descriptions = function (saveType) {
return saveDescriptions[passage()];
};
Config.saves.descriptions = function (saveType) {
const base = `(${L10n.get("turn")} ${State.turns})`;
switch (saveType) {
case Save.Type.Auto:
return `${base} A browser auto save…`;
case Save.Type.Base64:
return `${base} A base64 save…`;
case Save.Type.Disk:
return `${base} A local disk save…`;
case Save.Type.Slot:
return `${base} A browser slot save…`;
}
};
Config.saves.id
↔ string (default: slugified story title) Config.saves.id
↔ 字符串(默认:故事标题的缩写)Sets the story ID associated with saves.
设置与存档关联的故事 ID。
v2.0.0
: Introduced. v2.0.0
: 引入。Config.saves.id = "a-big-huge-story-part-1";
Config.saves.isAllowed
↔ function (default: none) Config.saves.isAllowed
↔ 函数(默认:无)Determines whether saving is allowed within the current context. If unset, saves are always allowed. If a callback function is assigned, it is passed one parameter, the type of save being attempted. If its return value is truthy, the save is allowed, elsewise it is disallowed.
判断当前上下文中是否允许保存。如果未设置,则始终允许保存。如果分配了回调函数,则将尝试保存的类型作为参数传递给它。如果其返回值为真,则允许保存,否则不允许。
See:
Save.Type
pseudo-enumeration for more information on save types.
查看: Save.Type
了解更多关于保存类型的伪枚举信息。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Added save type parameter.Allows saves on passages if it returns a truthy value.
如果返回真值,则允许在段落中保存。
Config.saves.isAllowed = function (saveType) {
/* code returning a boolean value */
};
Disallow saving on passages tagged with menu
.
禁止保存带有 menu
.标签的段落。
Config.saves.isAllowed = function (saveType) {
return !tags().includes("menu");
};
Attempt a new auto save only on passages tagged with autosave
. Other save types are not limited.
仅在带有 autosave
.标签的段落上尝试新的自动保存。其他保存类型不受限制。
Config.saves.isAllowed = function (saveType) {
if (saveType === Save.Type.Auto) {
return tags().includes("autosave");
}
return true;
};
Attempt a new auto save only on every eighth turn and limit all other save types to passages tagged with cansave
.
尝试仅在每第八回合进行新的自动保存,并将所有其他保存类型限制为带有 cansave
标签的章节。
// Using an `if` statement
Config.saves.isAllowed = function (saveType) {
if (saveType === Save.Type.Auto) {
return turns() % 8 === 0;
}
return tags().includes("cansave");
};
Different logic for most save types.
不同类型的保存逻辑。
Note:
For example purposes only, not really recommended.
注意:仅用于示例,并不推荐。
Config.saves.isAllowed = function (saveType) {
switch (saveType) {
case Save.Type.Auto:
// Only every tenth turn
return turns() % 10 === 0;
case Save.Type.Disk:
case Save.Type.Slot:
// Only on passages tagged `cansave`
return tags().includes("cansave");
case Save.Type.Base64:
// Always
return true;
}
};
Config.saves.maxAutoSaves
integer (default: 0
) Config.saves.maxAutoSaves
整数(默认: 0
)Sets the maximum number of available auto saves. Using a value of 0
disables auto saves.
设置可用的最大自动保存次数。使用 0
的值将禁用自动保存。
Note:
When enabled, an auto save is attempted each turn by default. Thus, it is recommended that the Config.saves.isAllowed
setting be used to limit the frequency.
注意:默认情况下,启用后,每回合都会尝试自动保存。因此,建议使用 Config.saves.isAllowed
设置来限制频率。
Warning:
As available browser-based storage is very limited, it is strongly recommended that the number of available saves not be set too high. A range of 1
–10
is suggested.
警告:由于基于浏览器的存储空间非常有限,强烈建议不要将可用的保存数量设置得过高。建议的范围是 1
– 10
。
v2.37.0
: Introduced. v2.37.0
: 引入。Config.saves.maxAutoSaves = 3;
Config.saves.maxSlotSaves
integer (default: 8
) 8
)Sets the maximum number of available slot saves. Using a value of 0
disables slot saves.
设置可用的槽位保存的最大数量。使用 0
的值将禁用槽位保存。
Warning:
As available browser-based storage is very limited, it is strongly recommended that the number of available saves not be set too high. A range of 1
–10
is suggested.
警告:由于基于浏览器的存储非常有限,强烈建议不要将可用的保存数量设置得太高。建议的范围为 1
– 10
。
v2.37.0
: Introduced. v2.37.0
: 引入。Config.saves.maxSlotSaves = 4;
Config.saves.version
↔ any (default: none) Config.saves.version
↔ 任何(默认:无)Sets the version
property of saves.
设置保存的 version
属性。
Note:
This setting is only used to set the version
property of saves. Thus, it is only truly useful if you plan to upgrade out-of-date saves via the Save
Events API—specifically the Save.onLoad.add()
static method.
注意:此设置仅用于设置保存的 version
属性。因此,它只有在您计划通过 Save
事件 API 升级过时的保存时才真正有用——特别是通过 Save.onLoad.add()
静态方法。
v2.0.0
: Introduced. v2.0.0
: 引入。// As an integer (recommended)
Config.saves.version = 3;
// As a string (strongly not recommended)
Config.saves.version = "v3";
Config.saves.autoload
↔ boolean | string | function (default: none)Config.saves.autoload
↔ 布尔值 | 字符串 | 函数(默认:无) Deprecated:
This setting has been deprecated and should no longer be used. The default UI now includes a Continue button, which loads the latest save. If disabling or replacing the default UI, see the Save.browser.continue()
method to replicate the functionality.
已弃用:此设置已被弃用,不应再使用。默认 UI 现在包含继续按钮,该按钮加载最新存档。如果禁用或替换默认 UI,请参阅 Save.browser.continue()
方法以复制功能。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Config.saves.autosave
↔ boolean | Array<string> | function (default: none)Config.saves.autosave
↔ 布尔值 | 字符串数组 | 函数(默认:无) Deprecated:
This setting has been deprecated and should no longer be used. See the Config.saves.maxAutoSaves
setting to set the number of available auto saves and the Config.saves.isAllowed
setting to control when new auto saves are created.
已废弃:此设置已被弃用,不应再使用。请参阅 Config.saves.maxAutoSaves
设置以设置可用的自动保存数量,以及 Config.saves.isAllowed
设置以控制何时创建新的自动保存。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.30.0
: Added function values and deprecated string values.v2.30.0
: 添加了函数值,弃用了字符串值。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Config.saves.onLoad
↔ function (default: none)Config.saves.onLoad
↔ 函数(默认:无) Deprecated:
This setting has been deprecated and should no longer be used. See the Save.onLoad.add()
method for its replacement.
已弃用:此设置已被弃用,不应再使用。请参阅 Save.onLoad.add()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.36.0
: Deprecated in favor of the Save
Events API.v2.36.0
已弃用,推荐使用 Save
事件 API。Config.saves.onSave
↔ function (default: none)Config.saves.onSave
↔ 函数(默认:无) Deprecated:
This setting has been deprecated and should no longer be used. See the Save.onSave.add()
method for its replacement.
已弃用:此设置已被弃用,不应再使用。请参阅 Save.onSave.add()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.33.0
: Added save operation details object parameter to the callback function.v2.33.0
: 添加到回调函数的保存操作详情对象参数。v2.36.0
: Deprecated in favor of the Save
Events API.v2.36.0
已弃用,推荐使用 Save
事件 API。Config.saves.slots
integer (default: 8
)Config.saves.slots
整数(默认值: 8
) Deprecated:
This setting has been deprecated and should no longer be used. See the Config.saves.maxSlotSaves
setting for its replacement.
已弃用:此设置已被弃用,不应再使用。有关替代方案,请参阅 Config.saves.maxSlotSaves
设置。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Config.saves.maxSlotSaves
setting.v2.37.0
:已被 Config.saves.maxSlotSaves
设置取代。Config.saves.tryDiskOnMobile
↔ boolean (default: true
)Config.saves.tryDiskOnMobile
↔ 布尔值(默认: true
) Deprecated:
This setting has been deprecated and should no longer be used. Saving to disk on mobile devices is now unconditionally enabled.
已弃用:此设置已被弃用,不应再使用。在移动设备上保存到磁盘现在无条件启用。
v2.34.0
: Introduced. v2.34.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Config.ui.stowBarInitially
↔ boolean | integer (default: 800
) Config.ui.stowBarInitially
↔ 布尔值 | 整数(默认: 800
)Determines whether the UI bar (sidebar) starts in the stowed (shut) state initially. Valid values are boolean true
/false
, which causes the UI bar to always/never start in the stowed state, or an integer, which causes the UI bar to start in the stowed state if the viewport width is less-than-or-equal-to the specified number of pixels.
确定用户界面栏(侧边栏)最初是否处于收起(关闭)状态。有效值是布尔值 true
/ false
,这将导致用户界面栏始终/从不启动在收起状态,或整数,这将导致用户界面栏在视口宽度小于或等于指定像素数时启动在收起状态。
v2.11.0
: Introduced. v2.11.0
: 引入。// As a boolean; always start stowed
Config.ui.stowBarInitially = true;
// As a boolean; never start stowed
Config.ui.stowBarInitially = false;
// As an integer; start stowed if the viewport is 800px or less
Config.ui.stowBarInitially = 800;
Config.ui.updateStoryElements
↔ boolean (default: true
) Config.ui.updateStoryElements
双向布尔值(默认: true
)Determines whether certain elements within the UI bar are updated when passages are displayed. The affected elements are the story: banner, subtitle, author, caption, and menu.
确定在显示段落时 UI 栏中的某些元素是否更新。受影响的元素包括故事:横幅、副标题、作者、字幕和菜单。
Note:
The story title is not included in updates because SugarCube uses it as the basis for the key used to store and load data used when playing the story and for saves.
注意:故事标题不包括在更新中,因为 SugarCube 将其用作存储和加载故事播放时使用的数据以及保存所用的键的基础。
v2.0.0
: Introduced. v2.0.0
: 引入。// If you don't need those elements to update
Config.ui.updateStoryElements = false;
Dialog
API Dialog.append(content)
→ Dialog
object Dialog.append(content)
→ Dialog
对象 Appends the given content to the dialog's content area. Returns a reference to the Dialog
object for chaining.
将给定内容追加到对话框的内容区域。返回对 Dialog
对象的引用以进行链式调用。
Note:
If your content contains any SugarCube markup, you'll need to use the Dialog.wiki()
method instead.
注意:如果您的内容包含任何 SugarCube 标记,您需要使用 Dialog.wiki()
方法。
v2.9.0
: Introduced. v2.9.0
: 引入。content
: (Node | string) The content to append. As this method is essentially a shortcut for jQuery(Dialog.body()).append(…)
, see jQuery's append()
method for the range of valid content types.content
:(节点 | 字符串) 要追加的内容。由于此方法本质上是对 jQuery(Dialog.body()).append(…)
的快捷方式,请参阅 jQuery 的 append()
方法以获取有效内容类型的范围。Dialog.append("Cry 'Havoc!', and let slip the <em>ponies</em> of <strong>friendship</strong>.");
Dialog.append( /* DOM nodes */ );
Dialog.body()
→ HTMLElement
object Dialog.body()
→ HTMLElement
对象 Returns a reference to the dialog's content area.
返回对话框内容区域的引用。
v2.0.0
: Introduced. v2.0.0
: 引入。jQuery(Dialog.body())
.append("Cry 'Havoc!', and let slip the <em>ponies</em> of <strong>friendship</strong>.");
jQuery(Dialog.body())
.wiki("Cry 'Havoc!', and let slip the //ponies// of ''friendship''.");
Dialog.close()
→ Dialog
object Dialog.close()
→ Dialog
对象 Closes the dialog. Returns a reference to the Dialog
object for chaining.
关闭对话框。返回对 Dialog
对象的引用以进行链式调用。
v2.0.0
: Introduced. v2.0.0
: 引入。Dialog.close();
Dialog.create([title [, classNames]])
→ Dialog
object Dialog.create([title [, classNames]])
→ Dialog
对象 Prepares the dialog for use. Returns a reference to the Dialog
object for chaining.
准备对话框以供使用。返回对 Dialog
对象的引用以进行链式调用。
v2.37.0
: Introduced. v2.37.0
: 引入。title
: (optional, string) The title of the dialog.classNames
: (optional, string) The space-separated-list of classes to add to the dialog.Dialog.create();
Dialog.create("Character Sheet");
Dialog.create("Character Sheet", "charsheet");
Dialog
.create("Character Sheet", "charsheet")
.wikiPassage("Player Character")
.open();
Dialog.empty()
→ HTMLElement
object Dialog.empty()
→ HTMLElement
对象 Empties the dialog's content area. Returns a reference to the Dialog
object for chaining.
清空对话框的内容区域。返回对 Dialog
对象的引用以进行链式调用。
v2.37.0
: Introduced. v2.37.0
: 引入。Dialog.empty();
Dialog
.empty()
.wikiPassage("Quests");
Dialog.isOpen([classNames])
→ boolean Dialog.isOpen([classNames])
→ 布尔值 Returns whether the dialog is currently open.
返回对话框当前是否打开。
v2.0.0
: Introduced. v2.0.0
: 引入。classNames
: (optional, string) The space-separated-list of classes to check for when determining the state of the dialog. Each of the built-in dialogs contains a name-themed class that can be tested for in this manner—e.g., the Saves dialog contains the class saves
.classNames
:(可选,字符串)当确定对话框状态时,检查的空格分隔的类列表。每个内置对话框都包含一个以名称为主题的类,可以通过这种方式进行测试——例如,保存对话框包含类 saves
。if (Dialog.isOpen()) {
/* code to execute if the dialog is open… */
}
saves
class existssaves
类if (Dialog.isOpen("saves")) {
/* code to execute if the Saves dialog is open… */
}
Dialog.open([options [, closeFn]])
→ Dialog
object Dialog.open([options [, closeFn]])
→ Dialog
对象 Opens the dialog. Returns a reference to the Dialog
object for chaining.
打开对话框。返回 Dialog
对象的引用以进行链式调用。
Note:
Call this only after populating the dialog with content.
注意:仅在填充对话框内容后调用此方法。
v2.0.0
: Introduced. v2.0.0
: 引入。options
: (optional, null | object) The options to be used when opening the dialog.options
: (可选,null | 对象) 打开对话框时使用的选项。closeFn
: (optional, null | function) The function to execute whenever the dialog is closed.closeFn
: (可选,null | 函数) 每次对话框关闭时执行的函数。An options object should have some of the following properties:
选项对象应包含以下一些属性:
top
: Top y-coordinate of the dialog (default: 50
; in pixels, but without the unit).50
;以像素为单位,但无需单位)。Dialog.open();
Dialog.wiki(wikiMarkup)
→ Dialog
object Dialog.wiki(wikiMarkup)
→ Dialog
对象 Renders the given markup and appends it to the dialog's content area. Returns a reference to the Dialog
object for chaining.
渲染给定的标记并附加到对话框的内容区域。返回对 Dialog
对象的引用以进行链式调用。
Note:
If you simply want to render a passage, see the Dialog.wikiPassage()
method instead.
注意:如果您只想渲染一个段落,请参阅 Dialog.wikiPassage()
方法。
Warning:
If your content consists of DOM nodes, you'll need to use the Dialog.append()
method instead.
警告:如果您的内容包含 DOM 节点,您需要使用 Dialog.append()
方法。
v2.9.0
: Introduced. v2.9.0
: 引入。wikiMarkup
: (string) The markup to render.wikiMarkup
:(字符串) 要渲染的标记。Dialog.wiki("Cry 'Havoc!', and let slip the //ponies// of ''friendship''.");
Dialog.wikiPassage(name)
→ Dialog
object Dialog.wikiPassage(name)
→ Dialog
对象 Renders the passage by the given name and appends it to the dialog's content area. Returns a reference to the Dialog
object for chaining.
通过给定的名称渲染段落,并将其追加到对话框的内容区域。返回 Dialog
对象的引用以进行链式调用。
v2.37.0
: Introduced. v2.37.0
: 引入。name
: (string) The name of the passage to render.name
:(字符串) 要渲染的段落的名称。Dialog.wikiPassage("Inventory");
Dialog.setup([title [, classNames]])
→ HTMLElement
object Dialog.setup([title [, classNames]])
→ HTMLElement
对象 Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of Dialog.create()
.Dialog.create()
。Engine
API Engine.lastPlay
→ number Engine.lastPlay
→ 数字 Returns a timestamp representing the last time Engine.play()
was called.
返回表示上次调用 Engine.play()
的时间戳。
v2.0.0
: Introduced. v2.0.0
: 引入。Engine.lastPlay → The timestamp at which Engine.play() was last called
Engine.state
→ string Engine.state
→ 字符串 Returns the current state of the engine ("idle"
, "playing"
, "rendering"
).
返回引擎当前状态( "idle"
, "playing"
, "rendering"
)。
v2.7.0
: Introduced. v2.7.0
: 引入。"idle"
: The engine is idle, awaiting the triggering of passage navigation—the default state."idle"
: 引擎处于空闲状态,等待通过导航章节的触发——默认状态。"playing"
: Passage navigation has been triggered and a turn is being processed."rendering"
: The incoming passage is being rendered and added to the page—takes place during turn processing, so implies "playing"
."rendering"
: 正在渲染并添加到页面中的传入段落——发生在回合处理期间,因此暗示 "playing"
。Engine.state → Returns the current state of the engine
Engine.backward()
→ boolean Engine.backward()
→ 布尔值 Moves backward one moment within the full history (past + future), if possible, activating and showing the moment moved to. Returns whether the history navigation was successful (should only fail if already at the beginning of the full history).
如果可能,向后移动一个时刻在完整历史(过去+未来)中,激活并显示移动到的时刻。返回历史导航是否成功(只有在已处于完整历史的开始时才会失败)。
v2.0.0
: Introduced. v2.0.0
: 引入。Engine.backward() → Rewinds the full history by one moment—i.e., undoes the moment
Engine.forward()
→ boolean Engine.forward()
→ 布尔值 Moves forward one moment within the full history (past + future), if possible, activating and showing the moment moved to. Returns whether the history navigation was successful (should only fail if already at the end of the full history).
如果可能,向前移动一个瞬间,在完整历史(过去+未来)中,激活并显示移动到的瞬间。返回历史导航是否成功(只有在到达完整历史的末尾时才会失败)。
v2.0.0
: Introduced. v2.0.0
: 引入。Engine.forward() → Fast forwards the full history by one moment—i.e., redoes the moment
Engine.go(offset)
→ boolean Engine.go(offset)
→ 布尔值 Activates the moment at the given offset from the active (present) moment within the full state history and show it. Returns whether the history navigation was successful (should only fail if the offset from the active (present) moment is not within the bounds of the full history).
激活在完整状态历史中从当前(现在)瞬间给定偏移量的瞬间,并显示它。返回历史导航是否成功(只有在偏移量不在完整历史范围内时才会失败)。
v2.0.0
: Introduced. v2.0.0
: 引入。offset
: (integer) The offset from the active (present) moment of the moment to go to.offset
: (整数) 要前往的瞬间相对于当前(现在)瞬间的偏移量。Engine.go(2) → Fast forwards the full history by two moments—i.e., redoes the moments
Engine.go(-4) → Rewinds the full history by four moments—i.e., undoes the moments
Engine.goTo(index)
→ boolean Engine.goTo(index)
→ 布尔值 Activates the moment at the given index within the full state history and show it. Returns whether the history navigation was successful (should only fail if the index is not within the bounds of the full history).
在全状态历史中激活给定索引处的时刻并显示它。返回历史导航是否成功(只有在索引不在完整历史范围内时才会失败)。
v2.0.0
: Introduced. v2.0.0
: 引入。index
: (integer) The index of the moment to go to.index
: (整数) 要前往的时刻索引。Engine.goTo(0) → Goes to the first moment
Engine.goTo(9) → Goes to the tenth moment
Engine.isIdle()
→ boolean Engine.isIdle()
→ 布尔值 Returns whether the engine is idle.
返回引擎是否空闲。
v2.16.0
: Introduced. v2.16.0
: 引入。Engine.isIdle() → Returns whether the engine is idle
Engine.isPlaying()
→ boolean Engine.isPlaying()
→ 布尔值 Returns whether the engine is processing a turn—i.e., passage navigation has been triggered.
返回引擎是否正在处理回合——即触发了篇章导航。
v2.16.0
: Introduced. v2.16.0
: 引入。Engine.isPlaying() → Returns whether the engine is playing
Engine.isRendering()
→ boolean Engine.isRendering()
→ 布尔值 Returns whether the engine is rendering the incoming passage.
返回引擎是否正在渲染传入的段落。
v2.16.0
: Introduced. v2.16.0
: 引入。Engine.isRendering() → Returns whether the engine is rendering
Engine.play(passageTitle [, noHistory])
→ HTMLElement
object Engine.play(passageTitle [, noHistory])
→ HTMLElement
对象 Renders and displays the passage referenced by the given title, optionally without adding a new moment to the history.
渲染并显示由给定标题引用的段落,可选地不添加新的历史记录项。
v2.0.0
: Introduced. v2.0.0
: 引入。passageTitle
: (string) The title of the passage to play.passageTitle
: (字符串) 要播放的段落的标题。noHistory
: (optional, boolean) Disables the update of the history—i.e., no moment is added to the history.noHistory
: (可选,布尔值) 禁用历史记录的更新——即不添加历史记录项。Engine.play("Foo") → Renders, displays, and adds a moment for the passage "Foo" to the history
Engine.play("Foo", true) → Renders and displays the passage "Foo", but does not add new history
Engine.restart()
Causes the browser to immediately attempt to reload the window, thus restarting the story.
导致浏览器立即尝试重新加载窗口,从而重新启动故事。
Warning:
The player will not be prompted and all unsaved state will be lost.
警告:玩家将不会收到提示,所有未保存的状态都将丢失。
Note:
In general, you should not call this method directly. Instead, call the UI.restart()
static method, which prompts the player with an OK/Cancel dialog before itself calling Engine.restart()
, if they accept.
备注:通常情况下,您不应直接调用此方法。相反,应调用 UI.restart()
静态方法,在它自己调用 Engine.restart()
之前,如果玩家接受,将提示玩家 OK/Cancel 对话框。
v2.0.0
: Introduced. v2.0.0
: 引入。Engine.restart() → Restarts the story
Engine.show()
→ HTMLElement
object Engine.show()
→ HTMLElement
对象 Renders and displays the active (present) moment's associated passage without adding a new moment to the history.
渲染并显示当前(存在)时刻关联的段落,而不在历史记录中添加新的时刻。
v2.0.0
: Introduced. v2.0.0
: 引入。Engine.show() → Renders and displays the present passage without adding new history
Fullscreen
API Provides access to browsers' fullscreen functionality.
提供访问浏览器全屏功能。
If you wish to use custom backgrounds, either simply colors or with images, then you should place them on the body
element. For example:
如果您想使用自定义背景,无论是纯色还是图片,请将它们放置在 body
元素上。例如:
body {
background: #111 fixed url("images/background.png") center / contain no-repeat;
}
Warning:
It is strongly recommended that you do not place background properties on the html
element in addition to the body
element as this can cause background jitter in Internet Explorer when scrolling outside of fullscreen mode.
警告:强烈建议您不要在 html
元素和 body
元素上同时放置背景属性,因为这可能导致在退出全屏模式时滚动时在 Internet Explorer 中产生背景抖动。
Warning:
If setting a background image via the background
shorthand property, then you should also specify a background-color
value with it or include a separate background-color
property after the background
property. The reason being is that the background
property resets the background color, so if you do not set one either as one of its values or via a following background-color
property, then the browser's default background color could show through if the background image does not cover the entire viewport or includes transparency.
警告:如果通过 background
简写属性设置背景图片,那么您也应该指定一个 background-color
值与之一起,或者在该 background
属性之后包含一个单独的 background-color
属性。原因是 background
属性会重置背景颜色,所以如果您不设置一个值作为其值之一或通过后续的 background-color
属性,那么如果背景图片没有覆盖整个视口或包含透明度,浏览器默认的背景颜色可能会显示出来。
The Fullscreen
API comes with some built-in limitations:
Fullscreen
API 带有一些内置的限制:
Fullscreen.element
→ HTMLElement
object | nullFullscreen.element
→ HTMLElement
对象 | null Returns the current fullscreen element or, if fullscreen mode is not active, null
.
返回当前全屏元素,如果全屏模式未激活,则为 null
。
v2.31.0
: Introduced. v2.31.0
: 引入。Fullscreen.element → The current fullscreen element
Fullscreen.isEnabled()
→ boolean Fullscreen.isEnabled()
→ 布尔值 Returns whether fullscreen is both supported and enabled.
返回全屏是否被支持且已启用。
v2.31.0
: Introduced. v2.31.0
: 引入。Fullscreen.isEnabled() → Whether fullscreen mode is available
Fullscreen.isFullscreen()
→ boolean Fullscreen.isFullscreen()
→ 布尔值 Returns whether fullscreen mode is currently active.
返回全屏模式是否当前处于激活状态。
v2.31.0
: Introduced. v2.31.0
: 引入。Fullscreen.isFullscreen() → Whether fullscreen mode is active
Fullscreen.request([options [, requestedEl]])
→ Promise
object Fullscreen.request([options [, requestedEl]])
→ Promise
对象 Request that the browser enter fullscreen mode.
请求浏览器进入全屏模式。
See:
Backgrounds and limitations.
参考:背景和限制。
v2.31.0
: Introduced. v2.31.0
: 引入。options
: (optional, object) The fullscreen options object.options
:(可选,对象)全屏选项对象。requestedEl
: (optional, HTMLElement
object) The element to enter fullscreen mode with. If omitted, defaults to the entire page.requestedEl
:(可选, HTMLElement
对象)要进入全屏模式的元素。如果省略,则默认为整个页面。A fullscreen options object should have some of the following properties:
全屏选项对象应包含以下一些属性:
navigationUI
: (string) Determines the fullscreen navigation UI preference. Valid values are (default: "auto"
):
navigationUI
: (字符串) 用于确定全屏导航 UI 的首选项。有效值有(默认为 "auto"
):"auto"
: Indicates no preference."auto"
:表示无偏好。"hide"
: Request that the browser's navigation UI be hidden. The full dimensions of the screen will be used to display the element."show"
: Request that the browser's navigation UI be shown. The screen dimensions allocated to the element will be clamped to leave room for the UI.Note:
Browsers are not currently required to honor the navigationUI
setting.
注意:浏览器目前不需要遵守 navigationUI
设置。
/* Request to enter fullscreen mode. */
Fullscreen.request();
/* Request to enter fullscreen mode while showing its navigation UI and with the given element. */
Fullscreen.request({ navigationUI : "show" }, myElement);
Fullscreen.exit()
→ Promise
object Fullscreen.exit()
→ Promise
对象 Request that the browser exit fullscreen mode.
请求浏览器退出全屏模式。
v2.31.0
: Introduced. v2.31.0
: 引入。/* Request to exit fullscreen mode. */
Fullscreen.exit();
Fullscreen.toggle([options [, requestedEl]])
→ Promise
object Fullscreen.toggle([options [, requestedEl]])
→ Promise
对象 Request that the browser toggle fullscreen mode—i.e., enter or exit as appropriate.
请求浏览器切换全屏模式——即根据需要进入或退出。
v2.31.0
: Introduced. v2.31.0
: 引入。options
: (optional, object) The fullscreen options object. See Fullscreen.request()
for more information.options
:(可选,对象)全屏选项对象。更多信息请参阅 Fullscreen.request()
。requestedEl
: (optional, HTMLElement
object) The element to toggle fullscreen mode with. If omitted, defaults to the entire page.requestedEl
:(可选, HTMLElement
对象)用于切换全屏模式的元素。如果省略,则默认为整个页面。/* Request to toggle fullscreen mode. */
Fullscreen.toggle();
/* Request to toggle fullscreen mode while showing its navigation UI and with the given element. */
Fullscreen.toggle({ navigationUI : "show" }, myElement);
Fullscreen.onChange(handlerFn [, requestedEl])
Attaches fullscreen change event handlers.
附加全屏更改事件处理器。
v2.31.0
: Introduced. v2.31.0
: 引入。handlerFn
: (function) The function to invoke when fullscreen mode is changed.requestedEl
: (optional, HTMLElement
object) The element to attach the handler to.requestedEl
:(可选, HTMLElement
对象)要附加处理器的元素。/* Attach a hander to listen for fullscreen change events. */
Fullscreen.onChange(function (ev) {
/* Fullscreen mode changed, so do something. */
});
/* Attach a hander to the given element to listen for fullscreen change events. */
Fullscreen.onChange(function (ev) {
/* Fullscreen mode changed on myElement, so do something. */
}, myElement);
Fullscreen.offChange([handlerFn [, requestedEl]])
Removes fullscreen change event handlers.
移除全屏更改事件处理器。
v2.31.0
: Introduced. v2.31.0
: 引入。handlerFn
: (optional, function) The function to remove. If omitted, will remove all handler functions.requestedEl
: (optional, HTMLElement
object) The element to remove the handler(s) from.HTMLElement
对象)从该元素移除处理器。/* Remove all fullscreen change event handers. */
Fullscreen.offChange();
/* Remove the given fullscreen change event hander. */
/* NOTE: Requires that the original handler function was saved. */
Fullscreen.offChange(originalHandlerFn);
/* Remove all fullscreen change event handers from myElement. */
Fullscreen.offChange(null, myElement);
/* Remove the given fullscreen change event hander from myElement. */
/* NOTE: Requires that the original handler function was saved. */
Fullscreen.offChange(originalHandlerFn, myElement);
Fullscreen.onError(handlerFn [, requestedEl])
Attaches fullscreen error event handlers.
添加全屏错误事件处理器。
v2.31.0
: Introduced. v2.31.0
: 引入。handlerFn
: (function) The function to invoke when fullscreen mode encounters an error.handlerFn
: (function) 全屏模式遇到错误时要调用的函数。requestedEl
: (optional, HTMLElement
object) The element to attach the handler to.requestedEl
:(可选, HTMLElement
对象)要附加处理器的元素。/* Attach a hander to listen for fullscreen error events. */
Fullscreen.onError(function (ev) {
/* Fullscreen mode changed, so do something. */
});
/* Attach a hander to the given element to listen for fullscreen error events. */
Fullscreen.onError(function (ev) {
/* Fullscreen mode changed on myElement, so do something. */
}, myElement);
Fullscreen.offError([handlerFn [, requestedEl]])
Removes fullscreen error event handlers.
移除全屏错误事件处理器。
v2.31.0
: Introduced. v2.31.0
: 引入。handlerFn
: (optional, function) The function to remove. If omitted, will remove all handler functions.requestedEl
: (optional, HTMLElement
object) The element to remove the handler(s) from.HTMLElement
对象)从该元素移除处理器。/* Remove all fullscreen error event handers. */
Fullscreen.offError();
/* Remove the given fullscreen error event hander. */
/* NOTE: Requires that the original handler function was saved. */
Fullscreen.offError(originalHandlerFn);
/* Remove all fullscreen error event handers from myElement. */
Fullscreen.offError(null, myElement);
/* Remove the given fullscreen error event hander from myElement. */
/* NOTE: Requires that the original handler function was saved. */
Fullscreen.offError(originalHandlerFn, myElement);
LoadScreen
API Note:
To simply add a delay to the dismissal of the loading screen to hide initial flashes of unstyled content (FOUC)—e.g., style changes and page reflows—you do not need to use this API. See the Config.loadDelay
configuration setting.
注意:为了简单地在加载屏幕消失时添加延迟,以隐藏未样式化内容的初始闪烁(FOUC)——例如样式更改和页面重排——您不需要使用此 API。请参阅 Config.loadDelay
配置设置。
LoadScreen.lock()
→ number LoadScreen.lock()
→ 数字 Acquire a loading screen lock and, if necessary, display the loading screen.
获取加载屏幕锁,并在必要时显示加载屏幕。
v2.15.0
: Introduced. v2.15.0
: 引入。The (integer) lock ID. (整数)锁 ID。
See the LoadScreen.unlock()
static method for additional examples.
请参阅 LoadScreen.unlock()
静态方法以获取更多示例。
// Lock the loading screen and get the lock ID.
var lockId = LoadScreen.lock();
LoadScreen.unlock(lockId)
Release the loading screen lock with the given ID and, if no other locks exist, hide the loading screen.
使用给定的 ID 释放加载屏幕锁,如果没有其他锁存在,则隐藏加载屏幕。
v2.15.0
: Introduced. v2.15.0
: 引入。lockId
: (integer) The loading screen lock ID.// Lock the loading screen and get the lock ID.
var lockId = LoadScreen.lock();
// Do something whose timing is unpredictable that should be hidden by the loading screen.
// Release the given lock ID.
LoadScreen.unlock(lockId);
Macro
API See Also:
MacroContext
API.
参见: MacroContext
API。
Macro.add(name , definition)
Add new macro(s). 添加新宏。
v2.0.0
: Introduced v2.0.0
: 引入v2.33.0
: Obsoleted the deep
parameter.v2.33.0
: 已废弃 deep
参数。name
: (string | Array<string>) Name, or array of names, of the macro(s) to add. NOTE: Names must consist of characters from the basic Latin alphabet and start with a letter, which may be optionally followed by any number of letters, numbers, the underscore, or the hyphen.name
: 要添加的宏(string | Array)名称,或宏名称的数组。注意:名称必须由基本拉丁字母组成,并且以字母开头,后面可以跟任意数量的字母、数字、下划线或连字符。definition
: (object | string) Definition of the macro(s) or the name of an existing macro whose definition to copy.definition
: 宏(object | string)的定义或要复制定义的现有宏的名称。A macro definition object should have some of the following properties (only handler
is absolutely required):
宏定义对象应具有以下一些属性(其中 handler
是绝对必须的):
skipArgs
: (optional, boolean | Array<string>) Disables parsing argument strings into discrete arguments. Used by macros that only use the raw/full argument strings. Boolean true
to affect all tags or an array of tag names to affect.skipArgs
: (可选,布尔值 | 字符串数组)禁用将参数字符串解析为离散参数。供仅使用原始/完整参数字符串的宏使用。布尔值 true
影响所有标签或一个标签名称数组以影响。tags
: (optional, null | Array<string>) Signifies that the macro is a container macro—i.e., not self-closing. An array child tag names or null
, if there are no child tags.tags
: (可选,null | 字符串数组)表示该宏是一个容器宏——即不是自闭合的。一个子标签名称数组或 null
,如果没有子标签。handler
: (function) The macro's main function. It will be called without arguments, but with its this
set to a macro context object.this
将被设置为宏上下文对象。Additional properties may be added for internal use.
可以为内部使用添加额外的属性。
/*
Example of a very simple/naive <<if>>/<<elseif>>/<<else>> macro implementation.
*/
Macro.add('if', {
skipArgs : true,
tags : ['elseif', 'else'],
handler : function () {
try {
for (var i = 0, len = this.payload.length; i < len; ++i) {
if (
this.payload[i].name === 'else' ||
!!Scripting.evalJavaScript(this.payload[i].args.full)
) {
jQuery(this.output).wiki(this.payload[i].contents);
break;
}
}
}
catch (ex) {
return this.error('bad conditional expression: ' + ex.message);
}
}
});
Macro.delete(name)
Remove existing macro(s).
删除现有的宏。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string | Array<string>) Name, or array of names, of the macro(s) to remove.name
: 要移除的宏(字符串 | Array)名称,或名称数组。Macro.delete("amacro")
Macro.delete(["amacro", "bmacro"])
Macro.get(name)
→ object Macro.get(name)
→ 对象 Return the named macro definition, or null
on failure.
返回命名的宏定义,或在失败时返回 null
。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string) Name of the macro whose definition should be returned.name
: (字符串) 应返回其定义的宏的名称。Macro.get("print")
Macro.has(name)
→ boolean Macro.has(name)
→ 布尔值 Returns whether the named macro exists.
返回是否存在指定的宏。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string) Name of the macro to search for.name
: (字符串) 要搜索的宏的名称。Macro.has("print")
Macro.tags.get(name)
→ Array<string> Macro.tags.get(name)
→ 数组 Return the named macro tag's parents array (includes the names of all macros who have registered the tag as a child), or null
on failure.
返回指定宏标签的父级数组(包括所有已将标签注册为子级的宏的名称),或失败时返回 null
。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string) Name of the macro tag whose parents array should be returned.name
: (字符串) 应返回其父数组宏标签的名称。Macro.tags.get("else") → For the standard library, returns: ["if"]
Macro.tags.has(name)
→ boolean Macro.tags.has(name)
→ 布尔值 Returns whether the named macro tag exists.
返回是否存在指定的宏标签。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string) Name of the macro tag to search for.name
: (字符串) 要搜索的宏标签名称。Macro.tags.has("else")
MacroContext
API See Also:
Macro
API.
参见: Macro
API。
Macro handlers are called with no arguments, but with their this
set to a macro (execution) context object. Macro context objects contain the following data and method properties.
宏处理程序不带任何参数被调用,但其 this
被设置为宏(执行)上下文对象。宏上下文对象包含以下数据和方法属性。
<MacroContext>.args
→ Array<any> An array of discrete arguments parsed from the argument string.
从参数字符串中解析出的离散参数数组。
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: <<someMacro "a" "b" "c">>
this.args.length // Returns 3
this.args[0] // Returns 'a'
this.args[1] // Returns 'b'
this.args[2] // Returns 'c'
<MacroContext>.args.full
→ string <MacroContext>.args.full
→ 字符串 The argument string after converting all TwineScript syntax elements into their native JavaScript counterparts.
将所有 TwineScript 语法元素转换为它们的原生 JavaScript 表示形式的参数字符串。
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: <<if $a is "b">>
this.args.full // Returns 'State.variables.a === "b"'
<MacroContext>.args.raw
→ string <MacroContext>.args.raw
→ 字符串 The unprocessed argument string.
未处理的参数字符串
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: <<if "a" is "b">>
this.args.raw // Returns '"a" is "b"'
<MacroContext>.name
→ string <MacroContext>.name
→ 字符串 The name of the macro.
宏的名称
v2.0.0
: Introduced. v2.0.0
: 引入。// Given: <<someMacro …>>
this.name // Returns 'someMacro'
<MacroContext>.output
→ HTMLElement
object <MacroContext>.output
→ HTMLElement
对象 The current output element.
当前输出元素。
v2.0.0
: Introduced. v2.0.0
: 引入。<MacroContext>.parent
→ null | object<MacroContext>.parent
→ null 或对象 The (execution) context object of the macro's parent, or null
if the macro has no parent.
宏父级的(执行)上下文对象,或如果没有父级则为 null
v2.0.0
: Introduced. v2.0.0
: 引入。<MacroContext>.parser
→ object <MacroContext>.parser
→ 对象 The parser instance that generated the macro call.
生成宏调用的解析实例。
v2.0.0
: Introduced. v2.0.0
: 引入。<MacroContext>.payload
→ null | Array<object> The text of a container macro parsed into discrete payload objects by tag. Payload objects have the following properties:
容器宏的文本通过标签解析成离散的有效负载对象。有效负载对象具有以下属性:
name
: (string) Name of the current tag.name
: (字符串) 当前标签的名称。args
: (Array<any>) The current tag's argument string parsed into an array of discrete arguments. Equivalent in function to <MacroContext>.args
.
<MacroContext>.args
。args.full
: (string) The current tag's argument string after converting all TwineScript syntax elements into their native JavaScript counterparts. Equivalent in function to <MacroContext>.args.full
.args.full
: (字符串) 将所有 TwineScript 语法元素转换为它们的原生 JavaScript 对应项后的当前标签的参数字符串。在功能上等同于 <MacroContext>.args.full
。args.raw
: (string) The current tag's unprocessed argument string. Equivalent in function to <MacroContext>.args.raw
.args.raw
: (字符串) 当前标签的未处理参数字符串。在功能上等同于 <MacroContext>.args.raw
。contents
: (string) The current tag's contents—i.e., the text between the current tag and the next.contents
: (字符串) 当前标签的内容——即当前标签与下一个标签之间的文本。v2.0.0
: Introduced. v2.0.0
: 引入。<MacroContext>.self
→ object <MacroContext>.self
→ 对象 The macro's definition—created via Macro.add()
.
宏的定义——通过 Macro.add()
创建。
v2.0.0
: Introduced. v2.0.0
: 引入。<MacroContext>.contextFilter(predicate)
→ Array<object> <MacroContext>.contextFilter(predicate)
→ 数组对象 Returns a new array containing all of the macro's ancestors that passed the test implemented by the given predicate function or an empty array, if no members pass.
返回一个新数组,包含所有通过给定谓词函数测试的宏祖先,如果没有成员通过,则返回空数组。
v2.37.0
: Introduced. v2.37.0
: 引入。predicate
: (function) The function used to test each ancestor execution context object, which is passed in as its sole parameter.predicate
: (函数) 用于测试每个祖先执行上下文对象的函数,该函数作为其唯一参数传入。var isInclude = function (ctx) { return ctx.name === "include"; };
this.contextFilter(isInclude); // Returns an array of all <<include>> macro ancestors
<MacroContext>.contextFind(predicate)
→ object | undefined<MacroContext>.contextFind(predicate)
→ 对象 | 未定义 Returns the first of the macro's ancestors that passed the test implemented by the given predicate function or undefined
, if no members pass.
返回第一个通过给定谓词函数测试的宏祖先,如果没有成员通过,则返回 undefined
。
v2.37.0
: Introduced. v2.37.0
: 引入。predicate
: (function) The function used to test each ancestor execution context object, which is passed in as its sole parameter.var isInclude = function (ctx) { return ctx.name === "include"; };
this.contextFind(isInclude); // Returns the first <<include>> macro ancestor
<MacroContext>.contextSome(predicate)
→ boolean <MacroContext>.contextSome(predicate)
→ 布尔值 Returns whether any of the macro's ancestors passed the test implemented by the given predicate function.
返回宏的祖先中是否有任何一个通过了由给定谓词函数实现的测试。
v2.37.0
: Introduced. v2.37.0
: 引入。predicate
: (function) The function used to test each ancestor execution context object, which is passed in as its sole parameter.var isInclude = function (ctx) { return ctx.name === "include"; };
this.contextSome(isInclude); // Returns true if any ancestor was an <<include>> macro
<MacroContext>.error(message)
→ boolean:false <MacroContext>.error(message)
→ 布尔值:false Renders the message prefixed with the name of the macro and returns false
.
使用宏名称作为前缀渲染消息并返回 false
。
v2.0.0
: Introduced. v2.0.0
: 引入。message
: (string) The error message to output.message
:(字符串)要输出的错误消息。// Given: <<someMacro …>>
return this.error("oops"); // Outputs '<<someMacro>>: oops'
<MacroContext>.shadowHandler(callback [, doneCallback [, startCallback]])
→ function <MacroContext>.shadowHandler(callback [, doneCallback [, startCallback]])
→ 函数 Returns a callback function that wraps the specified callback functions to provide access to the variable shadowing system used by the <<capture>>
macro.
返回一个包装指定回调函数的回调函数,以提供对由 <<capture>>
宏使用的变量阴影系统访问。
Note:
All of the specified callbacks are invoked as the wrapper is invoked—meaning, with their this
set to the this
of the wrapper and with whatever parameters were passed to the wrapper.
注意:所有指定的回调都会在包装器被调用时触发——这意味着,它们的 this
被设置为包装器的 this
,并且传递给包装器的任何参数都会被使用。
Warning:
Only useful when you have an asynchronous callback that invokes code/content that needs to access story and/or temporary variables shadowed by <<capture>>
. If you don't know what that means, then this API is likely not for you.
警告:仅在您有一个异步回调,该回调调用需要访问被 <<capture>>
影射的故事和/或临时变量时才有效。如果您不明白这是什么意思,那么这个 API 可能不适合您。
v2.37.0
: Introduced. v2.37.0
: 引入。callback
: (function) The main callback function, executed when the wrapper is invoked. Receives access to variable shadows.callback
: (函数) 主回调函数,在包装器被调用时执行。接收访问变量阴影。doneCallback
: (optional, function) The finalization callback function, executed after the main callback
returns. Does not receive access to variable shadows.doneCallback
: (可选,函数) 最终化回调函数,在主 callback
返回后执行。不接收访问变量阴影。startCallback
: (optional, function) The initialization callback function, executed before the main callback
is invoked. Does not receive access to variable shadows.startCallback
: (可选,函数) 初始化回调函数,在主 callback
被调用之前执行。不接收访问变量阴影。$someElement.on('some_event', this.shadowHandler(function (ev) {
/* main asynchronous code */
}));
doneCallback
有一个可选的 doneCallback
$someElement.on('some_event', this.shadowHandler(
function (ev) {
/* main asynchronous code */
},
function (ev) {
/* asynchronous code invoked after the main code */
}
));
doneCallback
and startCallback
doneCallback
和 startCallback
$someElement.on('some_event', this.shadowHandler(
function (ev) {
/* main asynchronous code */
},
function (ev) {
/* asynchronous code invoked after the main code */
},
function (ev) {
/* asynchronous code invoked before the main code */
}
));
<MacroContext>.contextHas(filter)
→ boolean <MacroContext>.contextHas(filter)
→ 布尔值 Deprecated:
This method has been deprecated and should no longer be used. See the <MacroContext>.contextSome()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 <MacroContext>.contextSome()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of <MacroContext>.contextSome()
.<MacroContext>.contextSome()
。<MacroContext>.contextSelect(filter)
→ null | object<MacroContext>.contextSelect(filter)
→ null | 对象 Deprecated:
This method has been deprecated and should no longer be used. See the <MacroContext>.contextFind()
method for its replacement.
已弃用:此方法已被弃用,不应再使用。请参阅 <MacroContext>.contextFind()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of <MacroContext>.contextFind()
.<MacroContext>.contextFind()
。<MacroContext>.contextSelectAll(filter)
→ Array<object> <MacroContext>.contextSelectAll(filter)
→ 对象数组 Deprecated:
This method has been deprecated and should no longer be used. See the <MacroContext>.contextFilter()
method for its replacement.
已弃用:此方法已被弃用,不应再使用。请参阅 <MacroContext>.contextFilter()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of <MacroContext>.contextFilter()
.<MacroContext>.contextFilter()
。<MacroContext>.createShadowWrapper(callback [, doneCallback [, startCallback]])
→ function 函数 Deprecated:
This method has been deprecated and should no longer be used. See the <MacroContext>.shadowHandler()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 <MacroContext>.shadowHandler()
方法以获取其替代方案。
v2.14.0
: Introduced. v2.14.0
: 引入。v2.23.3
: Fixed an issue where shadows would fail for multiple layers of nested asynchronous code due to loss of context.v2.37.0
: Deprecated in favor of <MacroContext>.shadowHandler()
.<MacroContext>.shadowHandler()
。Passage
API Instances of the Passage
object are returned by the Story.get()
static method.
Passage
对象的实例由 Story.get()
静态方法返回。
All properties of Passage
objects should be treated as if they were read-only, as modifying them could result in unexpected behavior.
应当将 Passage
对象的所有属性视为只读,因为修改它们可能会导致意外行为。
<Passage>.id
→ string <Passage>.id
→ 字符串 The DOM-compatible ID of the passage, created from the slugified passage title.
段落与 DOM 兼容的 ID,由 slugified 段落标题创建。
v2.37.0
: Introduced. v2.37.0
: 引入。<Passage>.name
→ string <Passage>.name
→ 字符串 The name of the passage.
段落名称。
v2.37.0
: Introduced. v2.37.0
: 引入。<Passage>.tags
→ Array<string> <Passage>.tags
→ 数组 The tags of the passage.
段落的标签。
v2.0.0
: Introduced. v2.0.0
: 引入。<Passage>.text
→ string <Passage>.text
→ 字符串 The raw text of the passage.
该段落的原始文本。
v2.0.0
: Introduced. v2.0.0
: 引入。<Passage>.processText()
→ string <Passage>.processText()
→ 字符串 Returns the processed text of the passage, created from applying nobr
tag and image passage processing to its raw text.
返回经过应用 nobr
标签和图像段落处理后的处理文本。
v2.0.0
: Introduced. v2.0.0
: 引入。var passage = Story.get("The Ducky");
passage.processText() → Returns the fully processed text of "The Ducky" passage
<Passage>.domId
→ string <Passage>.domId
→ 字符串 Deprecated:
This property has been deprecated and should no longer be used. See the <Passage>.id
property for its replacement.
已弃用:此属性已被弃用,不应再使用。请参阅 <Passage>.id
属性以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of <Passage>.id
.<Passage>.id
。<Passage>.title
→ string <Passage>.title
→ 字符串 Deprecated:
This property has been deprecated and should no longer be used. See the <Passage>.name
property for its replacement.
已弃用:此属性已被弃用,不应再使用。请参阅 <Passage>.name
属性以了解其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of <Passage>.name
.<Passage>.name
。<Passage>.description()
→ string <Passage>.description()
→ 字符串 Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Save
API Note:
There are several configuration settings for saves that it would be wise for you to familiarize yourself with.
注意:保存功能有多个配置设置,您最好熟悉一下。
Warning:
Browser saves—i.e., auto and slot saves—are largely incompatible with private browsing modes, which cause all in-browser storage mechanisms to either persist only for the lifetime of the browsing session or fail outright.
警告:浏览器保存(即自动和槽位保存)与私密浏览模式 largely 不兼容,这会导致所有浏览器内存储机制要么仅在浏览会话期间持续,要么完全失败。
Note:
Adding additional properties directly to save data objects is not recommended. Instead, use the metadata
property.
注意:不建议直接向保存数据对象添加额外属性。相反,请使用 metadata
属性。
A save data object has the following properties:
保存数据对象具有以下属性:
date
: (integer
) The save's creation date (in milliseconds elapsed since epoch).date
: ( integer
) 保存的创建日期(自纪元以来经过的毫秒数)。desc
: (string
) The save's description.desc
: ( string
) 保存的描述。id
: (string
) The save ID. See the Config.saves.id
for details.id
: ( string
) 保存 ID。有关详细信息,请参阅 Config.saves.id
。metadata
: (optional, any
) The save's metadata, which must be JSON-serializable. Exists only if specified. See the appropriate save API or Config.saves.metadata
for details.metadata
(可选, any
) 保存的元数据,必须是可 JSON 序列化的。如果指定则存在。请参阅相应的保存 API 或 Config.saves.metadata
获取详细信息。state
: (object
) The marshaled story state. See below for details.state
( object
) 序列化的故事状态。请参阅以下详细信息。type
: (Save.Type
) The save's type. See Save.Type
for details.type
( Save.Type
) 保存的类型。请参阅 Save.Type
获取详细信息。version
: (optional, any
) The save's version. Exists only if specified. See Config.saves.version
for details.version
(可选, any
) 保存的版本。如果指定则存在。请参阅 Config.saves.version
获取详细信息。The marshaled story state object, from the state
property, has the following properties:
从 state
属性中序列化的故事状态对象具有以下属性:
expired
: (optional, Array<string>
) The array of expired moment passage titles. Exists only if any moments have expired.expired
: (可选, Array<string>
)已过期的时刻段落标题数组。如果存在任何已过期的时刻,则存在。history
: (Array<object>
) The array of moment objects. See below for details.history
: ( Array<object>
)时刻对象的数组。详细信息请见下文。index
: (integer
) The index of the active moment.index
: ( integer
) 活动时刻的索引。seed
: (optional, string
) The seed of the seedable PRNG. Exists only if enabled.seed
:(可选, string
)可种子化伪随机数生成器的种子。如果启用则存在。Each moment object, from the history
property's array, has the following properties:
每个时刻对象,从 history
属性的数组中,具有以下属性:
pull
: (optional, integer
) The current pull count of the seedable PRNG. Exists only if enabled.title
: (string
) The name of the associated passage.variables
: (object
) The current variable store object, which contains sigil-less name ⇒ value pairs—e.g., $foo
exists as the property foo
.$foo
作为属性 foo
存在。Save descriptor objects are only provided for browser saves and are identical to save data objects save that they do not include a state
property
保存描述符对象仅适用于浏览器保存,并且与保存数据对象相同,只是它们不包含 state
属性
Save.Type
Save types pseudo-enumeration. Used to denote the type of save.
保存类型伪枚举。用于表示保存的类型。
v2.33.0
: Introduced. v2.33.0
: 引入。v2.37.0
: Changed into a public API.v2.37.0
:已变为公共 API。Type 类型 | Description 描述 |
---|---|
Save.Type.Auto |
Browser auto saves. 浏览器自动保存。 |
Save.Type.Base64 |
Base64 string saves. Base64 字符串保存。 |
Save.Type.Disk |
Disk saves. 磁盘保存。 |
Save.Type.Slot |
Browser slot saves. 浏览器槽保存。 |
Save.browser.size
→ integer
The total number of existing browser saves, both auto and slot.
现有浏览器保存总数,包括自动保存和槽位保存。
v2.37.0
: Introduced. v2.37.0
: 引入。The integer
count of existing browser saves.
已存在浏览器保存的 integer
数量。
console.log(`There are currently ${Save.browser.size} browser saves`);
if (Save.browser.size > 0) {
/* Browser saves exist. */
}
if (Save.browser.size === 0) {
/* No browser saves exist. */
}
Save.browser.clear()
Deletes all existing browser saves, both auto and slot.
删除所有现有的浏览器保存,包括自动和槽位。
v2.37.0
: Introduced. v2.37.0
: 引入。Save.browser.clear();
Save.browser.continue()
→ Promise
Loads the most recent browser save, either auto or slot.
加载最近的浏览器保存,无论是自动还是槽位。
Note:
The default UI includes a Continue button that makes use of this API. Thus, unless you disable or replace the default UI, players already have access to this functionality.
注意:默认 UI 包括一个“继续”按钮,该按钮使用此 API。因此,除非您禁用或替换默认 UI,否则玩家已经可以访问此功能。
Warning:
Saves cannot be loaded during startup and any attempt to do so will cause an error.
警告:启动期间无法加载保存,任何尝试加载保存的操作都将导致错误。
v2.37.0
: Introduced. v2.37.0
: 引入。A Promise
that simply resolves, or rejects with an error if the save could not be loaded.
一个简单的解析器,或者如果无法加载保存,则拒绝并报错。
Load the most recent browser save, only handling failure. This should be sufficient in the majority of cases.
仅处理失败情况,加载最新的浏览器保存。这在大多数情况下应该足够了。
if (Save.browser.size > 0) {
Save.browser.continue()
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
}
else {
/* No browser saves exist. */
}
Load the most recent browser save, handling both success and failure.
加载最新的浏览器保存,处理成功和失败两种情况。
if (Save.browser.size > 0) {
Save.browser.continue()
.then(() => {
/* Success. Do something special. */
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
}
else {
/* No browser saves exist. */
}
Save.browser.isEnabled()
→ boolean
Determines whether any browser saves are enabled, either auto, slot, or both.
确定是否任何浏览器保存都启用,无论是自动、槽位还是两者都启用。
v2.37.0
: Introduced. v2.37.0
: 引入。Boolean true
if any browser saves are enabled, elsewise false
.
如果任何浏览器保存功能已启用,否则 false
。
if (Save.browser.isEnabled()) {
/* Some browser saves are enabled. */
}
Save.browser.auto.size
→ integer
The total number of existing browser auto saves.
现有浏览器自动保存的总数。
v2.37.0
: Introduced. v2.37.0
: 引入。The integer
count of existing browser auto saves.
已存在浏览器自动保存的 integer
数量。
console.log(`There are currently ${Save.browser.auto.size} browser auto saves`);
if (Save.browser.auto.size > 0) {
/* Browser auto saves exist. */
}
if (Save.browser.auto.size === 0) {
/* No browser auto saves exist. */
}
Save.browser.auto.clear()
Deletes all existing auto saves.
删除所有现有自动保存。
v2.37.0
: Introduced. v2.37.0
: 引入。Save.browser.auto.clear();
Save.browser.auto.delete(index)
Deletes the auto save at the given index.
删除给定索引的自动保存。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Auto save index (0
-based). Must be in the range 0
–Config.saves.maxAutoSaves
.index
: ( integer
) 自动保存索引( 0
- 基于的)。必须在 0
– Config.saves.maxAutoSaves
范围内。An Error
instance. 一个 Error
实例。
Delete the auto save at the given index, handling failure.
删除指定索引处的自动保存,处理失败情况。
try {
Save.browser.auto.delete(index);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.browser.auto.entries()
→ Array<object>
Provides an array of details about all auto saves.
提供所有自动保存的详细信息数组。
v2.37.0
: Introduced. v2.37.0
: 引入。An Array
of { index, info }
generic objects, or an empty Array
if no auto saves exist.
一个 Array
的 { index, info }
通用对象,或者如果没有自动保存则为一个空的 Array
。
index
: (integer
) The auto save's index (0
-based).index
: ( integer
) 自动保存的索引( 0
基础)。info
: (object
) The save's descriptor object.info
: ( object
) 保存的描述对象。An Error
instance. 一个 Error
实例。
Save.browser.auto.entries().forEach(function (entry) {
console.log(`Descriptor of the auto save at index ${entry.index}:`, entry.info);
});
Save.browser.auto.get(index)
→ object
Details the auto save at the given index.
详细说明在指定索引处的自动保存。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Auto save index (0
-based). Must be in the range 0
–Config.saves.maxAutoSaves
.integer
)。必须在 0
– Config.saves.maxAutoSaves
的范围内。The descriptor object for the auto save if it exists, elsewise null
.
如果存在,则为自动保存的描述符对象,否则为 null
。
An Error
instance. 一个 Error
实例。
console.log(`Descriptor of the auto save at index ${index}:`, Save.browser.auto.get(index));
Save.browser.auto.has(index)
→ boolean
Determines whether the auto save at the given index exists.
判断给定索引处的自动保存是否存在。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Auto save index (0
-based). Must be in the range 0
–Config.saves.maxAutoSaves
.index
: ( integer
) 自动保存索引( 0
基于的)。必须在 0
– Config.saves.maxAutoSaves
的范围内。Boolean true
if the auto save exists, elsewise false
.
如果自动保存存在,则为布尔值 true
,否则为 false
。
An Error
instance. 一个 Error
实例。
if (Save.browser.auto.has(index)) {
/* The auto save at the given index exists. */
}
Save.browser.auto.isEnabled()
→ boolean
Determines whether auto saves are enabled.
确定是否启用自动保存。
v2.37.0
: Introduced. v2.37.0
: 引入。Boolean true
if auto saves are anabled, elsewise false
.
如果自动保存已启用,否则 false
。
if (Save.browser.auto.isEnabled()) {
/* Auto saves are enabled. */
}
Save.browser.auto.load(index)
→ Promise
Loads the auto save at the given index.
加载指定索引的自动保存。
Warning:
Saves cannot be loaded during startup and any attempt to do so will cause an error.
警告:启动期间无法加载保存,任何尝试这样做都会导致错误。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Auto save index (0
-based). Must be in the range 0
–Config.saves.maxAutoSaves
.index
: ( integer
) 自动保存索引( 0
基于的)。必须在 0
– Config.saves.maxAutoSaves
的范围内。A Promise
that simply resolves, or rejects with an error if the save could not be loaded.
一个简单的解析器,或者如果无法加载保存,则拒绝并报错。
Load the auto save at the given index. This should be sufficient in the majority of cases.
加载指定索引的自动保存。这在大多数情况下应该足够了。
Save.browser.auto.load(index)
.then(() => {
Engine.show();
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
Save.browser.auto.save([desc [, metadata]])
Saves an auto save. If all auto save positions are full, replaces the oldest auto save.
保存自动保存。如果所有自动保存位置已满,则替换最旧的自动保存。
v2.37.0
: Introduced. v2.37.0
: 引入。desc
: (optional, string
) The description of the auto save. If omitted or null
, defaults to the active passage's description.desc
(可选, string
)自动保存的描述。如果省略或 null
,则默认为活动节段的描述。metadata
: (optional, any
) The data to be stored in the save object's metadata
property. Must be JSON-serializable.metadata
(可选, any
)要存储在保存对象 metadata
属性的中的数据。必须是可 JSON 序列化的。An Error
instance. 一个 Error
实例。
Save an auto save with the default description and no metadata, handling failure.
保存一个带有默认描述和没有元数据的自动保存,并处理失败情况。
try {
Save.browser.auto.save();
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save an auto save with a description and no metadata, handling failure.
保存一个带有描述且无元数据的自动保存,处理失败情况。
try {
Save.browser.auto.save("In the wilds");
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save an auto save with the default description and metadata, handling failure.
保存具有默认描述和元数据的自动保存,处理失败情况。
try {
const saveMetadata = {
chars : ['Celes', 'Locke', 'Edward'],
gold : 2345
};
Save.browser.auto.save(null, saveMetadata);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save an auto save with a description and metadata, handling failure.
保存带有描述和元数据的自动保存,处理失败情况。
try {
const saveMetadata = {
chars : ['Celes', 'Locke', 'Edward'],
gold : 2345
};
Save.browser.auto.save("In the wilds", saveMetadata);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.browser.slot.size
→ integer
The total number of existing browser slot saves.
现有浏览器槽位保存的总数。
v2.37.0
: Introduced. v2.37.0
: 引入。The integer
count of existing browser slot saves.
现有浏览器槽位保存的 integer
计数。
console.log(`There are currently ${Save.browser.slot.size} browser slot saves`);
if (Save.browser.slot.size > 0) {
/* Browser slot saves exist. */
}
if (Save.browser.slot.size === 0) {
/* No browser slot saves exist. */
}
Save.browser.slot.clear()
Deletes all existing slot saves.
删除所有现有的槽位保存。
v2.37.0
: Introduced. v2.37.0
: 引入。Save.browser.slot.clear();
Save.browser.slot.delete(index)
Deletes the slot save at the given index.
删除指定索引处的槽位保存。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Slot save index (0
-based). Must be in the range 0
–Config.saves.maxSlotSaves
.index
: ( integer
) 槽位保存索引( 0
- 基于的)。必须在 0
– Config.saves.maxSlotSaves
范围内。An Error
instance. 一个 Error
实例。
Delete the slot save at the given index, handling failure.
删除指定索引处的槽位保存,处理失败情况。
try {
Save.browser.slot.delete(index);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.browser.slot.entries()
→ Array<object>
Provides an array of details about all slot saves.
提供所有槽位保存的详细信息数组。
v2.37.0
: Introduced. v2.37.0
: 引入。An Array
of { index, info }
generic objects, or an empty Array
if no slot saves exist.
一个 Array
的 { index, info }
通用对象,或者如果没有槽位保存存在,则为空的 Array
。
index
: (integer
) The slot save's index (0
-based).index
: ( integer
) 槽位保存的索引( 0
基础)。info
: (object
) The save's descriptor object.info
: ( object
) 保存的描述对象。An Error
instance. 一个 Error
实例。
Save.browser.slot.entries().forEach(function (entry) {
console.log(`Descriptor of the slot save at index ${entry.index}:`, entry.info);
});
Save.browser.slot.get(index)
→ object
Details the slot save at the given index.
详细说明在指定索引处的槽位保存情况。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Slot save index (0
-based). Must be in the range 0
–Config.saves.maxSlotSaves
.index
: ( integer
) 槽位保存索引(基于 0
)。必须在 0
– Config.saves.maxSlotSaves
的范围内。The descriptor object for the slot save if it exists, elsewise null
.
如果存在,则为槽位保存的描述符对象,否则为 null
。
An Error
instance. 一个 Error
实例。
console.log(`Descriptor of the slot save at index ${index}:`, Save.browser.slot.get(index));
Save.browser.slot.has(index)
→ boolean
Determines whether the slot save at the given index exists.
确定给定索引处的槽位保存是否存在。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Slot save index (0
-based). Must be in the range 0
–Config.saves.maxSlotSaves
.index
: ( integer
) 槽位保存索引( 0
- 基于的)。必须在 0
– Config.saves.maxSlotSaves
范围内。Boolean true
if the slot save exists, elsewise false
.
布尔值 true
如果槽位保存存在,否则 false
.
An Error
instance. 一个 Error
实例。
if (Save.browser.slot.has(index)) {
/* The slot save at the given index exists. */
}
Save.browser.slot.isEnabled()
→ boolean
Determines whether slot saves are enabled.
确定槽位保存是否启用。
v2.37.0
: Introduced. v2.37.0
: 引入。Boolean true
if slot saves are anabled, elsewise false
.
布尔值 true
如果槽位保存已启用,否则 false
.
if (Save.browser.slot.isEnabled()) {
/* Slot saves are enabled. */
}
Save.browser.slot.load(index)
→ Promise
Loads the slot save at the given index.
加载给定索引处的槽位保存。
Warning:
Saves cannot be loaded during startup and any attempt to do so will cause an error.
警告:启动期间无法加载保存,任何尝试这样做都会导致错误。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Slot save index (0
-based). Must be in the range 0
–Config.saves.maxSlotSaves
.index
: ( integer
) 槽位保存索引( 0
- 基于的)。必须在 0
– Config.saves.maxSlotSaves
范围内。A Promise
that simply resolves, or rejects with an error if the save could not be loaded.
一个简单的解析器,或者如果无法加载保存,则拒绝并报错。
Load the slot save at the given index. This should be sufficient in the majority of cases.
加载指定索引处的槽位保存。这在大多数情况下应该足够了。
Save.browser.slot.load(index)
.then(() => {
Engine.show();
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
Save.browser.slot.save(index, [desc [, metadata]])
Saves a slot save to the given index.
将槽位保存保存到指定索引。
v2.37.0
: Introduced. v2.37.0
: 引入。index
: (integer
) Slot save index (0
-based). Must be in the range 0
–Config.saves.maxSlotSaves
.index
: ( integer
) 槽位保存索引( 0
- 基于的)。必须在 0
– Config.saves.maxSlotSaves
范围内。desc
: (optional, string
) The description of the slot save. If omitted or null
, defaults to the active passage's description.desc
:(可选, string
)槽位保存的描述。如果省略或 null
,则默认为活动篇章的描述。metadata
: (optional, any
) The data to be stored in the save object's metadata
property. Must be JSON-serializable.metadata
(可选, any
)要存储在保存对象 metadata
属性的中的数据。必须是可 JSON 序列化的。An Error
instance. 一个 Error
实例。
Save to slot save index 0
with the default description and no metadata, handling failure.
将内容保存到槽位 save index 0
,使用默认描述和没有元数据,处理失败。
try {
Save.browser.slot.save(0);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save to slot save index 0
with a description and no metadata, handling failure.
将内容保存到槽位 save index 0
,带有描述但没有元数据,处理失败。
try {
Save.browser.slot.save(0, "In the wilds");
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save to slot save index 0
with the default description and metadata, handling failure.
使用默认描述和元数据将数据保存到槽位 save index 0
,处理失败情况。
try {
const saveMetadata = {
chars : ['Celes', 'Locke', 'Edward'],
gold : 2345
};
Save.browser.slot.save(0, null, saveMetadata);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save to slot save index 0
with a description and metadata, handling failure.
使用描述和元数据将数据保存到槽位 save index 0
,处理失败情况。
try {
const saveMetadata = {
chars : ['Celes', 'Locke', 'Edward'],
gold : 2345
};
Save.browser.slot.save(0, "In the wilds", saveMetadata);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.disk.export(filename)
Exports all existing browser saves as a bundle to disk, which may be restored via Save.disk.import()
.
将所有现有的浏览器存档导出为存档包到磁盘,可以通过 Save.disk.import()
恢复。
v2.37.0
: Introduced. v2.37.0
: 引入。filename
: (string
) The base filename of the browser save export, which gets slugified to remove most symbols. Appended to this is a datestamp (format: YYYMMDD-hhmmss
) and the file extension .savesbundle
—e.g., "The Scooby Chronicles"
would result in the full filename: the-scooby-chronicles-{datestamp}.savesbundle
.YYYMMDD-hhmmss
)和文件扩展名 .savesbundle
,例如, "The Scooby Chronicles"
将生成完整的文件名: the-scooby-chronicles-{datestamp}.savesbundle
。An Error
instance. 一个 Error
实例。
Export all saves as a bundle with a base filename, handling failure.
将所有保存导出为一个包含基本文件名的包,并处理失败情况。
try {
Save.disk.export('The 6th Fantasy');
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.disk.import(event)
→ Promise
Imports a saves bundle from disk, created via Save.disk.export()
.
从磁盘导入通过 Save.disk.export()
创建的保存包。
Note:
This method must be used as, or be called by, the change
event handler of an <input type="file">
element.
注意:此方法必须作为或由 <input type="file">
元素的 change
事件处理器调用。
Warning:
All existing browser saves will be deleted as part of restoring the exported save bundle.
警告:在恢复导出的存档包时,所有现有的浏览器保存内容将被删除。
v2.37.0
: Introduced. v2.37.0
: 引入。event
: (Event
) The event object that was passed to the change
event handler of the associated <input type="file">
element.change
事件处理器的 <input type="file">
事件。A Promise
that simply resolves, or rejects with an error if the browser saves bundle could not be imported.
一个简单的 Promise
,如果浏览器保存的包无法导入,则拒绝或抛出错误。
Import the saves bundle from disk, only handling failure. This should be sufficient in the majority of cases.
导入磁盘上的保存包,仅处理失败情况。这在大多数情况下应该足够了。
jQuery(document.createElement('input'))
.prop({
id : 'saves-import-file',
name : 'saves-import-file',
type : 'file'
})
.on('change', ev => {
// You must provide the event to Save.disk.import()
Save.disk.import(ev)
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
});
Import the saves bundle from disk, handling both success and failure.
导入从磁盘上的保存包,处理成功和失败的情况。
jQuery(document.createElement('input'))
.prop({
id : 'saves-import-file',
name : 'saves-import-file',
type : 'file'
})
.on('change', function (ev) {
// You must provide the event to Save.browser.import()
Save.disk.import(ev)
.then(() => {
/* Success. Do something special. */
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
});
Save.disk.load(event)
→ Promise
Loads the given save from disk, created via Save.disk.save()
.
加载通过 Save.disk.save()
创建的磁盘上的给定保存。
Note:
This method must be used as, or be called by, the change
event handler of an <input type="file">
element.
注意:此方法必须作为或由 <input type="file">
元素的 change
事件处理器调用。
Warning:
Saves cannot be loaded during startup and any attempt to do so will cause an error.
警告:启动期间无法加载保存,任何尝试这样做都会导致错误。
v2.37.0
: Introduced. v2.37.0
: 引入。event
: (Event
) The event object that was passed to the change
event handler of the associated <input type="file">
element.change
事件处理器的 <input type="file">
事件。A Promise
that resolves with the save's metadata (any
), or rejects with an error if the save could not be loaded.
一个 Promise
,它会根据保存的元数据( any
)解析,或者在无法加载保存时拒绝并返回错误。
Load the disk save. This should be sufficient in the majority of cases.
加载磁盘保存。这在大多数情况下应该足够了。
jQuery(document.createElement('input'))
.prop({
id : 'saves-disk-load-file',
name : 'saves-disk-load-file',
type : 'file'
})
.on('change', ev => {
// You must provide the event to Save.disk.load()
Save.disk.load(ev)
.then(metadata => {
Engine.show();
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
});
<<button "Load From Disk">>
<<script>>
jQuery(document.createElement('input'))
.prop('type', 'file')
.on('change', ev => {
// You must provide the event to Save.disk.load()
Save.disk.load(ev)
.then(metadata => {
Engine.show();
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
})
.trigger('click');
<</script>>
<</button>>
Save.disk.save(filename [, metadata])
Saves the current story state to disk, which may be restored via Save.disk.load()
.
将当前故事状态保存到磁盘,这可以通过 Save.disk.load()
恢复。
v2.37.0
: Introduced. v2.37.0
: 引入。filename
: (string
) The base filename of the disk save, which gets slugified to remove most symbols. Appended to this is a datestamp (format: YYYMMDD-hhmmss
) and the file extension .save
—e.g., "The Scooby Chronicles"
would result in the full filename: the-scooby-chronicles-{datestamp}.save
.YYYMMDD-hhmmss
)和文件扩展名 .save
—例如, "The Scooby Chronicles"
将生成完整的文件名: the-scooby-chronicles-{datestamp}.save
。metadata
: (optional, any
) The data to be stored in the save object's metadata
property. Must be JSON-serializable.metadata
(可选, any
)要存储在保存对象 metadata
属性的中的数据。必须是可 JSON 序列化的。An Error
instance. 一个 Error
实例。
Save with a base filename and no metadata, handling failure.
使用基本文件名保存,不包含元数据,处理失败情况。
try {
Save.disk.save("The 6th Fantasy");
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save with a base filename and metadata, handling failure.
使用基本文件名和元数据保存,处理失败情况。
try {
const saveMetadata = {
chars : ['Celes', 'Locke', 'Edward'],
gold : 2345
};
Save.disk.save("The 6th Fantasy", saveMetadata);
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.base64.export()
→ string
Exports all existing browser saves as a bundle to a Base64 string, which may be restored via Save.base64.import()
.
将所有现有的浏览器保存记录作为一个包导出为 Base64 字符串,可以通过 Save.base64.import()
.进行恢复。
v2.37.0
: Introduced. v2.37.0
: 引入。An Error
instance. 一个 Error
实例。
Export all saves as a bundle, handling failure.
导出所有存档为捆绑包,处理失败情况。
try {
const base64Save = Save.base64.export();
/* Do something with the saves bundle. */
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.base64.import(bundle)
→ Promise
Imports the given Base64 saves bundle string, created via Save.base64.export()
.
导入通过 Save.base64.export()
创建的给定 Base64 存档捆绑包字符串。
Warning:
All existing browser saves will be deleted as part of restoring the exported save bundle.
警告:在恢复导出的存档包时,所有现有的浏览器保存内容将被删除。
v2.37.0
: Introduced. v2.37.0
: 引入。bundle
: (string
) The Base64 saves bundle string.bundle
: ( string
) Base64 保存的包字符串。A Promise
that simply resolves, or rejects with an error if the browser saves bundle could not be imported.
一个简单的 Promise
,如果浏览器保存的包无法导入,则拒绝或抛出错误。
Import the saves bundle, only handling failure. This should be sufficient in the majority of cases.
仅处理导入保存包的失败情况,这在大多数情况下应该足够。
Save.base64.import(base64Bundle)
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
Import the saves bundle, handling both success and failure.
处理导入保存包的成功和失败情况。
Save.base64.import(base64Bundle)
.then(() => {
/* Success. Do something special. */
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
Save.base64.load(save)
→ Promise
Loads the given Base64 save string, created via Save.base64.save()
.
加载由 Save.base64.save()
生成的给定 Base64 保存字符串。
Warning:
Saves cannot be loaded during startup and any attempt to do so will cause an error.
警告:启动期间无法加载保存,任何尝试这样做都会导致错误。
v2.37.0
: Introduced. v2.37.0
: 引入。save
: (string
) The Base64 save string.save
: ( string
) 基础 64 保存字符串。A Promise
that resolves with the save's metadata (any
), or rejects with an error if the save could not be loaded.
一个 Promise
,它会根据保存的元数据( any
)解析,或者在无法加载保存时拒绝并返回错误。
Load the save string. This should be sufficient in the majority of cases.
加载保存字符串。这在大多数情况下应该足够。
Save.base64.load(base64Save)
.then(metadata => {
Engine.show();
})
.catch(error => {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
});
Save.base64.save([metadata])
→ string
Saves the current story state as a Base64 string.
将当前故事状态保存为 Base64 字符串。
v2.37.0
: Introduced. v2.37.0
: 引入。metadata
: (optional, any
) The data to be stored in the save object's metadata
property. Must be JSON-serializable.metadata
(可选, any
)要存储在保存对象 metadata
属性的中的数据。必须是可 JSON 序列化的。A Base64 save string
.
Base64 保存 string
.
An Error
instance. 一个 Error
实例。
Save without metadata, handling failure.
不保存元数据,处理失败。
try {
const base64Save = Save.base64.save();
/* Do something with the save. */
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save with metadata, handling failure.
保存元数据,处理失败。
try {
const saveMetadata = {
chars : ['Celes', 'Locke', 'Edward'],
gold : 2345
};
const base64Save = Save.base64.save(saveMetadata);
/* Do something with the save. */
}
catch (error) {
/* Failure. Handle the error. */
console.error(error);
UI.alert(error);
}
Save.onLoad.size
→ integer
The total number of currently registered on-load handlers.
当前注册的加载处理器的总数。
v2.36.0
: Introduced. v2.36.0
: 引入。The integer
count of currently registered on-load handlers.
当前注册的加载处理器的 integer
计数。
console.log('There are %d onLoad handlers registered.', Save.onLoad.size);
Save.onLoad.add(handler)
Performs any required processing before the save data is loaded—e.g., upgrading out-of-date save data. The handler is passed one parameter, the save object to be processed. If it encounters an unrecoverable problem during its processing, it may throw an exception containing an error message; the message will be displayed to the player and loading of the save will be terminated.
在加载数据之前执行任何必要的处理 - 例如,升级过时的存档数据。处理程序接收一个参数,即要处理的存档对象。如果在处理过程中遇到无法恢复的问题,它可能会抛出一个包含错误信息的异常;该消息将显示给玩家,并终止加载存档。
v2.36.0
: Introduced. v2.36.0
: 引入。handler
: (function) The handler function to be executed upon the loading of a save.handler
: (函数) 在加载存档时执行的处理器函数。An Error
instance. 一个 Error
实例。
save
: (object
) The save object to be processed.Save.onLoad.add(function (save) {
/* code to process the save object before it's loaded */
});
type
property and the Save.Type
pseudo-enumerationtype
属性和 Save.Type
伪枚举。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;
}
}
});
Save.onLoad.clear()
Deletes all currently registered on-load handlers.
删除所有当前注册的加载处理程序。
v2.36.0
: Introduced. v2.36.0
: 引入。Save.onLoad.clear();
Save.onLoad.delete(handler)
→ boolean
Deletes the specified on-load handler.
删除指定的加载处理程序。
v2.36.0
: Introduced. v2.36.0
: 引入。handler
: (function) The handler function to be deleted.handler
(函数)要删除的处理程序函数。Boolean true
if the handler existed, elsewise false
.
布尔值 true
如果处理程序存在,否则 false
。
// Given:
// let myOnLoadHandler = function (save) {
// /* code to process the save object before it's loaded */
// };
// Save.onLoad.add(myOnLoadHandler);
Save.onLoad.delete(myOnLoadHandler);
Save.onSave.size
→ integer
The total number of currently registered on-save handlers.
当前已注册的保存处理程序总数。
v2.36.0
: Introduced. v2.36.0
: 引入。The integer
count of currently registered on-save handlers.
当前注册的保存处理器的数量 integer
。
console.log('There are %d onSave handlers registered.', Save.onSave.size);
Save.onSave.add(handler)
Performs any required processing before the save data is saved. The handler is passed one parameter, the save object to be processed.
在保存数据保存之前执行任何必要的处理。处理程序传递一个参数,即要处理的保存对象。
v2.36.0
: Introduced. v2.36.0
: 引入。v2.37.0
: Deprecated handlers' details
parameter.v2.37.0
:已弃用处理器的 details
参数。handler
: (function) The handler function to be executed upon the saving of a save.handler
:在保存时执行的处理函数(function)。An Error
instance. 一个 Error
实例。
save
: (object
) The save object to be processed.Save.onSave.add(function (save) {
/* code to process the save object before it's saved */
});
type
property and the Save.Type
pseudo-enumerationtype
属性和 Save.Type
伪枚举。Save.onSave.add(function (save) {
switch (save.type) {
case Save.Type.Auto: {
/* code to process an auto save object before it's saved */
break;
}
case Save.Type.Base64: {
/* code to process a base64 save object before it's saved */
break;
}
case Save.Type.Disk: {
/* code to process a disk save object before it's saved */
break;
}
case Save.Type.Slot: {
/* code to process a slot save object before it's saved */
break;
}
}
});
Save.onSave.clear()
Deletes all currently registered on-save handlers.
删除所有当前注册的保存处理程序。
v2.36.0
: Introduced. v2.36.0
: 引入。Save.onSave.clear();
Save.onSave.delete(handler)
→ boolean
Deletes the specified on-save handler.
删除指定的保存时处理器。
v2.36.0
: Introduced. v2.36.0
: 引入。handler
: (function) The handler function to be deleted.handler
: (函数) 要删除的处理函数。Boolean true
if the handler existed, elsewise false
.
布尔值 true
如果处理程序存在,否则 false
。
// Given:
// let myOnSaveHandler = function (save) {
// /* code to process the save object before it's saved */
// };
// Save.onSave.add(myOnSaveHandler);
Save.onSave.delete(myOnSaveHandler);
Save.clear()
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.clear()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.clear()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.clear()
method.v2.37.0
: 已废弃,改用 Save.browser.clear()
方法。Save.get()
Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Save.ok()
→ boolean
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.isEnabled()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.isEnabled()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.isEnabled()
method.Save.browser.isEnabled()
方法。Save.autosave.delete()
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.auto.delete()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.auto.delete()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.auto.delete()
method.Save.browser.auto.delete()
方法。Save.autosave.get()
→ object
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.auto.get()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.auto.get()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.auto.get()
method.Save.browser.auto.get()
方法。Save.autosave.has()
→ boolean
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.auto.has()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.auto.has()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.auto.has()
method.Save.browser.auto.has()
方法。Save.autosave.load()
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.auto.load()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.auto.load()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.auto.load()
method.Save.browser.auto.load()
方法。Save.autosave.ok()
→ boolean
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.auto.isEnabled()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.auto.isEnabled()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.auto.isEnabled()
method.Save.browser.auto.isEnabled()
方法。Save.autosave.save([title [, metadata]])
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.auto.save()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.auto.save()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.auto.save()
method.Save.browser.auto.save()
方法。Save.slots.length
→ integer
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.size
property for its replacement.
已弃用:此方法已被弃用,不应再使用。请参阅 Save.browser.slot.size
属性以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.size
property.Save.browser.slot.size
属性。Save.slots.count()
→ integer
Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Save.slots.delete(slot)
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.delete()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.slot.delete()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.delete()
method.Save.browser.slot.delete()
方法。Save.slots.get(slot)
→ object
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.get()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.slot.get()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.get()
method.Save.browser.slot.get()
方法。Save.slots.has(slot)
→ boolean
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.has()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.slot.has()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.has()
method.Save.browser.slot.has()
方法。Save.slots.isEmpty()
→ boolean
Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。Save.slots.load(slot)
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.load()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.slot.load()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.load()
method.Save.browser.slot.load()
方法。Save.slots.ok()
→ boolean
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.isEnabled()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.slot.isEnabled()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.isEnabled()
method.Save.browser.slot.isEnabled()
方法。Save.slots.save(slot [, title [, metadata]])
Deprecated:
This method has been deprecated and should no longer be used. See the Save.browser.slot.save()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.browser.slot.save()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.browser.slot.save()
method.Save.browser.slot.save()
方法。Save.import(event)
Deprecated:
This method has been deprecated and should no longer be used. See the Save.disk.load()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.disk.load()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of the Save.disk.load()
method.Save.disk.load()
方法。Save.export([filename [, metadata]])
Deprecated:
This method has been deprecated and should no longer be used. See the Save.disk.save()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.disk.save()
方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.8.0
: Added metadata
parameter.metadata
参数。v2.37.0
: Deprecated in favor of the Save.disk.save()
method.Save.disk.save()
方法。Save.deserialize(saveStr)
→ any
| null
Deprecated:
This method has been deprecated and should no longer be used. See the Save.base64.load()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.base64.load()
方法以获取其替代方案。
v2.21.0
: Introduced. v2.21.0
: 引入。v2.37.0
: Deprecated in favor of the Save.base64.load()
method.Save.base64.load()
方法。Save.serialize([metadata])
→ string
| null
Deprecated:
This method has been deprecated and should no longer be used. See the Save.base64.save()
method for its replacement.
已废弃:此方法已被废弃,不应再使用。请参阅 Save.base64.save()
方法以获取其替代方案。
v2.21.0
: Introduced. v2.21.0
: 引入。v2.37.0
: Deprecated in favor of the Save.base64.save()
method.Save.base64.save()
方法。Setting
API Manages the Settings dialog and settings
object.
管理设置对话框和 settings
对象。
Warning:
Setting
API method calls must be placed within your project's JavaScript section (Twine 2: the Story JavaScript; Twine 1/Twee: a script
-tagged passage) or settings will not function correctly.
警告: Setting
API 方法调用必须放在您的项目 JavaScript 部分(Twine 2:故事 JavaScript;Twine 1/Twee:一个 script
-标记的段落)中,否则设置将无法正确工作。
Setting.addHeader(name [, desc])
Adds a header to the Settings dialog.
添加设置对话框的标题。
v2.7.1
: Introduced. v2.7.1
: 引入。name
: (string) Name of the header.name
: (字符串)标题名称。desc
: (optional, string) Description explaining the header in greater detail. May contain markup.desc
: (可选,字符串)对标题的详细描述。可能包含标记。// Setting up a basic header
Setting.addHeader("Content Settings");
// Setting up a header w/ a description
Setting.addHeader("Content Settings", "Settings controlling what content is made available in the game.");
Setting.addList(name, definition)
Adds the named property to the settings
object and a list control for it to the Settings dialog.
将命名属性添加到 settings
对象中,并将其列表控件添加到设置对话框中。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.26.0
: Added desc
property to definition object.v2.26.0
: 已将 desc
属性添加到定义对象中。name
: (string) Name of the settings
property to add, which the control will manage.name
: (字符串) 要添加的 settings
属性的名称,该控件将进行管理。definition
: (object) Definition of the setting and control.definition
: (对象) 设置和控件的定义。A list-type definition object should have some of the following properties:
一个列表类型定义对象应具有以下一些属性:
label
: (string) Label to use for the control.label
: (字符串)用于控件的标签。list
: (Array<string>) The array of members.list
: (Array) 成员数组。desc
: (optional, string) Description explaining the control in greater detail. May contain markup.desc
: (可选,string) 详细说明控制项的描述。可以包含标记。default
: (optional, [as list
array]) The default value for the setting and default state of the control. It should have the same value as one of the members of the list
array. Leaving it undefined means to use the first array member as the default.default
: (可选,[as list
array]) 设置的默认值和控制项的默认状态。它应该与 list
数组中的一个成员具有相同的值。留空表示使用数组中的第一个成员作为默认值。onInit
: (optional, function) The function to call during initialization. It is called with a result object as its sole parameter and, if possible, set as its this
.this
。onChange
: (optional, function) The function to call when the control's state is changed. It is called with a result object as its sole parameter and, if possible, set as its this
.onChange
: (可选,函数)当控件状态改变时调用的函数。它以结果对象作为唯一参数调用,并在可能的情况下将其设置为 this
。name
: (string) Name of the settings
property.name
: (字符串) settings
属性的名称。value
: ([as list
array]) The current value of the setting.value
: ([as list
array]) 设置的当前值。default
: ([as list
array]) The default value for the setting.default
: ([as list
数组]) 设置的默认值。list
: (Array<string>) The array of members.list
: (Array) 成员数组。// Setting up a basic list control for the settings property 'difficulty'
Setting.addList("difficulty", {
label : "Choose a difficulty level.",
list : ["Easy", "Normal", "Hard", "INSANE"],
default : "Normal"
});
// Setting up a list control for the settings property 'theme' w/ callbacks
var settingThemeNames = ["(none)", "Bright Lights", "Charcoal", "Midnight", "Tinsel City"];
var settingThemeHandler = function () {
// cache the jQuery-wrapped <html> element
var $html = $("html");
// remove any existing theme class
$html.removeClass("theme-bright-lights theme-charcoal theme-midnight theme-tinsel-city");
// switch on the theme name to add the requested theme class
switch (settings.theme) {
case "Bright Lights":
$html.addClass("theme-bright-lights");
break;
case "Charcoal":
$html.addClass("theme-charcoal");
break;
case "Midnight":
$html.addClass("theme-midnight");
break;
case "Tinsel City":
$html.addClass("theme-tinsel-city");
break;
}
};
Setting.addList("theme", {
label : "Choose a theme.",
list : settingThemeNames,
onInit : settingThemeHandler,
onChange : settingThemeHandler
}); // default value not defined, so the first array member "(none)" is used
Setting.addRange(name, definition)
Adds the named property to the settings
object and a range control for it to the Settings dialog.
添加指定的属性到 settings
对象,并在设置对话框中为其添加一个范围控制。
v2.26.0
: Introduced. v2.26.0
: 引入。name
: (string) Name of the settings
property to add, which the control will manage.name
: (字符串) 要添加的 settings
属性的名称,该控件将进行管理。definition
: (object) Definition of the setting and control.definition
: (对象) 设置和控件的定义。A range-type definition object should have some of the following properties:
一个范围类型定义对象应具有以下一些属性:
label
: (string) Label to use for the control.label
: (字符串) 用于控件的标签。max
: (number) The maximum value.max
: (数字) 最大值。min
: (number) The minimum value.min
: (数字) 最小值。step
: (number) Limits the increments to which the value may be set. It must be evenly divisible into the full range—i.e., max - min
.step
: (数字) 限制可以设置的值的增量。它必须能够整除整个范围——即, max - min
。desc
: (optional, string) Description explaining the control in greater detail. May contain markup.desc
: (可选,string) 详细说明控制项的描述。可以包含标记。default
: (optional, number) The default value for the setting and default state of the control. Leaving it undefined means to use the value of max
as the default.default
: (可选,数字)设置的默认值和控件默认状态。未定义则使用 max
的值作为默认值。onInit
: (optional, function) The function to call during initialization. It is called with a result object as its sole parameter and, if possible, set as its this
.this
。onChange
: (optional, function) The function to call when the control's state is changed. It is called with a result object as its sole parameter and, if possible, set as its this
.onChange
: (可选,函数)当控件状态改变时调用的函数。它以结果对象作为唯一参数调用,并在可能的情况下将其设置为 this
。name
: (string) Name of the settings
property.name
: (字符串) settings
属性的名称。value
: (number) The current value of the setting.value
: (数字)设置的当前值。default
: (number) The default value for the setting.default
: (数字)设置的默认值。max
: (number) The maximum value for the setting.max
: (数字)设置的 最大值。min
: (number) The minimum value for the setting.min
:(数字)设置的最小值。step
: (number) The step value for the setting.step
:(数字)设置的步进值。// Setting up a volume control for the settings property 'masterVolume' w/ callback
var settingMasterVolumeHandler = function () {
SimpleAudio.volume(settings.masterVolume / 10);
};
Setting.addRange("masterVolume", {
label : "Master volume.",
min : 0,
max : 10,
step : 1,
onInit : settingMasterVolumeHandler,
onChange : settingMasterVolumeHandler
}); // default value not defined, so max value (10) is used
Setting.addToggle(name, definition)
Adds the named property to the settings
object and a toggle control for it to the Settings dialog.
添加指定的属性到 settings
对象,并在设置对话框中为其添加一个切换控制。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.26.0
: Added desc
property to definition object.v2.26.0
: 已将 desc
属性添加到定义对象中。name
: (string) Name of the settings
property to add, which the control will manage.name
: (字符串) 要添加的 settings
属性的名称,该控件将进行管理。definition
: (object) Definition of the setting and control.definition
: (对象) 设置和控件的定义。A toggle-type definition object should have some of the following properties:
一个切换类型定义对象应具有以下一些属性:
label
: (string) Label to use for the control.label
: (字符串)用于控件的标签。desc
: (optional, string) Description explaining the control in greater detail. May contain markup.desc
: (可选,string) 详细说明控制项的描述。可以包含标记。default
: (optional, boolean) The default value for the setting and default state of the control. Leaving it undefined means to use false
as the default.default
:(可选,布尔值)设置的默认值和控制器的默认状态。留空不定义则使用 false
作为默认值。onInit
: (optional, function) The function to call during initialization. It is called with a result object as its sole parameter and, if possible, set as its this
.this
。onChange
: (optional, function) The function to call when the control's state is changed. It is called with a result object as its sole parameter and, if possible, set as its this
.onChange
: (可选,函数)当控件状态改变时调用的函数。它以结果对象作为唯一参数调用,并在可能的情况下将其设置为 this
。name
: (string) Name of the settings
property.name
: (字符串) settings
属性的名称。value
: (boolean) The current value of the setting.value
: (布尔) 设置的当前值。default
: (boolean) The default value for the setting.default
: (布尔) 设置的默认值。// Setting up a basic toggle control for the settings property 'mature'
Setting.addToggle("mature", {
label : "Content for mature audiences?"
}); // default value not defined, so false is used
// Setting up a toggle control for the settings property 'widescreen' w/ callbacks
var settingWidescreenHandler = function () {
if (settings.widescreen) { // is true
$("html").addClass("widescreen");
}
else { // is false
$("html").removeClass("widescreen");
}
};
Setting.addToggle("widescreen", {
label : "Allow the story to use the full width of your browser window?",
default : false,
onInit : settingWidescreenHandler,
onChange : settingWidescreenHandler
});
And the requisite CSS style rule:
所需 CSS 样式规则:
html.widescreen #passages {
max-width: none;
}
Setting.addValue(name [, definition])
Adds the named property to the settings
object.
将指定的属性添加到 settings
对象中。
Note:
Does not add a control to the Settings dialog.
注意:不会添加到设置对话框中的控件。
v2.37.0
: Introduced. v2.37.0
: 引入。name
: (string) Name of the settings
property to add.name
:(字符串) 要添加的 settings
属性的名称。definition
: (optional, object) Definition of the setting. May be omitted.definition
:(可选,对象) 设置的定义。可以省略。A value-type definition object should have some of the following properties:
一个值类型定义对象应具有以下一些属性:
default
: (optional, any) The default value for the setting.default
:(可选,任何)设置的默认值。onInit
: (optional, function) The function to call during initialization. It is called with a result object as its sole parameter and, if possible, set as its this
.this
。onChange
: (optional, function) The function to call when the control's state is changed. It is called with a result object as its sole parameter and, if possible, set as its this
.onChange
: (可选,函数)当控件状态改变时调用的函数。它以结果对象作为唯一参数调用,并在可能的情况下将其设置为 this
。name
: (string) Name of the settings
property.name
: (字符串) settings
属性的名称。value
: (any) The current value of the setting.value
: (任何) 设置的当前值。default
: (any) The default value for the setting.default
: (任何) 设置的默认值。Setting.addValue("someSetting");
Setting.addValue("anotherSetting", {
default : 42,
onInit : function () {
/* Do something when the setting is initialized. */
},
onChange : function () {
/* Do something when the setting is changed. */
}
});
Setting.getValue(name)
→ any
Returns the setting's current value.
返回设置的当前值。
Note:
Calling this method is equivalent to using settings[name]
.
注意:调用此方法与使用 settings[name]
等效。
v2.37.0
: Introduced. v2.37.0
: 引入。// Assume `disableAudio` is a toggle-type setting.
if (Setting.getValue("disableAudio")) {
/* Audio should be disabled. */
}
Setting.load()
Loads the settings from storage.
从存储中加载设置。
Note:
This method is automatically called during startup, so you should never need to call it manually.
注意:此方法在启动时会自动调用,因此您无需手动调用。
v2.0.0
: Introduced. v2.0.0
: 引入。Setting.load();
Setting.reset([name])
Resets the setting with the given name to its default value. If no name is given, resets all settings.
重置指定名称的设置为其默认值。如果没有指定名称,则重置所有设置。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (optional, string) Name of the settings
object property to reset.name
:(可选,字符串)重置 settings
对象属性的名称。// Reset the setting 'difficulty'
Setting.reset("difficulty");
// Reset all settings
Setting.reset();
Setting.save()
Saves the settings to storage.
保存设置到存储。
Note:
The controls of the Settings dialog and the Setting.setValue()
method automatically call this method when settings are changed, so you should normally never need to call this method manually. Only when directly modifying the values of settings
object properties, outside of the controls or Setting.setValue()
method, would you need to call this method.
注意:设置对话框的控件和 Setting.setValue()
方法在设置更改时自动调用此方法,因此您通常不需要手动调用此方法。只有在直接修改控件或 Setting.setValue()
方法之外的 settings
对象属性值时,您才需要调用此方法。
v2.0.0
: Introduced. v2.0.0
: 引入。Setting.save();
Setting.setValue(name, value)
Sets the setting's value.
设置设置的值。
Note:
This method automatically calls the Setting.save()
method.
注意:此方法会自动调用 Setting.save()
方法。
Warning:
If manually changing a setting that has an associated control, be mindful that the value you set makes sense for the setting in question, elsewise shenanigans could occur—e.g., don't set a range-type setting to non-number or out-of-range values.
警告:如果手动更改与控件关联的设置,请注意您设置的值对于该设置是有意义的,否则可能会出现麻烦——例如,不要将范围类型的设置设置为非数字或超出范围的值。
v2.37.0
: Introduced. v2.37.0
: 引入。name
: (string) Name of the settings
property.name
: (字符串) settings
属性的名称。value
: (any) The new value for the setting.value
:(任何) 设置的新值。Setting.setValue("theme", "dark");
settings
object 对象A prototype-less generic object whose properties and values are defined by the Setting.addList()
, Setting.addRange()
, Setting.addToggle()
, and Setting.addValue()
methods.
一个无原型的通用对象,其属性和值由 Setting.addList()
、 Setting.addRange()
、 Setting.addToggle()
和 Setting.addValue()
方法定义。
For all types of setting types except value-types, the values of its properties are automatically managed by the Settings dialog controls. If necessary, you may manually change setting values via the Setting.setValue()
method.
对于所有非值类型的设置类型,其属性的值将由设置对话框控件自动管理。如有必要,您可以通过 Setting.setValue()
方法手动更改设置值。
Note:
You may also manually change setting values by assigning directly to the associated property—e.g., settings["mode"] = "day"
. Doing so, however, does not automatically save any values so updated, thus you must manually call the Setting.save()
method afterwards.
注意:您还可以通过直接分配给相关属性来手动更改设置值——例如, settings["mode"] = "day"
。但是,这样做并不会自动保存更新的任何值,因此您必须在之后手动调用 Setting.save()
方法。
Warning:
If manually changing a setting that has an associated control, be mindful that the value you set makes sense for the setting in question, elsewise shenanigans could occur—e.g., don't set a range-type setting to non-number or out-of-range values.
警告:如果手动更改与控制关联的设置,请注意您设置的值对于该设置是有意义的,否则可能会出现麻烦——例如,不要将范围类型的设置设置为非数字或超出范围的值。
v2.0.0
: Introduced. v2.0.0
: 引入。SimpleAudio
API The core audio subsystem and backend for the audio macros.
核心音频子系统和音频宏的后端。
See Also:
AudioTrack
API, AudioRunner
API, and AudioList
API.
相关链接: AudioTrack
API、 AudioRunner
API 和 AudioList
API。
The audio subsystem is based upon the HTML Media Elements APIs and comes with some built-in limitations:
音频子系统基于 HTML 媒体元素 API,并自带一些内置限制:
<<timed>>
—though this ultimately depends on various factors. A simple solution for the former is to use some kind of click/touch-through screen—e.g., a splash screen, which the player goes through to the real starting passage. The latter is harder to resolve, so is best avoided.<<timed>>
——也不太可能播放——尽管这最终取决于各种因素。对于前者,一个简单的解决方案是使用某种点击/触摸穿透屏幕——例如,一个启动画面,玩家通过它进入真正的起始段落。后者更难解决,因此最好避免。SimpleAudio.load()
Pauses playback of all currently registered tracks and, if they're not already in the process of loading, force them to drop any existing data and begin loading.
暂停所有已注册轨道的播放,并且如果它们尚未开始加载,则强制它们丢弃任何现有数据并开始加载。
Warning:
This should not be done lightly if your audio sources are on the network, as it forces players to begin downloading them.
警告:如果您的音频源在网络上,则不应轻率地进行此操作,因为它会强制播放器开始下载它们。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.load();
SimpleAudio.loadWithScreen()
Displays the loading screen until all currently registered audio tracks have either loaded to a playable state or aborted loading due to errors. The loading process is as described in SimpleAudio.load()
.
显示加载界面,直到所有当前注册的音频轨道都已加载到可播放状态或由于错误而中止加载。加载过程如 SimpleAudio.load()
所述。
Warning:
This should not be done lightly if your audio sources are on the network, as it forces players to begin downloading them.
警告:如果您的音频源在网络上,则不应轻率地进行此操作,因为它会强制播放器开始下载它们。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.loadWithScreen();
SimpleAudio.mute([state])
→ get: boolean | set: undefinedSimpleAudio.mute([state])
→ 获取: 布尔值 | 设置: 未定义 Gets or sets the mute state for the master volume (default: false
).
获取或设置主音量的静音状态(默认: false
)。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The mute state.state
: (可选,布尔值)静音状态。// Get the current master volume mute state.
var isMuted = SimpleAudio.mute();
// Mute the master volume.
SimpleAudio.mute(true);
// Unmute the master volume.
SimpleAudio.mute(false);
SimpleAudio.muteOnHidden([state])
→ get: boolean | set: undefinedSimpleAudio.muteOnHidden([state])
→ 获取: 布尔值 | 设置: 未定义 Gets or sets the mute-on-hidden state for the master volume (default: false
). The mute-on-hidden state controls whether the master volume is automatically muted/unmuted when the story's browser tab loses/gains visibility. Loss of visibility is defined as when the browser window is either switched to another tab or minimized.
获取或设置主音量的静音状态(默认: false
)。静音状态控制当故事浏览器的标签页失去/获得可见性时,主音量是否自动静音/取消静音。失去可见性定义为当浏览器窗口切换到另一个标签页或最小化时。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The mute-on-hidden state.state
:(可选,布尔值)隐藏时静音状态。// Get the current master volume mute-on-hidden state.
var isMuteOnHidden = SimpleAudio.muteOnHidden();
// Enable automatic muting of the master volume when visibility is lost.
SimpleAudio.muteOnHidden(true);
// Disable automatic muting of the master volume when visibility is lost.
SimpleAudio.muteOnHidden(false);
SimpleAudio.select(selector)
→ AudioRunner
object SimpleAudio.select(selector)
→ AudioRunner
对象 Returns an AudioRunner
instance for the tracks matching the given selector.
返回与给定选择器匹配的轨道的 AudioRunner
实例。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.37.0
: Added :stopped
predefined group ID.v2.37.0
: 添加了 :stopped
预定义组 ID。selector
: (string) The list of audio track(s) and/or group ID(s), separated by spaces. There are several predefined group IDs (:all
, :looped
, :muted
, :paused
, :playing
, :stopped
). The :not()
group modifier syntax (groupId:not(selector)
) allows a group to have some of its tracks excluded from selection.:all
, :looped
, :muted
, :paused
, :playing
, :stopped
)。 :not()
组修饰符语法( groupId:not(selector)
)允许将某些音轨从选择中排除。SimpleAudio.select(":ui") → Returns the AudioRunner instance for the tracks matching ":ui"
// Return the AudioTrack instance matching "swamped" and do something with it
SimpleAudio.select("swamped").volume(1).play();
// Start playback of paused audio tracks
SimpleAudio.select(":paused").play();
// Pause playback of playing audio tracks
SimpleAudio.select(":playing").pause();
// Stop playback of playing audio tracks
SimpleAudio.select(":playing").stop();
// Stop playback of all audio tracks (not uniquely part of a playlist)
SimpleAudio.select(":all").stop();
// Stop playback of playing audio tracks except those in the ":ui" group
SimpleAudio.select(":playing:not(:ui)").stop();
// Change the volume of all audio tracks except those in the ":ui" group
// to 40%, without changing the current playback state
SimpleAudio.select(":all:not(:ui)").volume(0.40);
SimpleAudio.stop()
Stops playback of all currently registered tracks.
停止播放所有当前注册的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.stop();
SimpleAudio.unload()
Stops playback of all currently registered tracks and force them to drop any existing data.
停止播放所有当前注册的曲目并强制它们丢弃任何现有数据。
Note:
Once a track has been unloaded, playback cannot occur until it is reloaded.
注意:一旦轨道被卸载,除非重新加载,否则无法播放。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.unload();
SimpleAudio.volume([level])
→ get: number | set: undefinedSimpleAudio.volume([level])
→ 获取: 数字 | 设置: 未定义 Gets or sets the master volume level (default: 1
).
获取或设置主音量级别(默认: 1
)。
v2.28.0
: Introduced. v2.28.0
: 引入。level
: (optional, number) The volume level to set. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.level
:(可选,数字)要设置的音量级别。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。// Get the current master volume level.
var currentMasterVolume = SimpleAudio.volume();
// Set the master volume level to 75%.
SimpleAudio.volume(0.75);
SimpleAudio.tracks.add(trackId, sources…)
Adds an audio track with the given track ID.
添加一个指定 ID 的音频轨道。
v2.28.0
: Introduced. v2.28.0
: 引入。trackId
: (string) The ID of the track, which will be used to reference it.trackId
: (字符串) 轨道的 ID,用于引用。sources
: (string… | Array<string>) The audio sources for the track, which may be a list of sources or an array. Only one is required, though supplying additional sources in differing formats is recommended, as no single format is supported by all browsers. A source must be either a URL (absolute or relative) to an audio resource, the name of an audio passage, or a data URI. In rare cases where the audio format cannot be automatically detected from the source (URLs are parsed for a file extension, data URIs are parsed for the media type), a format specifier may be prepended to the front of each source to manually specify the format (syntax: formatId|
, where formatId
is the audio format—generally, whatever the file extension would normally be; e.g., mp3
, mp4
, ogg
, weba
, wav
).sources
: (字符串… | 数组) 轨道的音频源,可能是一个源列表或数组。虽然只需要一个源,但推荐提供不同格式的额外源,因为没有任何单一格式被所有浏览器支持。源必须是一个指向音频资源的 URL(绝对或相对)、音频段落的名称,或数据 URI。在极少数情况下,无法从源(URL 解析文件扩展名,数据 URI 解析媒体类型)自动检测音频格式时,可以在每个源前添加格式指定符以手动指定格式(语法: formatId|
,其中 formatId
是音频格式——通常是文件扩展名;例如: mp3
, mp4
, ogg
, weba
, wav
)。// Cache a track with the ID "boom" and one source via relative URL
SimpleAudio.tracks.add("boom", "media/audio/explosion.mp3");
// Cache a track with the ID "boom" and one source via audio passage
SimpleAudio.tracks.add("boom", "explosion");
// Cache a track with the ID "bgm_space" and two sources via relative URLs
SimpleAudio.tracks.add("bgm_space", "media/audio/space_quest.mp3", "media/audio/space_quest.ogg");
// Cache a track with the ID "what" and one source via URL with a format specifier
SimpleAudio.tracks.add("what", "mp3|http://an-audio-service.com/a-user/a-track-id");
SimpleAudio.tracks.clear()
Deletes all audio tracks.
删除所有音频轨道。
Note:
Cannot delete tracks solely under the control of a playlist.
注意:不能仅删除由播放列表控制的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.tracks.clear();
SimpleAudio.tracks.delete(trackId)
Deletes the audio track with the given track ID.
删除具有给定曲目 ID 的音频轨道。
Note:
Cannot delete tracks solely under the control of a playlist.
注意:不能仅通过播放列表控制删除曲目。
Warning:
Does not currently remove the track from either groups or playlists. Thus, any groups or playlists containing the deleted track should be rebuilt.
警告:目前无法从任何组或播放列表中删除曲目。因此,包含已删除曲目的任何组或播放列表都需要重新构建。
v2.28.0
: Introduced. v2.28.0
: 引入。trackId
: (string) The ID of the track.trackId
: (字符串) 轨迹的 ID。SimpleAudio.tracks.delete("bgm_space");
SimpleAudio.tracks.get(trackId)
→ AudioTrack
object | nullSimpleAudio.tracks.get(trackId)
→ AudioTrack
对象 | null Returns the AudioTrack
instance with the given track ID, or null
on failure.
返回具有给定轨道 ID 的 AudioTrack
实例,或在失败时返回 null
。
Note:
To affect multiple tracks and/or groups at once, see the SimpleAudio.select()
method.
注意:要同时影响多个轨道和/或组,请参阅 SimpleAudio.select()
方法。
v2.28.0
: Introduced. v2.28.0
: 引入。trackId
: (string) The ID of the track.trackId
:(字符串) 轨道的 ID。SimpleAudio.tracks.get("swamped") → Returns the AudioTrack instance matching "swamped"
// Return the AudioTrack instance matching "swamped" and do something with it
SimpleAudio.tracks.get("swamped").volume(1).play();
SimpleAudio.tracks.has(trackId)
→ boolean SimpleAudio.tracks.has(trackId)
→ 布尔值 Returns whether an audio track with the given track ID exists.
返回是否存在给定音轨 ID 的音频轨道。
v2.28.0
: Introduced. v2.28.0
: 引入。trackId
: (string) The ID of the track.trackId
: (字符串) 轨道 ID。if (SimpleAudio.tracks.has("bgm_space")) {
// Track "bgm_space" exists.
}
SimpleAudio.groups.add(groupId, trackIds…)
Adds an audio group with the given group ID. Groups are useful for applying actions to multiple tracks simultaneously and/or excluding the included tracks from a larger set when applying actions.
添加具有指定组 ID 的音频组。组可用于同时应用操作到多个轨道,或当应用操作时,从更大的集合中排除包含的轨道。
Note:
If you want to play tracks in a sequence, then you want a playlist instead.
注意:如果您想按顺序播放曲目,那么您需要一个播放列表。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.37.0
: Added :stopped
predefined group ID.v2.37.0
: 添加了 :stopped
预定义组 ID。groupId
: (string) The ID of the group, which will be used to reference it and must begin with a colon. NOTE: There are several predefined group IDs (:all
, :looped
, :muted
, :paused
, :playing
, :stopped
) and the :not
group modifier that cannot be reused/overwritten.groupId
: (字符串) 分组的 ID,用于引用它,必须以冒号开头。注意:有几个预定义的分组 ID( :all
、 :looped
、 :muted
、 :paused
、 :playing
、 :stopped
)以及 :not
分组修饰符,不能被重新使用/覆盖。trackIds
: (string… | Array<string>) The IDs of the tracks to make part of the group, which may be a list of track IDs or an array.// Set up a group ":ui" with the tracks: "ui_beep", "ui_boop", and "ui_swish"
SimpleAudio.groups.add(":ui", "ui_beep", "ui_boop", "ui_swish");
SimpleAudio.groups.clear()
Deletes all audio groups.
删除所有音频组。
Note:
Only deletes the groups themselves, does not affect their component tracks.
注意:仅删除组本身,不影响其组成轨道。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.groups.clear();
SimpleAudio.groups.delete(groupId)
Deletes the audio group with the given group ID.
删除具有给定组 ID 的音频组。
Note:
Only deletes the group itself, does not affect its component tracks.
注意:仅删除组本身,不影响其组件轨道。
v2.28.0
: Introduced. v2.28.0
: 引入。groupId
: (string) The ID of the group.groupId
: (字符串) 组的 ID。SimpleAudio.groups.delete(":ui");
SimpleAudio.groups.get(groupId)
→ Array<string> | null Returns the array of track IDs with the given group ID, or null
on failure.
返回具有给定组 ID 的轨道 ID 数组,或在失败时返回 null
。
Note:
To actually affect multiple tracks and/or groups, see the SimpleAudio.select()
method.
注意:要实际影响多个轨道和/或组,请参阅 SimpleAudio.select()
方法。
v2.28.0
: Introduced. v2.28.0
: 引入。groupId
: (string) The ID of the group.groupId
: (string) 组的 ID。SimpleAudio.groups.get(":ui") → Returns the array of track IDs matching ":ui"
SimpleAudio.groups.has(groupId)
→ boolean SimpleAudio.groups.has(groupId)
→ 布尔值 Returns whether an audio group with the given group ID exists.
返回是否存在具有给定组 ID 的音频组。
v2.28.0
: Introduced. v2.28.0
: 引入。groupId
: (string) The ID of the group.groupId
: (字符串) 组的 ID。if (SimpleAudio.groups.has(":ui")) {
// Group ":ui" exists.
}
SimpleAudio.lists.add(listId, sources…)
Adds a playlist with the given list ID. Playlists are useful for playing tracks in a sequence—i.e., one after another.
添加具有给定列表 ID 的播放列表。播放列表用于按顺序播放曲目——即一个接一个。
Note:
If you simply want to apply actions to multiple tracks simultaneously, then you want a group instead.
注意:如果您只想同时应用操作到多个曲目,那么您需要一个组。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Changed descriptor object copy
property to own
.v2.29.0
: 将描述符对象 copy
属性更改为 own
。listId
: (string) The ID of the list, which will be used to reference it.listId
: (字符串) 列表的 ID,将用于引用它。sources
: (string | object | Array<string | object>) The track IDs or descriptors of the tracks to make part of the list, which may be specified as a list or an array.Track descriptor objects come in two forms and should have some of the noted properties:
轨迹描述符对象有两种形式,应具有以下一些属性:
{ id, [own], [volume] }
现有轨迹形式: { id, [own], [volume] }
id
: (string) The ID of an existing track.id
:(字符串) 现有轨迹的 ID。own
: (optional, boolean) When true
, signifies that the playlist should create its own independent copy of the track, rather than simply referencing the existing instance. Owned copies are solely under the control of their playlist and cannot be selected with either the SimpleAudio.tracks.get()
method or the SimpleAudio.select()
method.own
:(可选,布尔值)当 true
时,表示播放列表应创建其自己的独立副本,而不是简单地引用现有实例。拥有副本仅受其播放列表的控制,无法使用 SimpleAudio.tracks.get()
方法或 SimpleAudio.select()
方法进行选择。volume
: (optional, number) The base volume level of the track within the playlist. If omitted, defaults to the track's current volume. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.volume
:(可选,数字)该曲目在播放列表中的基本音量级别。如果省略,则默认为曲目的当前音量。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。{ sources, [volume] }
新曲目表单: { sources, [volume] }
sources
: (Array<string>) The audio sources for the track. Only one is required, though supplying additional sources in differing formats is recommended, as no single format is supported by all browsers. A source must be either a URL (absolute or relative) to an audio resource, the name of an audio passage, or a data URI. In rare cases where the audio format cannot be automatically detected from the source (URLs are parsed for a file extension, data URIs are parsed for the media type), a format specifier may be prepended to the front of each source to manually specify the format (syntax: formatId|
, where formatId
is the audio format—generally, whatever the file extension would normally be; e.g., mp3
, mp4
, ogg
, weba
, wav
).sources
:(字符串数组)该曲目的音频源。虽然只需要一个,但推荐提供不同格式的额外源,因为没有任何格式被所有浏览器支持。一个源必须是音频资源的 URL(绝对或相对)、音频段落的名称或数据 URI。在极少数情况下,无法从源(URL 解析文件扩展名,数据 URI 解析媒体类型)自动检测音频格式时,可以在每个源前添加格式指定符以手动指定格式(语法: formatId|
,其中 formatId
是音频格式——通常是文件扩展名;例如, mp3
, mp4
, ogg
, weba
, wav
)。volume
: (optional, number) The base volume level of the track within the playlist. If omitted, defaults to 1
(loudest). Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.1
(最响)。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。// Add existing tracks at their current volumes
SimpleAudio.lists.add("bgm_lacuna", "swamped", "heavens_a_lie", "closer", "to_the_edge");
SimpleAudio.lists.add("bgm_lacuna",
// Add existing track "swamped" at its current volume
"swamped",
// Add existing track "heavens_a_lie" at 50% volume
{
id : "heavens_a_lie",
volume : 0.5
},
// Add an owned copy of existing track "closer" at its current volume
{
id : "closer",
own : true
},
// Add an owned copy of existing track "to_the_edge" at 100% volume
{
id : "to_the_edge",
own : true,
volume : 1
}
);
SimpleAudio.lists.add("bgm_lacuna",
// Add a track from the given sources at the default volume (100%)
{
sources : ["media/audio/Swamped.mp3"]
}
// Add a track from the given sources at 50% volume
{
sources : ["media/audio/Heaven's_A_Lie.mp3"],
volume : 0.5
},
// Add a track from the given sources at the default volume (100%)
{
sources : ["media/audio/Closer.mp3"]
},
// Add a track from the given sources at 100% volume
{
sources : ["media/audio/To_The_Edge.mp3"],
volume : 1
}
);
SimpleAudio.lists.clear()
Deletes all playlists. 删除所有播放列表。
v2.28.0
: Introduced. v2.28.0
: 引入。SimpleAudio.lists.clear();
SimpleAudio.lists.delete(listId)
Deletes the playlist with the given list ID.
删除具有给定列表 ID 的播放列表。
v2.28.0
: Introduced. v2.28.0
: 引入。listId
: (string) The ID of the playlist.listId
: (字符串) 播放列表的 ID。SimpleAudio.lists.delete("bgm_lacuna");
SimpleAudio.lists.get(listId)
→ AudioList
object | nullSimpleAudio.lists.get(listId)
→ AudioList
对象 | null Returns the AudioList
instance with the given list ID, or null
on failure.
返回具有给定列表 ID 的 AudioList
实例,或失败时返回 null
。
v2.28.0
: Introduced. v2.28.0
: 引入。listId
: (string) The ID of the playlist.listId
: (字符串) 播放列表的 ID。SimpleAudio.lists.get("bgm_lacuna") → Returns the AudioList instance matching "bgm_lacuna"
// Return the AudioList instance matching "bgm_lacuna" and do something with it
SimpleAudio.lists.get("bgm_lacuna").volume(1).loop(true).play();
SimpleAudio.lists.has(listId)
→ boolean SimpleAudio.lists.has(listId)
→ 布尔值 Returns whether a playlist with the given list ID exists.
返回给定列表 ID 的播放列表是否存在。
v2.28.0
: Introduced. v2.28.0
: 引入。listId
: (string) The ID of the playlist.listId
: (字符串)播放列表的 ID。if (SimpleAudio.lists.has("bgm_lacuna")) {
// Playlist "bgm_lacuna" exists.
}
AudioTrack
API Audio tracks encapsulate and provide a consistent interface to an audio resource.
音轨封装并提供对音频资源的统一接口。
See Also:
SimpleAudio
API, AudioRunner
API, and AudioList
API.
相关链接: SimpleAudio
API、 AudioRunner
API 和 AudioList
API。
<AudioTrack>.clone()
→ AudioTrack
object <AudioTrack>.clone()
→ AudioTrack
对象 Returns a new independent copy of the track.
返回轨道的新独立副本。
v2.28.0
: Introduced. v2.28.0
: 引入。var trackCopy = aTrack.clone();
<AudioTrack>.duration()
→ number <AudioTrack>.duration()
→ 数字 Returns the track's total playtime in seconds, Infinity
for a stream, or NaN
if no metadata exists.
返回该曲目总播放时间(以秒为单位),对于流媒体为 Infinity
,如果不存在元数据则为 NaN
。
v2.28.0
: Introduced. v2.28.0
: 引入。var trackLength = aTrack.duration();
<AudioTrack>.fade(duration , toVol [, fromVol])
→ Promise
object <AudioTrack>.fade(duration , toVol [, fromVol])
→ Promise
对象 Starts playback of the track and fades it between the specified starting and destination volume levels over the specified number of seconds.
开始播放曲目,并在指定的起始和目标音量级别之间,在指定的时间内淡入淡出。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)决定音频子系统是否自动暂停淡入到 0
音量(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。duration
: (number) The number of seconds over which the track should be faded.duration
:(数字)曲目淡入所需的时间(秒)。toVol
: (number) The destination volume level.toVol
:(数字)目标音量级别。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the track's current volume level.fromVol
:(可选,数字)起始音量级别。如果省略,则默认为当前音轨的音量级别。// Fade the track from volume 0 to 1 over 6 seconds.
aTrack.fade(6, 1, 0);
<AudioTrack>.fadeIn(duration [, fromVol])
→ Promise
object <AudioTrack>.fadeIn(duration [, fromVol])
→ Promise
对象 Starts playback of the track and fades it from the specified volume level to 1
(loudest) over the specified number of seconds.
开始播放曲目,并在指定秒数内从指定音量级别渐变到 1
(最响)。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Updated to return a Promise
.v2.29.0
: 更新为返回一个 Promise
。duration
: (number) The number of seconds over which the track should be faded.duration
: (数字) 轨道应该淡入的秒数。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the track's current volume level.fromVol
: (可选,数字) 开始的音量级别。如果省略,则默认为轨道当前的音量级别。// Fade the track in from volume 0 over 5 seconds.
aTrack.fadeIn(5, 0);
<AudioTrack>.fadeOut(duration [, fromVol])
→ Promise
object <AudioTrack>.fadeOut(duration [, fromVol])
→ Promise
对象 Starts playback of the track and fades it from the specified volume level to 0
(silent) over the specified number of seconds.
开始播放曲目,并在指定秒数内从指定音量级别渐变到 0
(静音)。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)决定是否自动暂停渐变到 0
音量(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Updated to return a Promise
.v2.29.0
:更新为返回 Promise
。duration
: (number) The number of seconds over which the track should be faded.duration
:(数字)曲目应渐变的秒数。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the track's current volume level.fromVol
:(可选,数字)起始音量级别。如果省略,则默认为当前音轨的音量级别。// Fade the track out from volume 1 over 8 seconds.
aTrack.fadeOut(8, 1);
<AudioTrack>.fadeStop()
Interrupts an in-progress fade of the track, or does nothing if no fade is progressing.
中断正在进行的音轨淡入,如果没有淡入正在进行,则不执行任何操作。
Note:
This does not alter the volume level.
注意:这不会改变音量级别。
v2.28.0
: Introduced. v2.28.0
: 引入。aTrack.fadeStop();
<AudioTrack>.hasData()
→ boolean <AudioTrack>.hasData()
→ 布尔值 Returns whether enough data has been loaded to play the track through to the end without interruption.
返回是否有足够的数据已加载,可以无间断地播放曲目至结束。
Note:
This is an estimate calculated by the browser based upon the currently downloaded data and the download rate.
注意:这是浏览器根据当前已下载的数据和下载速率计算出的估计值。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.hasData()) {
/* do something */
}
<AudioTrack>.hasMetadata()
→ boolean <AudioTrack>.hasMetadata()
→ 布尔值 Returns whether, at least, the track's metadata has been loaded.
返回是否至少已加载轨道的元数据。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.hasMetadata()) {
/* do something */
}
<AudioTrack>.hasNoData()
→ boolean <AudioTrack>.hasNoData()
→ 布尔值 Returns whether none of the track's data has been loaded.
返回是否没有加载任何音轨数据。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.hasNoData()) {
/* do something */
}
<AudioTrack>.hasSomeData()
→ boolean <AudioTrack>.hasSomeData()
→ 布尔值 Returns whether, at least, some of the track's data has been loaded.
返回是否至少已加载部分轨道数据。
Tip:
The <AudioTrack>.hasData()
method is generally more useful.
提示:通常 <AudioTrack>.hasData()
方法更有用。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.hasSomeData()) {
/* do something */
}
<AudioTrack>.hasSource()
→ boolean <AudioTrack>.hasSource()
→ 布尔值 Returns whether any valid sources were registered.
返回是否有已注册的有效来源。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.hasSource()) {
/* do something */
}
<AudioTrack>.isEnded()
→ boolean <AudioTrack>.isEnded()
→ 布尔值 Returns whether playback of the track has ended.
返回是否已结束播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isEnded()) {
/* do something */
}
<AudioTrack>.isFading()
→ boolean <AudioTrack>.isFading()
→ 布尔值 Returns whether a fade is in-progress on the track.
返回该轨道上是否正在执行淡入/淡出操作。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isFading()) {
/* do something */
}
<AudioTrack>.isFailed()
→ boolean <AudioTrack>.isFailed()
→ 布尔值 Returns whether an error has occurred.
返回是否发生了错误。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isFailed()) {
/* do something */
}
<AudioTrack>.isLoading()
→ boolean <AudioTrack>.isLoading()
→ 布尔值 Returns whether the track is loading data.
返回是否正在加载数据。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isLoading()) {
/* do something */
}
<AudioTrack>.isPaused()
→ boolean <AudioTrack>.isPaused()
→ 布尔值 Returns whether playback of the track has been paused.
返回是否已暂停播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isPaused()) {
/* do something */
}
<AudioTrack>.isPlaying()
→ boolean <AudioTrack>.isPlaying()
→ 布尔值 Returns whether the track is playing.
返回是否正在播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isPlaying()) {
/* do something */
}
<AudioTrack>.isSeeking()
→ boolean <AudioTrack>.isSeeking()
→ 布尔值 Returns whether the track is seeking.
返回是否正在搜索。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isSeeking()) {
/* do something */
}
<AudioTrack>.isStopped()
→ boolean <AudioTrack>.isStopped()
→ 布尔值 Returns whether playback of the track has been stopped.
返回是否已停止播放曲目。
v2.29.0
: Introduced. v2.29.0
: 引入。if (aTrack.isStopped()) {
/* do something */
}
<AudioTrack>.isUnavailable()
→ boolean <AudioTrack>.isUnavailable()
→ 布尔值 Returns whether the track is currently unavailable for playback. Possible reasons include: no valid sources are registered, no sources are currently loaded, an error has occurred.
返回是否当前无法播放轨道。可能的原因包括:未注册有效源,当前未加载源,发生错误。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isUnavailable()) {
/* do something */
}
<AudioTrack>.isUnloaded()
→ boolean <AudioTrack>.isUnloaded()
→ 布尔值 Returns whether the track's sources are currently unloaded.
返回轨道的源是否当前未加载。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aTrack.isUnloaded()) {
/* do something */
}
<AudioTrack>.load()
Pauses playback of the track and, if it's not already in the process of loading, forces it to drop any existing data and begin loading.
暂停轨道的播放,如果它尚未在加载过程中,则强制它丢弃任何现有数据并开始加载。
Warning:
This should not be done lightly if your audio sources are on the network, as it forces players to begin downloading them.
警告:如果您的音频源在网络上,则不应轻率地进行此操作,因为它会强制播放器开始下载它们。
v2.28.0
: Introduced. v2.28.0
: 引入。aTrack.load();
<AudioTrack>.loop([state])
→ get: boolean | set: AudioTrack
object<AudioTrack>.loop([state])
→ 获取:布尔值 | 设置: AudioTrack
对象 Gets or sets the track's repeating playback state (default: false
). When used to set the loop state, returns a reference to the current AudioTrack
instance for chaining.
获取或设置音轨的重复播放状态(默认: false
)。当用于设置循环状态时,返回当前 AudioTrack
实例的引用以实现链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The loop state.state
: (可选,布尔值)循环状态。// Get the track's current loop state.
var isLooped = aTrack.loop();
// Loop the track.
aTrack.loop(true);
// Unloop the track.
aTrack.loop(false);
<AudioTrack>.mute([state])
→ get: boolean | set: AudioTrack
object Gets or sets the track's volume mute state (default: false
). When used to set the mute state, returns a reference to the current AudioTrack
instance for chaining.
获取或设置音轨的静音状态(默认: false
)。当用于设置静音状态时,返回当前 AudioTrack
实例的引用以实现链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The mute state.state
:(可选,布尔值)静音状态。// 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);
<AudioTrack>.off(...args)
→ AudioTrack
object <AudioTrack>.off(...args)
→ AudioTrack
对象 Removes event handlers from the track. Returns a reference to the current AudioTrack
instance for chaining.
移除跟踪的事件处理器。返回当前 AudioTrack
实例的引用以实现链式调用。
Note:
Shorthand for jQuery's .off()
method applied to the audio element.
注意:这是对 jQuery 的 .off()
方法的简写,应用于音频元素。
Warning:
The SimpleAudio
APIs use events internally for various pieces of functionality. To prevent conflicts, it is strongly suggested that you specify a custom user namespace—e.g., .myEvents
—when attaching your own handlers. It is further strongly suggested that you provide that same custom user namespace when removing them.
警告: SimpleAudio
API 在内部使用事件来实现各种功能。为了避免冲突,强烈建议您在附加自己的处理器时指定自定义用户命名空间——例如, .myEvents
。同样强烈建议在移除它们时提供相同的自定义用户命名空间。
v2.28.0
: Introduced. v2.28.0
: 引入。See:
<jQuery>.off()
in the jQuery API docs for more information.
查看 jQuery API 文档中的 <jQuery>.off()
以获取更多信息。
// Remove any handlers for the ended event.
aTrack.off('ended.myEvents');
<AudioTrack>.on(...args)
→ AudioTrack
object <AudioTrack>.on(...args)
→ AudioTrack
对象 Attaches event handlers to the track. Returns a reference to the current AudioTrack
instance for chaining.
将事件处理器附加到轨道上。返回当前 AudioTrack
实例的引用以实现链式调用。
Note:
Shorthand for jQuery's .on()
method applied to the audio element.
注意:这是对 jQuery 的 .on()
方法的简写,应用于音频元素。
Warning:
The SimpleAudio
APIs use events internally for various pieces of functionality. To prevent conflicts, it is strongly suggested that you specify a custom user namespace—e.g., .myEvents
—when attaching your own handlers. It is further strongly suggested that you provide that same custom user namespace when removing them.
警告: SimpleAudio
API 在内部使用事件来实现各种功能。为了避免冲突,强烈建议您在附加自己的处理器时指定自定义用户命名空间——例如, .myEvents
。同样,在移除它们时也强烈建议您提供相同的自定义用户命名空间。
v2.28.0
: Introduced. v2.28.0
: 引入。See:
<jQuery>.on()
in the jQuery API docs for more information.
查看:在 jQuery API 文档中查看 <jQuery>.on()
以获取更多信息。
// Add a handler for the ended event.
aTrack.on('ended.myEvents', function () {
/* do something */
});
<AudioTrack>.one(...args)
→ AudioTrack
object <AudioTrack>.one(...args)
→ AudioTrack
对象 Attaches single-use event handlers to the track. Returns a reference to the current AudioTrack
instance for chaining.
为轨道附加单次使用的事件处理器。返回当前 AudioTrack
实例的引用以进行链式调用。
Note:
Shorthand for jQuery's .one()
method applied to the audio element.
注意:jQuery 的 .one()
方法的简写,应用于音频元素。
Warning:
The SimpleAudio
APIs use events internally for various pieces of functionality. To prevent conflicts, it is strongly suggested that you specify a custom user namespace—e.g., .myEvents
—when attaching your own handlers. It is further strongly suggested that you provide that same custom user namespace when removing them.
警告: SimpleAudio
API 内部使用事件来实现各种功能。为了避免冲突,强烈建议您在附加自己的处理程序时指定一个自定义用户命名空间——例如, .myEvents
。同样,在移除它们时也强烈建议您提供相同的自定义用户命名空间。
v2.28.0
: Introduced. v2.28.0
: 引入。See:
<jQuery>.one()
in the jQuery API docs for more information.
查看 jQuery API 文档中的 <jQuery>.one()
以获取更多信息。
// Add a single-use handler for the ended event.
aTrack.one('ended.myEvents', function () {
/* do something */
});
<AudioTrack>.pause()
Pauses playback of the track.
暂停播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。aTrack.pause();
<AudioTrack>.play()
→ Promise
object <AudioTrack>.play()
→ Promise
对象 Begins playback of the track.
开始播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。aTrack.play();
Promise
使用返回的 Promise
aTrack.play()
.then(function () {
console.log('The track is playing.');
})
.catch(function (problem) {
console.warn('There was a problem with playback: ' + problem);
});
<AudioTrack>.playWhenAllowed()
Begins playback of the track or, failing that, sets the track to begin playback as soon as the player has interacted with the document.
开始播放曲目或,如果失败,则在播放器与文档交互后立即开始播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。aTrack.playWhenAllowed();
<AudioTrack>.remaining()
→ number <AudioTrack>.remaining()
→ 数字 Returns how much remains of the track's total playtime in seconds, Infinity
for a stream, or NaN
if no metadata exists.
返回轨道总播放时间剩余秒数,对于流媒体为 Infinity
,如果不存在元数据则为 NaN
。
v2.28.0
: Introduced. v2.28.0
: 引入。var trackRemains = aTrack.remaining();
<AudioTrack>.stop()
Stops playback of the track.
停止播放曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。someTrack.stop();
<AudioTrack>.time([seconds])
→ get: number | set: AudioTrack
object<AudioTrack>.time([seconds])
→ 获取:数字 | 设置: AudioTrack
对象 Gets or sets the track's current time in seconds. When used to set a value, returns a reference to the current AudioTrack
instance for chaining.
获取或设置轨道的当前时间(以秒为单位)。当用于设置值时,返回对当前 AudioTrack
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。seconds
: (optional, number) The time to set. Valid values are floating-point numbers in the range 0
(start) to the maximum duration—e.g., 60
is 60
is sixty seconds in, 90.5
is ninety-point-five seconds in.0
(开始)到最大持续时间之间的浮点数——例如, 60
是六十秒后, 60
是九十点五秒后。// Get the track's current time.
var trackTime = aTrack.time();
// Set the track's current time to 30 seconds from its beginning.
aTrack.time(30);
// Set the track's current time to 30 seconds from its end.
aTrack.time(aTrack.duration() - 30);
<AudioTrack>.unload()
Stops playback of the track and forces it to drop any existing data.
停止播放曲目并强制它丢弃任何现有数据。
Note:
Once unloaded, playback cannot occur until the track's data is loaded again.
注意:一旦卸载,播放将无法进行,直到再次加载音轨的数据。
v2.28.0
: Introduced. v2.28.0
: 引入。aTrack.unload();
<AudioTrack>.volume([level])
→ get: number | set: AudioTrack
object<AudioTrack>.volume([level])
→ 获取: 数字 | 设置: AudioTrack
对象 Gets or sets the track's volume level (default: 1
). When used to set the volume, returns a reference to the current AudioTrack
instance for chaining.
获取或设置音轨的音量级别(默认: 1
)。当用于设置音量时,返回当前 AudioTrack
实例以实现链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。level
: (optional, number) The volume level to set. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.level
:(可选,数字)要设置的音量级别。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。// Get the track's current volume level.
var trackVolume = aTrack.volume();
// Set the track's volume level to 75%.
aTrack.volume(0.75);
AudioRunner
API Audio runners are useful for performing actions on multiple tracks at once.
音频运行器可用于同时对多个曲目执行操作。
See Also:
SimpleAudio
API, AudioTrack
API, and AudioList
API.
相关链接: SimpleAudio
API、 AudioTrack
API 和 AudioList
API。
<AudioRunner>.fade(duration , toVol [, fromVol])
Starts playback of the selected tracks and fades them between the specified starting and destination volume levels over the specified number of seconds.
开始播放所选曲目,并在指定秒数内将音量从起始级别渐变到目标级别。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)决定是否自动暂停渐变到 0
音量(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。duration
: (number) The number of seconds over which the tracks should be faded.duration
: (秒数)轨道应该淡入的秒数。toVol
: (number) The destination volume level.toVol
: (数字)目标音量级别。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the tracks' current volume level.fromVol
: (可选,数字)起始音量级别。如果省略,则默认为轨道当前音量级别。// Fade the selected tracks from volume 0 to 1 over 6 seconds.
someTracks.fade(6, 1, 0);
<AudioRunner>.fadeIn(duration [, fromVol])
Starts playback of the selected tracks and fades them from the specified volume level to 1
(loudest) over the specified number of seconds.
开始播放所选轨道,并在指定的秒数内从指定音量级别淡入至 1
(最响)。
v2.28.0
: Introduced. v2.28.0
: 引入。duration
: (number) The number of seconds over which the tracks should be faded.duration
: (秒数)轨道应该淡入的秒数。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the tracks' current volume level.fromVol
: (可选,秒数)起始音量级别。如果省略,则默认为轨道当前音量级别。// Fade the selected tracks in from volume 0 over 5 seconds.
someTracks.fadeIn(5, 0);
<AudioRunner>.fadeOut(duration [, fromVol])
Starts playback of the selected tracks and fades them from the specified volume level to 0
(silent) over the specified number of seconds.
开始播放所选曲目,并在指定秒数内从指定音量级别渐变到 0
(静音)。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)决定是否自动暂停渐变到 0
音量(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。duration
: (number) The number of seconds over which the tracks should be faded.duration
:(数字) 曲目应渐变的秒数。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the tracks' current volume level.fromVol
:(可选,数字) 起始音量级别。如果省略,则默认为曲目当前音量级别。// Fade the selected tracks out from volume 1 over 8 seconds.
someTracks.fadeOut(8, 1);
<AudioRunner>.fadeStop()
Interrupts an in-progress fade of the selected tracks, or does nothing if no fade is progressing.
中断所选曲目的渐变操作,如果没有渐变操作进行,则不执行任何操作。
Note:
This does not alter the volume level.
注意:这不会改变音量级别。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.fadeStop();
<AudioRunner>.load()
Pauses playback of the selected tracks and, if they're not already in the process of loading, forces them to drop any existing data and begin loading.
暂停播放所选曲目,如果它们尚未在加载过程中,则强制它们丢弃任何现有数据并开始加载。
Warning:
This should not be done lightly if your audio sources are on the network, as it forces players to begin downloading them.
警告:如果您的音频源在网络上,则不应轻率地进行此操作,因为它会强制播放器开始下载它们。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.load();
<AudioRunner>.loop(state)
→ AudioRunner
object <AudioRunner>.loop(state)
→ AudioRunner
对象 Sets the selected tracks' repeating playback state (default: false
). Returns a reference to the current AudioRunner
instance for chaining.
设置所选轨道的重复播放状态(默认: false
)。返回当前 AudioRunner
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (boolean) The loop state.state
:(布尔值) 循环状态。// Loop the selected tracks.
someTracks.loop(true);
// Unloop the selected tracks.
someTracks.loop(false);
<AudioRunner>.mute(state)
→ AudioRunner
object <AudioRunner>.mute(state)
→ AudioRunner
对象 Sets the selected tracks' volume mute state (default: false
). Returns a reference to the current AudioRunner
instance for chaining.
设置所选轨道的音量静音状态(默认: false
)。返回当前 AudioRunner
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (boolean) The mute state.// Mute the selected tracks' volume.
someTracks.mute(true);
// Unmute the selected tracks' volume.
someTracks.mute(false);
<AudioRunner>.off(...args)
→ AudioRunner
object <AudioRunner>.off(...args)
→ AudioRunner
对象 Removes event handlers from the selected tracks. Returns a reference to the current AudioRunner
instance for chaining.
从所选轨道中移除事件处理器。返回当前 AudioRunner
实例的引用以进行链式调用。
Note:
Shorthand for jQuery's .off()
method applied to each of the audio elements.
注意:jQuery 的 .off()
方法的简写,应用于每个音频元素。
Warning:
The SimpleAudio
APIs use events internally for various pieces of functionality. To prevent conflicts, it is strongly suggested that you specify a custom user namespace—e.g., .myEvents
—when attaching your own handlers. It is further strongly suggested that you provide that same custom user namespace when removing them.
警告: SimpleAudio
API 内部使用事件来实现各种功能。为了避免冲突,强烈建议您在附加自己的处理程序时指定一个自定义用户命名空间——例如, .myEvents
。同样,在移除它们时也强烈建议您提供相同的自定义用户命名空间。
v2.28.0
: Introduced. v2.28.0
: 引入。See:
<jQuery>.off()
in the jQuery API docs for more information.
查看 jQuery API 文档中的 <jQuery>.off()
以获取更多信息。
// Remove any handlers for the ended event.
someTracks.off('ended.myEvents');
<AudioRunner>.on(...args)
→ AudioRunner
object <AudioRunner>.on(...args)
→ AudioRunner
对象 Attaches event handlers to the selected tracks. Returns a reference to the current AudioRunner
instance for chaining.
将事件处理器附加到所选轨道。返回当前 AudioRunner
实例的引用以进行链式调用。
Note:
Shorthand for jQuery's .on()
method applied to each of the audio elements.
注意:jQuery 的 .on()
方法的简写,应用于每个音频元素。
Warning:
The SimpleAudio
APIs use events internally for various pieces of functionality. To prevent conflicts, it is strongly suggested that you specify a custom user namespace—e.g., .myEvents
—when attaching your own handlers. It is further strongly suggested that you provide that same custom user namespace when removing them.
警告: SimpleAudio
API 内部使用事件来实现各种功能。为了避免冲突,强烈建议您在附加自己的处理程序时指定一个自定义用户命名空间——例如, .myEvents
。同样,在移除它们时也强烈建议您提供相同的自定义用户命名空间。
v2.28.0
: Introduced. v2.28.0
: 引入。See:
<jQuery>.on()
in the jQuery API docs for more information.
查看 jQuery API 文档中的 <jQuery>.on()
以获取更多信息。
// Add a handler for the ended event.
someTracks.on('ended.myEvents', function () {
/* do something */
});
<AudioRunner>.one(...args)
→ AudioRunner
object <AudioRunner>.one(...args)
→ AudioRunner
对象 Attaches single-use event handlers to the selected tracks. Returns a reference to the current AudioRunner
instance for chaining.
将单次使用的事件处理器附加到所选轨道。返回当前 AudioRunner
实例的引用以进行链式调用。
Note:
Shorthand for jQuery's .one()
method applied to each of the audio elements.
注意:这是 jQuery 的 .one()
方法对每个音频元素应用的简写。
Warning:
The SimpleAudio
APIs use events internally for various pieces of functionality. To prevent conflicts, it is strongly suggested that you specify a custom user namespace—e.g., .myEvents
—when attaching your own handlers. It is further strongly suggested that you provide that same custom user namespace when removing them.
警告: SimpleAudio
API 内部使用事件来实现各种功能。为了避免冲突,强烈建议您在附加自己的处理程序时指定一个自定义用户命名空间——例如, .myEvents
。同样,在移除它们时也强烈建议您提供相同的自定义用户命名空间。
v2.28.0
: Introduced. v2.28.0
: 引入。See:
<jQuery>.one()
in the jQuery API docs for more information.
查看 jQuery API 文档中的 <jQuery>.one()
以获取更多信息。
// Add a single-use handler for the ended event.
someTracks.one('ended.myEvents', function () {
/* do something */
});
<AudioRunner>.pause()
Pauses playback of the selected tracks.
暂停播放所选曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.pause();
<AudioRunner>.play()
Begins playback of the selected tracks.
开始播放所选曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.play();
<AudioRunner>.playWhenAllowed()
Begins playback of the selected tracks or, failing that, sets the tracks to begin playback as soon as the player has interacted with the document.
开始播放所选曲目,如果不行,则设置曲目在播放器与文档交互后立即开始播放。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.playWhenAllowed();
<AudioRunner>.stop()
Stops playback of the selected tracks.
停止播放所选曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.stop();
<AudioRunner>.time(seconds)
→ AudioRunner
object <AudioRunner>.time(seconds)
→ AudioRunner
对象 Sets the selected tracks' current time in seconds. Returns a reference to the current AudioRunner
instance for chaining.
设置所选曲目的当前时间(以秒为单位)。返回对当前 AudioRunner
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。seconds
: (number) The time to set. Valid values are floating-point numbers in the range 0
(start) to the maximum duration—e.g., 60
is 60
is sixty seconds in, 90.5
is ninety-point-five seconds in.seconds
: (数字) 要设置的时间。有效值是范围在 0
(开始)到最大持续时间之间的浮点数——例如, 60
是 60
是六十秒后, 90.5
是九十点五秒后。// Set the selected tracks' current time to 30 seconds from their beginning.
someTracks.time(30);
<AudioRunner>.unload()
Stops playback of the selected tracks and forces them to drop any existing data.
停止播放所选曲目并强制它们丢弃任何现有数据。
Note:
Once unloaded, playback cannot occur until the selected tracks' data is loaded again.
注意:一旦卸载,播放将无法进行,直到所选轨道的数据再次加载。
v2.28.0
: Introduced. v2.28.0
: 引入。someTracks.unload();
<AudioRunner>.volume(level)
→ AudioRunner
object <AudioRunner>.volume(level)
→ AudioRunner
对象 Sets the selected tracks' volume level (default: 1
). Returns a reference to the current AudioRunner
instance for chaining.
设置选中轨道的音量级别(默认: 1
)。返回当前 AudioRunner
实例的引用以实现链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。level
: (number) The volume level to set. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.level
:(数字) 要设置的音量级别。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。// Set the selected tracks' volume level to 75%.
someTracks.volume(0.75);
AudioList
API Audio lists (playlists) are useful for playing tracks in a sequence—i.e., one after another.
音频列表(播放列表)对于按顺序播放轨道非常有用——即,一个接一个地播放。
See Also:
SimpleAudio
API, AudioTrack
API, and AudioRunner
API.
相关链接: SimpleAudio
API、 AudioTrack
API 和 AudioRunner
API。
<AudioList>.duration()
→ number <AudioList>.duration()
→ 数字 Returns the playlist's total playtime in seconds, Infinity
if it contains any streams, or NaN
if no metadata exists.
返回播放列表的总播放时间(以秒为单位),如果包含任何流,则为 Infinity
,如果没有元数据存在,则为 NaN
。
v2.28.0
: Introduced. v2.28.0
: 引入。var listLength = aList.duration();
<AudioList>.fade(duration , toVol [, fromVol])
→ Promise
object <AudioList>.fade(duration , toVol [, fromVol])
→ Promise
对象 Starts playback of the playlist and fades the currently playing track between the specified starting and destination volume levels over the specified number of seconds.
开始播放播放列表,并在指定秒数内将当前播放的曲目从指定起始音量级别淡入到目标音量级别。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)决定是否自动暂停渐变到 0
音量(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Updated to return a Promise
.v2.29.0
:更新为返回 Promise
。duration
: (number) The number of seconds over which the currently playing track should be faded.duration
:(数字)当前播放的曲目应该淡入淡出的秒数。toVol
: (number) The destination volume level.fromVol
: (optional, number) The starting volume level. If omitted, defaults to the currently playing track's current volume level.fromVol
:(可选,数字)起始音量级别。如果省略,则默认为当前播放轨道的当前音量级别。// Fade the playlist from volume 0 to 1 over 6 seconds.
aList.fade(6, 1, 0);
<AudioList>.fadeIn(duration [, fromVol])
→ Promise
object <AudioList>.fadeIn(duration [, fromVol])
→ Promise
对象 Starts playback of the playlist and fades the currently playing track from the specified volume level to 1
(loudest) over the specified number of seconds.
开始播放播放列表,并将当前播放的曲目从指定的音量级别淡入到 1
(最响)的过程中,持续指定秒数。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Updated to return a Promise
.v2.29.0
:更新为返回 Promise
。duration
: (number) The number of seconds over which the currently playing track should be faded.duration
:指定秒数,当前播放的曲目应该在这段时间内淡入。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the currently playing track's current volume level.fromVol
:可选(数字),起始音量级别。如果省略,则默认为当前播放曲目的当前音量级别。// Fade the playlist in from volume 0 over 5 seconds.
aList.fadeIn(5, 0);
<AudioList>.fadeOut(duration [, fromVol])
→ Promise
object <AudioList>.fadeOut(duration [, fromVol])
→ Promise
对象 Starts playback of the playlist and fades the currently playing track from the specified volume level to 0
(silent) over the specified number of seconds.
开始播放播放列表,并在指定秒数内将当前播放的曲目从指定音量级别淡出到 0
(静音)。
Note:
The Config.audio.pauseOnFadeToZero
setting (default: true
) determines whether the audio subsystem automatically pauses tracks that have been faded to 0
volume (silent).
注意: Config.audio.pauseOnFadeToZero
设置(默认: true
)决定是否自动暂停渐变到 0
音量(静音)的曲目。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Updated to return a Promise
.v2.29.0
:更新为返回 Promise
。duration
: (number) The number of seconds over which the currently playing track should be faded.duration
:(数字)当前播放的曲目应该淡入淡出的秒数。fromVol
: (optional, number) The starting volume level. If omitted, defaults to the currently playing track's current volume level.fromVol
:(可选,数字)起始音量级别。如果省略,则默认为当前播放轨道的当前音量级别。// Fade the playlist out from volume 1 over 8 seconds.
aList.fadeOut(8, 1);
<AudioList>.fadeStop()
Interrupts an in-progress fade of the currently playing track, or does nothing if no fade is progressing.
中断当前播放的曲目正在进行的淡入,如果没有淡入进行则不执行任何操作。
Note:
This does not alter the volume level.
注意:这不会改变音量级别。
v2.29.0
: Introduced. v2.29.0
: 引入。aList.fadeStop();
<AudioList>.isEnded()
→ boolean <AudioList>.isEnded()
→ 布尔值 Returns whether playback of the playlist has ended.
返回播放列表是否已结束播放。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aList.isEnded()) {
/* do something */
}
<AudioList>.isFading()
→ boolean <AudioList>.isFading()
→ 布尔值 Returns whether a fade is in-progress on the currently playing track.
返回当前播放的曲目是否正在进行淡入。
v2.29.0
: Introduced. v2.29.0
: 引入。if (aList.isFading()) {
/* do something */
}
<AudioList>.isPaused()
→ boolean <AudioList>.isPaused()
→ 布尔值 Returns whether playback of the playlist has been paused.
返回播放列表是否已被暂停播放。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aList.isPaused()) {
/* do something */
}
<AudioList>.isPlaying()
→ boolean <AudioList>.isPlaying()
→ 布尔值 Returns whether the playlist is playing.
返回播放列表是否正在播放。
v2.28.0
: Introduced. v2.28.0
: 引入。if (aList.isPlaying()) {
/* do something */
}
<AudioList>.isStopped()
→ boolean <AudioList>.isStopped()
→ 布尔值 Returns whether playback of the playlist has been stopped.
返回播放列表播放是否已停止。
v2.29.0
: Introduced. v2.29.0
: 引入。if (aList.isStopped()) {
/* do something */
}
<AudioList>.load()
Pauses playback of the playlist and, if they're not already in the process of loading, forces its tracks to drop any existing data and begin loading.
暂停播放播放列表,并且如果它们尚未在加载过程中,则强制其曲目丢弃任何现有数据并开始加载。
Warning:
This should not be done lightly if your audio sources are on the network, as it forces players to begin downloading them.
警告:如果您的音频源在网络上,则不应轻率地进行此操作,因为它会强制播放器开始下载它们。
v2.28.0
: Introduced. v2.28.0
: 引入。aList.load();
<AudioList>.loop([state])
→ get: boolean | set: AudioList
object Gets or sets the playlist's repeating playback state (default: false
). When used to set the loop state, returns a reference to the current AudioList
instance for chaining.
获取或设置播放列表的重复播放状态(默认: false
)。当用于设置循环状态时,返回当前 AudioList
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The loop state.state
: (可选,布尔值)循环状态。// Get the playlist's current loop state.
var isLooped = aList.loop();
// Loop the playlist.
aList.loop(true);
// Unloop the playlist.
aList.loop(false);
<AudioList>.mute([state])
→ get: boolean | set: AudioList
object Gets or sets the playlist's volume mute state (default: false
). When used to set the mute state, returns a reference to the current AudioList
instance for chaining.
获取或设置播放列表的静音状态(默认: false
)。当用于设置静音状态时,返回当前 AudioList
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The mute state.state
:(可选,布尔值)静音状态。// Get the playlist's current volume mute state.
var isMuted = aList.mute();
// Mute the playlist's volume.
aList.mute(true);
// Unmute the playlist's volume.
aList.mute(false);
<AudioList>.pause()
Pauses playback of the playlist.
暂停播放播放列表。
v2.28.0
: Introduced. v2.28.0
: 引入。aList.pause();
<AudioList>.play()
→ Promise
object <AudioList>.play()
→ Promise
对象 Begins playback of the playlist.
开始播放播放列表。
v2.28.0
: Introduced. v2.28.0
: 引入。v2.29.0
: Updated to return a Promise
.v2.29.0
:更新为返回 Promise
。aList.play();
Promise
使用返回的 Promise
aList.play()
.then(function () {
console.log('The playlist is playing.');
})
.catch(function (problem) {
console.warn('There was a problem with playback: ' + problem);
});
<AudioList>.playWhenAllowed()
Begins playback of the playlist or, failing that, sets the playlist to begin playback as soon as the player has interacted with the document.
开始播放播放列表,或者在失败的情况下,将播放列表设置为在播放器与文档交互后立即开始播放。
v2.29.0
: Introduced. v2.29.0
: 引入。aList.playWhenAllowed();
<AudioList>.remaining()
→ number <AudioList>.remaining()
→ 数字 Returns how much remains of the playlist's total playtime in seconds, Infinity
if it contains any streams, or NaN
if no metadata exists.
返回播放列表总播放时间剩余秒数,如果包含任何流,则为 Infinity
,如果没有元数据,则为 NaN
。
v2.28.0
: Introduced. v2.28.0
: 引入。var listRemains = aList.remaining();
<AudioList>.shuffle([state])
→ get: boolean | set: AudioList
object Gets or sets the playlist's randomly shuffled playback state (default: false
). When used to set the shuffle state, returns a reference to the current AudioList
instance for chaining.
获取或设置播放列表的随机播放状态(默认: false
)。当用于设置随机播放状态时,返回当前 AudioList
实例的引用以实现链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。state
: (optional, boolean) The shuffle state.state
:(可选,布尔值)随机播放状态。// 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);
<AudioList>.skip()
Skips ahead to the next track in the playlist, if any.
跳转到播放列表中的下一首曲目(如果有)。
v2.28.0
: Introduced. v2.28.0
: 引入。someTrack.skip();
<AudioList>.stop()
Stops playback of the playlist.
停止播放播放列表。
v2.28.0
: Introduced. v2.28.0
: 引入。someTrack.stop();
<AudioList>.time()
→ number <AudioList>.time()
→ 数字 Returns the playlist's current time in seconds, or NaN
if no metadata exists.
返回播放列表的当前时间(以秒为单位),或 NaN
如果没有元数据存在。
v2.28.0
: Introduced. v2.28.0
: 引入。var listTime = aList.time();
<AudioList>.unload()
Stops playback of the playlist and forces its tracks to drop any existing data.
停止播放播放列表并强制其曲目丢弃任何现有数据。
Note:
Once unloaded, playback cannot occur until the track's data is loaded again.
注意:一旦卸载,播放将无法进行,直到再次加载曲目数据。
v2.28.0
: Introduced. v2.28.0
: 引入。aList.unload();
<AudioList>.volume([level])
→ get: number | set: AudioList
object<AudioList>.volume([level])
→ 获取: 数字 | 设置: AudioList
对象 Gets or sets the playlist's volume level (default: 1
). When used to set the volume, returns a reference to the current AudioList
instance for chaining.
获取或设置播放列表的音量级别(默认: 1
)。当用于设置音量时,返回当前 AudioList
实例的引用以进行链式调用。
v2.28.0
: Introduced. v2.28.0
: 引入。level
: (optional, number) The volume level to set. Valid values are floating-point numbers in the range 0
(silent) to 1
(loudest)—e.g., 0
is 0%, 0.5
is 50%, 1
is 100%.level
:(可选,数字)要设置的音量级别。有效值是范围在 0
(静音)到 1
(最响)之间的浮点数——例如, 0
是 0%, 0.5
是 50%, 1
是 100%。// Get the playlist's current volume level.
var trackVolume = aList.volume();
// Set the playlist's volume level to 75%.
aList.volume(0.75);
State
API The story history contains moments (states) created during play. Since it is possible to navigate the history—i.e., move backward and forward though the moments within the history—it may contain both past moments—i.e., moments that have been played—and future moments—i.e., moments that had been played, but have been rewound/undone, yet are still available to be restored.
故事历史包含在游戏过程中创建的瞬间(状态)。由于可以导航历史——即,在历史中的瞬间前后移动——它可能包含过去瞬间——即,已经玩过的瞬间——以及未来瞬间——即,已经玩过但被回滚/撤销,但仍可恢复的瞬间。
In addition to the history, there is also the active moment—i.e., present—and expired moments—i.e., moments that had been played, but have expired from the history, thus cannot be navigated to.
除了历史之外,还有当前瞬间——即,现在——以及过期瞬间——即,已经玩过但已从历史中过期的瞬间,因此无法导航到。
API members dealing with the history work upon either the active moment—i.e., present—or one of the history subsets: the full in-play history—i.e., past + future—the past in-play subset—i.e., past only—or the extended past subset—i.e., expired + past. These instances will be noted.
处理历史的 API 成员要么在当前瞬间——即,现在——要么在历史子集上工作:完整的游戏历史——即,过去+未来——过去游戏子集——即,仅过去——或扩展过去子集——即,过期+过去。这些实例将被注明。
State.active
→ object State.active
→ 对象 Returns the active (present) moment.
返回当前活跃(存在)的时刻。
Note:
Using State.active
directly is generally unnecessary as there exist a number of shortcut properties, State.passage
and State.variables
, and story functions, passage()
and variables()
, which grant access to its normal properties.
注意:通常不需要直接使用 State.active
,因为存在许多快捷属性 State.passage
和 State.variables
,以及故事函数 passage()
和 variables()
,它们可以提供对正常属性的访问。
v2.0.0
: Introduced. v2.0.0
: 引入。State.active.title → The title of the present moment
State.active.variables → The variables of the present moment
State.bottom
→ object State.bottom
→ 对象 Returns the bottommost (least recent) moment from the full in-play history (past + future).
返回全游戏历史中(过去+未来)最底部的(最不最近)时刻。
v2.0.0
: Introduced. v2.0.0
: 引入。State.bottom.title → The title of the least recent moment within the full in-play history
State.bottom.variables → The variables of the least recent moment within the full in-play history
State.current
→ object State.current
→ 对象 Returns the current moment from the full in-play history (past + future), which is the pre-play version of the active moment.
返回全游戏历史中(过去+未来)的当前时刻,这是活动时刻的预播放版本。
Warning:
State.current
is not a synonym for State.active
. You will, very likely, never need to use State.current
directly within your code.
警告: State.current
不是 State.active
的同义词。你很可能永远不需要在代码中直接使用 State.current
。
v2.8.0
: Introduced. v2.8.0
: 引入。State.current.title → The title of the current moment within the full in-play history
State.current.variables → The variables of the current moment within the full in-play history
State.length
→ integer State.length
→ 整数 Returns the number of moments within the past in-play history (past only).
返回过去在玩历史中的时刻数量(仅过去)。
v2.0.0
: Introduced. v2.0.0
: 引入。if (State.length === 0) {
/* No moments within the past in-play history. Egad! */
}
State.passage
→ string State.passage
→ 字符串 Returns the title of the passage associated with the active (present) moment.
返回与活动(当前)时刻关联的段落标题。
v2.0.0
: Introduced. v2.0.0
: 引入。State.passage → The passage title of the present moment
State.size
→ integer State.size
→ 整数 Returns the number of moments within the full in-play history (past + future).
返回整个在玩历史(过去+未来)中的时刻数量。
v2.0.0
: Introduced. v2.0.0
: 引入。if (State.size === 0) {
/* No moments within the full in-play history. Egad! */
}
State.temporary
→ object State.temporary
→ 对象 Returns the current temporary variables.
返回当前临时变量。
v2.13.0
: Introduced. v2.13.0
: 引入。State.temporary → The current temporary variables
State.top
→ object State.top
→ 对象 Returns the topmost (most recent) moment from the full in-play history (past + future).
返回全历史记录中最新(最近)的时刻(过去 + 未来)。
Warning:
State.top
is not a synonym for State.active
. You will, very likely, never need to use State.top
directly within your code.
警告: State.top
不是 State.active
的同义词。你很可能永远不需要在代码中直接使用 State.top
。
v2.0.0
: Introduced. v2.0.0
: 引入。State.top.title → The title of the most recent moment within the full in-play history
State.top.variables → The variables of the most recent moment within the full in-play history
State.turns
→ integer State.turns
→ 整数 Returns the total number (count) of played moments within the extended past history (expired + past).
返回在扩展过去历史中(已过期 + 过去)播放的时刻总数(计数)。
v2.0.0
: Introduced. v2.0.0
: 引入。if (State.turns === 1) {
/* Initial turn. The starting passage is displayed. */
}
State.variables
→ object State.variables
→ 对象 Returns the variables from the active (present) moment.
返回活动(当前)时刻的变量。
v2.0.0
: Introduced. v2.0.0
: 引入。State.variables → The variables of the present moment
State.getVar(varName)
→ any State.getVar(varName)
→ 任何 Returns the value of the story or temporary variable by the given name.
通过给定的名称返回故事或临时变量的值。
v2.22.0
: Introduced. v2.22.0
: 引入。varName
: (string) The name of the story or temporary variable, including its sigil—e.g., $charName
.varName
: (字符串) 故事或临时变量的名称,包括其符号—例如, $charName
.State.getVar("$charName") → Returns the value of $charName
State.has(passageTitle)
→ boolean State.has(passageTitle)
→ 布尔值 Returns whether any moments with the given title exist within the past in-play history (past only).
返回过去在游戏中是否存在具有给定标题的时刻(仅过去)。
Note:
State.has()
does not check expired moments. If you need to know if the player has ever been to a particular passage, then you must use the State.hasPlayed()
method or the hasVisited()
story function.
注意: State.has()
不检查已过期的时刻。如果您需要知道玩家是否曾经访问过特定的篇章,则必须使用 State.hasPlayed()
方法或 hasVisited()
故事函数。
v2.0.0
: Introduced. v2.0.0
: 引入。passageTitle
: (string) The title of the moment whose existence will be verified.passageTitle
:(字符串) 要验证其存在的时刻的标题。State.has("The Ducky") → Returns whether a moment matching "The Ducky" exists
State.hasPlayed(passageTitle)
→ boolean State.hasPlayed(passageTitle)
→ 布尔值 Returns whether any moments with the given title exist within the extended past history (expired + past).
返回过去和过期时刻(过期+过去)中是否存在具有给定标题的时刻。
Note:
If you need to check for multiple passages, the hasVisited()
story function will likely be more convenient to use.
注意:如果您需要检查多个段落,使用 hasVisited()
故事功能可能会更方便。
v2.0.0
: Introduced. v2.0.0
: 引入。passageTitle
: (string) The title of the moment whose existence will be verified.passageTitle
: (字符串) 验证存在的瞬间的标题。State.hasPlayed("The Ducky") → Returns whether a moment matching "The Ducky" ever existed
State.index(index)
→ object State.index(index)
→ 对象 Returns the moment, relative to the bottom of the past in-play history (past only), at the given index.
返回相对于过去在播放历史(仅过去)中给定索引的瞬间。
v2.0.0
: Introduced. v2.0.0
: 引入。index
: (integer) The index of the moment to return.index
: (整数) 要返回的瞬间的索引。State.index(0) → Returns the least recent moment within the past in-play history
State.index(1) → Returns the second to least recent moment within the past in-play history
State.index(State.length - 1) → Returns the most recent moment within the past in-play history
State.isEmpty()
→ boolean State.isEmpty()
→ 布尔值 Returns whether the full in-play history (past + future) is empty.
返回整个在播放历史(过去 + 未来)是否为空。
v2.0.0
: Introduced. v2.0.0
: 引入。if (State.isEmpty()) {
/* No moments within the full in-play history. Egad! */
}
State.peek([offset])
→ object State.peek([offset])
→ 对象 Returns the moment, relative to the top of the past in-play history (past only), at the, optional, offset.
返回相对于过去播放历史顶部的时间点(仅过去),以及可选的偏移量。
v2.0.0
: Introduced. v2.0.0
: 引入。offset
: (optional, integer) The offset, from the top of the past in-play history, of the moment to return. If not given, an offset of 0
is used.offset
:(可选,整数)返回的时间点相对于过去播放历史顶部的偏移量。如果没有提供,则使用偏移量 0
。State.peek() → Returns the most recent moment within the past in-play history
State.peek(0) → Returns the most recent moment within the past in-play history
State.peek(1) → Returns the second most recent moment within the past in-play history
State.peek(State.length - 1) → Returns the least recent moment within the past in-play history
State.metadata.size
→ integer State.metadata.size
→ 整数 Returns the size of the story metadata store—i.e., the number of stored pairs.
返回故事元数据存储的大小——即存储的配对数量。
v2.30.0
: Introduced. v2.30.0
: 引入。// Determines whether the metadata store has any members.
if (State.metadata.size > 0) {
/* store is not empty */
}
State.metadata.clear()
Empties the story metadata store.
清空故事元数据存储。
v2.29.0
: Introduced. v2.29.0
: 引入。// Removes all values from the metadata store.
State.metadata.clear();
State.metadata.delete(key)
Removes the specified key, and its associated value, from the story metadata store.
从故事元数据存储中删除指定的键及其关联的值。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string) The key to delete.// Removes 'achievements' from the metadata store.
State.metadata.delete('achievements');
State.metadata.entries()
→ Array<Array<string, any>>Returns an array of the story metadata store's key/value pairs as [key, value]
arrays.
返回故事元数据存储的键/值对作为 [key, value]
数组。
v2.36.0
: Introduced. v2.36.0
: 引入。// Iterate over the pairs with a `for` loop.
var metadata = State.metadata.entries();
for (var i = 0; i < metadata.length; ++i) {
var key = metadata[i][0];
var value = metadata[i][1];
/* do something */
}
// Iterate over the pairs with `<Array>.forEach()`.
State.metadata.entries().forEach(function (pair) {
var key = pair[0];
var value = pair[1];
/* do something */
});
State.metadata.get(key)
→ any State.metadata.get(key)
→ 任何 Returns the value associated with the specified key from the story metadata store.
返回从故事元数据存储中与指定键关联的值。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string) The key whose value should be returned.key
: (字符串) 应返回其值的键。// Returns the value of 'achievements' from the metadata store.
var playerAchievements = State.metadata.get('achievements');
State.metadata.has(key)
→ boolean State.metadata.has(key)
→ 布尔值 Returns whether the specified key exists within the story metadata store.
返回指定键是否存在于故事元数据存储中。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string) The key whose existence should be tested.key
: (字符串) 应测试其存在的键。// Returns whether 'achievements' exists within the metadata store.
if (State.metadata.has('achievements')) {
/* do something */
}
State.metadata.keys()
→ Array<string> State.metadata.keys()
→ 数组 Returns an array of the story metadata store's keys.
返回故事元数据存储键的数组。
v2.36.0
: Introduced. v2.36.0
: 引入。// Iterate over the keys with a `for` loop.
var metadataKeys = State.metadata.keys();
for (var i = 0; i < metadataKeys.length; ++i) {
var key = metadataKeys[i];
/* do something */
}
// Iterate over the keys with `<Array>.forEach()`.
State.metadata.keys().forEach(function (key) {
/* do something */
});
State.metadata.set(key, value)
Sets the specified key and value within the story metadata store, which causes them to persist over story and browser restarts—n.b. private browsing modes do interfere with this. To update the value associated with a key, simply set it again.
设置故事元数据存储中的指定键和值,这将使它们在故事和浏览器重启后持续存在——请注意,私密浏览模式会干扰这一点。要更新与键关联的值,只需再次设置它即可。
Note:
The story metadata, like saves, is tied to the specific story it was generated with. It is not a mechanism for moving data between stories.
注意:故事元数据,如存档,与特定生成的故事相关联。它不是在故事之间移动数据的一种机制。
Warning:
The story metadata store is not, and should not be used as, a replacement for saves. Examples of good uses: achievement tracking, new game+ data, playthrough statistics, etc.
警告:故事元数据存储不应,也不应作为保存的替代品使用。示例:成就跟踪、新游戏+数据、游玩统计等。
Warning:
This feature is largely incompatible with private browsing modes, which cause all in-browser storage mechanisms to either persist only for the lifetime of the browsing session or fail outright.
警告:此功能与私密浏览模式大部分不兼容,可能导致所有浏览器存储机制只能持续浏览会话的生命周期,或者完全失败。
v2.29.0
: Introduced. v2.29.0
: 引入。key
: (string) The key that should be set.key
: (字符串) 应设置的键。value
: (any) The value to set.value
: (任何类型) 要设置的值。// Sets 'achievements', with the given value, in the metadata store.
State.metadata.set('achievements', { ateYellowSnow : true });
// Sets 'ngplus', with the given value, in the metadata store.
State.metadata.set('ngplus', true);
State.prng.init([seed [, useEntropy]])
Initializes the seedable pseudo-random number generator (PRNG) and integrates it into the story state and saves. Once initialized, the State.random()
method and story functions, random()
and randomFloat()
, return deterministic results from the seeded PRNG—by default, they return non-deterministic results from Math.random()
.
初始化可播种的伪随机数生成器(PRNG),并将其集成到故事状态中并保存。一旦初始化, State.random()
方法以及故事函数 random()
和 randomFloat()
将从播种的 PRNG 返回确定性结果——默认情况下,它们从 Math.random()
返回非确定性结果。
Note:
State.prng.init()
must be called during story initialization, within either your project's JavaScript section (Twine 2: the Story JavaScript; Twine 1/Twee: a script
-tagged passage) or the StoryInit
special passage. Additionally, it is strongly recommended that you do not specify any arguments to State.prng.init()
and allow it to automatically seed itself. If you should chose to use an explicit seed, however, it is strongly recommended that you also enable additional entropy, otherwise all playthroughs for all players will be exactly the same.
注意: State.prng.init()
必须在故事初始化期间调用,无论是在您的项目的 JavaScript 部分(Twine 2:故事 JavaScript;Twine 1/Twee:带有 script
标签的段落)还是在 StoryInit
特殊段落中。此外,强烈建议您不要为 State.prng.init()
指定任何参数,并允许它自动播种。如果您选择使用显式种子,则强烈建议您还启用额外的熵,否则所有玩家的所有游戏过程都将完全相同。
v2.29.0
: Introduced. v2.29.0
: 引入。seed
: (optional, string) The explicit seed used to initialize the pseudo-random number generator.seed
: (可选,字符串) 用于初始化伪随机数生成器的显式种子。useEntropy
: (optional, boolean) Enables the use of additional entropy to pad the specified explicit seed.useEntropy
: (可选,布尔值) 启用使用额外熵来填充指定的显式种子。State.prng.init() → Automatically seed the PRNG (recommended)
State.prng.init("aVeryLongSeed") → Seed the PRNG with "aVeryLongSeed" (not recommended)
State.prng.init("aVeryLongSeed", true) → Seed the PRNG with "aVeryLongSeed" and pad it with extra entropy
State.prng.isEnabled()
→ boolean State.prng.isEnabled()
→ 布尔值 Returns whether the seedable PRNG has been enabled.
返回是否已启用可播种的伪随机数生成器。
v2.29.0
: Introduced. v2.29.0
: 引入。State.prng.isEnabled() → Returns whether the seedable PRNG is enabled
State.prng.pull
→ integer | NaNState.prng.pull
→ 整数 | 非数字 Returns the current pull count—i.e., how many requests have been made—from the seedable PRNG or, if the PRNG is not enabled, NaN
.
返回当前拉取计数,即已从可播种伪随机数生成器发出的请求数量,如果伪随机数生成器未启用,则为 NaN
。
Note:
The pull count is automatically included within saves and sessions, so this is not especially useful outside of debugging purposes.
注意:拉取计数会自动包含在保存和会话中,因此这主要用于调试目的。
v2.29.0
: Introduced. v2.29.0
: 引入。State.prng.pull → Returns the current PRNG pull count
State.prng.seed
→ string | nullState.prng.seed
→ 字符串 | null Returns the seed from the seedable PRNG or, if the PRNG is not enabled, null
.
返回可生成随机数的 PRNG 的种子,如果 PRNG 未启用,则为 null
。
Note:
The seed is automatically included within saves and sessions, so this is not especially useful outside of debugging purposes.
备注:种子会自动包含在保存和会话中,因此这主要用于调试目的。
v2.29.0
: Introduced. v2.29.0
: 引入。State.prng.seed → Returns the PRNG seed
State.random()
→ number State.random()
→ 数字 Returns a pseudo-random decimal number (floating-point) in the range 0
(inclusive) up to, but not including, 1
(exclusive).
返回一个伪随机的小数(浮点数),范围从 0
(包含)到 1
(不包含)。
Note:
By default, it simply returns non-deterministic results from Math.random()
, however, when the seedable PRNG has been enabled, via State.prng.init()
, it returns deterministic results from the seeded PRNG instead.
注意:默认情况下,它仅从 Math.random()
返回非确定性结果,然而,当启用可播种的伪随机数生成器后,通过 State.prng.init()
,它将返回从播种的伪随机数生成器得到的确定性结果。
v2.0.0
: Introduced. v2.0.0
: 引入。State.random() → Returns a pseudo-random floating-point number in the range [0, 1)
State.setVar(varName, value)
→ boolean State.setVar(varName, value)
→ 布尔值 Sets the value of the story or temporary variable by the given name. Returns whether the operation was successful.
设置指定名称的故事或临时变量的值。返回操作是否成功。
v2.22.0
: Introduced. v2.22.0
: 引入。varName
: (string) The name of the story or temporary variable, including its sigil—e.g., $charName
.varName
: (字符串) 故事或临时变量的名称,包括其符号—例如, $charName
.value
: (any) The value to assign.value
: (任何) 要分配的值。State.setVar("$charName", "Jane Doe") → Assigns the string "Jane Doe" to $charName
Story
API Story.id
→ string Story.id
→ 字符串 The DOM-compatible ID of the story.
故事兼容 DOM 的 ID。
v2.37.0
: Introduced. v2.37.0
: 引入。The string
DOM-compatible ID of the story, created from the slugified story name.
由故事名称的缩写形式创建的 string
故事兼容 DOM 的 ID。
Story.ifId
→ string Story.ifId
→ 字符串 The IFID (Interactive Fiction IDentifier) of the story.
故事 IFID(交互式小说标识符)。
v2.5.0
: Introduced. v2.5.0
: 引入。The string
IFID of the story, or an empty string if no IFID exists. The Twine 2 ecosystem's IFIDs are v4 random UUIDs.
故事的第 0# IFID,如果不存在则为一个空字符串。Twine 2 生态系统的 IFID 是 v4 随机 UUID。
Story.name
→ string Story.name
→ 字符串 The name of the story.
故事的名字。
v2.37.0
: Introduced. v2.37.0
: 引入。The string
name of the story.
string
故事的名字。
Story.add(descriptor)
→ boolean Story.add(descriptor)
→ 布尔值 Adds the passage to the passage store.
将段落添加到段落存储中。
Note:
This method cannot add code passages or passages tagged with code tags.
注意:此方法不能添加代码段落或带有代码标签的段落。
v2.37.0
: Introduced. v2.37.0
: 引入。descriptor
: (Object
) The passage descriptor object.descriptor
: ( Object
) 文本描述符对象。A passage descriptor object should have the following properties:
文本描述符对象应具有以下属性:
name
: (string
) The passage's name.name
: ( string
) 文本的名称。tags
: (string
) The passage's whitespace separated list of tags.tags
: ( string
) 该段落的空格分隔标签列表。text
: (string
) The passage's text.text
: ( string
) 该段落的文本。Boolean true
if the passage was added, elsewise false
.
布尔值 true
如果段落已被添加,否则 false
。
// Add a passage
const descriptor = {
name : "Forest 4",
tags : "forest heavy",
text : "You can barely see farther than arm's length for all the trees.",
};
if (Story.add(descriptor)) {
/* The "Forest 4" passage was added. */
}
Story.delete(name)
→ boolean Story.delete(name)
→ 布尔值 Deletes the Passage
instance with the given name.
删除具有给定名称的 Passage
实例。
Note:
This method cannot add code passages or passages tagged with code tags.
注意:此方法不能添加代码段落或带有代码标签的段落。
v2.37.0
: Introduced. v2.37.0
: 引入。name
: (string) The name of the Passage
instance.name
: (字符串) 实例的名称 Passage
。Boolean true
if a Passage
instance with the given name was deleted, elsewise false
.
布尔值 true
如果具有给定名称的实例已被删除,否则 false
。
// Delete the Passage instance with the name "The Ducky"
if (Story.delete("The Ducky")) {
/* The "The Ducky" passage was deleted. */
}
Story.filter(predicate [, thisArg])
→ Array<Passage>
Searches all Passage
instances for those that pass the test implemented by the given predicate function.
搜索所有 Passage
实例,以查找通过给定谓词函数测试的实例。
Note:
This method cannot retrieve passages tagged with code tags.
注意:此方法无法检索带有代码标签的段落。
v2.37.0
: Introduced. v2.37.0
: 引入。predicate
: (function) The function used to test each Passage
instance, which is passed into the function as its sole parameter. If the function returns true
, then the Passage
instance is added to the results.predicate
:(函数)用于测试每个 Passage
实例的函数,该函数作为其唯一参数传递给函数。如果该函数返回 true
,则将 Passage
实例添加到结果中。thisArg
: (optional, any) The value to use as this
when executing the predicate
function.thisArg
:(可选,任何)执行 predicate
函数时使用的 this
的值。A new Array<Passage>
filled with all instances that pass the test implemented by the given predicate function, or an empty Array
if no instances pass.
一个新填充了所有通过给定谓词函数测试的实例的 Array<Passage>
,如果没有实例通过测试,则为空 Array
。
// Returns all 'forest'-tagged Passage instances
Story.filter(function (p) {
return p.tags.includes("forest");
});
// Returns all Passage instances whose names include whitespace
var hasWhitespaceRegExp = /\s/;
Story.filter(function (p) {
return hasWhitespaceRegExp.test(p.name);
});
Story.find(predicate [, thisArg])
→ Passage
Searches all Passage
instances for the first that passes the test implemented by the given predicate function.
搜索所有 Passage
实例,找到第一个通过给定谓词函数实现的测试的实例。
Note:
This method cannot retrieve passages tagged with code tags.
注意:此方法无法检索带有代码标签的段落。
v2.37.0
: Introduced. v2.37.0
: 引入。predicate
: (function) The function used to test each Passage
object, which is passed into the function as its sole parameter. If the function returns true
, then the Passage
instance is added to the results.thisArg
: (optional, any) The value to use as this
when executing the predicate
function.thisArg
:(可选,任何)执行 predicate
函数时使用的 this
的值。The first Passage
instance that passed the test implemented by the given predicate function, or undefined
if no instance passes.
第一个通过给定谓词函数实现的测试实例,或者如果没有实例通过则为 undefined
。
// Returns the first 'forest'-tagged Passage instance
Story.find(function (p) {
return p.tags.includes("forest");
});
// Returns the first Passage instance whose name includes whitespace
var hasWhitespaceRegExp = /\s/;
Story.find(function (p) {
return hasWhitespaceRegExp.test(p.name);
});
Story.get(name)
→ Passage
Gets the Passage
instance with the given name.
获取给定名称的 Passage
实例。
Note:
This method cannot retrieve passages tagged with code tags.
注意:此方法无法检索带有代码标签的段落。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string) The name of the Passage
instance.name
: (字符串) 实例的名称 Passage
。The Passage
instance with the given name, or a new empty Passage
instance if no such passage exists.
指定名称的实例,如果不存在则创建一个空的实例。
// Get the Passage instance with the name "The Ducky"
const theDucky = Story.get("The Ducky");
Story.has(name)
→ boolean Story.has(name)
→ 布尔值 Determines whether a Passage
instance with the given name exists.
判断是否存在指定名称的实例。
Note:
This method does not check passages tagged with code tags.
注意:此方法不检查带有代码标签的段落。
v2.0.0
: Introduced. v2.0.0
: 引入。name
: (string) The name of the Passage
instance.name
: (字符串) 实例的名称 Passage
。Boolean true
if a Passage
instance with the given name exists, elsewise false
.
如果存在指定名称的实例,则为布尔值 true
,否则为 false
。
// Returns whether a "The Ducky" Passage instance exists
if (Story.has("The Ducky")) {
/* The "The Ducky" passage exists. */
}
Story.domId
→ string Story.domId
→ 字符串 Deprecated:
This setting has been deprecated and should no longer be used. See the Story.id
setting for its replacement.
已弃用:此设置已被弃用,不应再使用。有关替代方案,请参阅 Story.id
设置。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of Story.id
.Story.id
。Story.title
→ string Story.title
→ 字符串 Deprecated:
This setting has been deprecated and should no longer be used. See the Story.name
setting for its replacement.
已弃用:此设置已被弃用,不应再使用。有关替代方案,请参阅 Story.name
设置。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of Story.name
.Story.name
。Story.lookup(propertyName , searchValue [, sortProperty])
→ Array<Passage>
Deprecated:
This static method has been deprecated and should no longer be used. See the Story.filter()
static method for its replacement.
已弃用:此静态方法已被弃用,不应再使用。请参阅 Story.filter()
静态方法以获取其替代方案。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated in favor of Story.filter()
.Story.filter()
。Story.lookupWith(predicate [, sortProperty])
→ Array<Passage>
Deprecated:
This static method has been deprecated and should no longer be used. See the Story.filter()
static method for its replacement.
已弃用:此静态方法已被弃用,不应再使用。请参阅 Story.filter()
静态方法以获取其替代方案。
v2.11.0
: Introduced. v2.11.0
: 引入。v2.37.0
: Deprecated in favor of Story.filter()
.Story.filter()
。Template
API Template.size
→ number Template.size
→ 数字 Returns the number of existing templates.
返回现有模板的数量。
v2.29.0
: Introduced. v2.29.0
: 引入。if (Template.size === 0) {
/* No templates exist. */
}
Template.add(name , definition)
Add new template(s). 添加新模板。
v2.29.0
: Introduced. v2.29.0
: 引入。name
: (string | Array<string>) Name, or array of names, of the template(s) to add. NOTE: Names must consist of characters from the basic Latin alphabet and start with a letter, which may be optionally followed by any number of letters, numbers, the underscore, or the hyphen.name
: 要添加的模板的名称(字符串 | 字符串数组),或名称数组。注意:名称必须由基本拉丁字母组成,并以字母开头,后可跟任意数量的字母、数字、下划线或连字符。definition
: (function | string | Array<function | string>) Definition of the template(s), which may be a: function, string, or an array of either. NOTE: Each time array definitions are referenced, one of their member templates is randomly selected to be the output source.Function templates should return a string, which may itself contain markup. They are called with no arguments, but with their this
set to a template (execution) context object that contains the following data properties:
函数模板应返回一个字符串,该字符串本身可能包含标记。它们无参数调用,但使用其 this
设置为包含以下数据属性的模板(执行)上下文对象:
name
: (string) The template's name.name
: (字符串) 模板名称。String templates consist solely of a string, which may itself contain markup.
字符串模板仅由字符串组成,该字符串本身可能包含标记。
/* Define a function template named ?yolo. */
Template.add('yolo', function () {
return either('YOLO', 'You Only Live Once');
});
/* Define a string template named ?nolf. */
Template.add('nolf', 'No One Lives Forever');
/* Define an array of string templates named ?alsoYolo. */
Template.add('alsoYolo', ['YOLO', 'You Only Live Once']);
/* Define an array of mixed string and function templates named ?cmyk. */
Template.add('cmyk', [
'Cyan',
function () {
return either('Magenta', 'Yellow');
},
'Black'
]);
this
)this
)/* Define a function template with two names, ?color and ?Color, whose output changes based on its name. */
Template.add(['color', 'Color'], function () {
var color = either('red', 'green', 'blue');
return this.name === 'Color' ? color.toUpperFirst() : color;
});
Template.delete(name)
Remove existing template(s).
删除现有模板。
v2.29.0
: Introduced. v2.29.0
: 引入。name
: (string | Array<string>) Name, or array of names, of the template(s) to remove.name
: 要移除的模板(字符串 | 字符串数组)的名称,或名称数组。/* Deletes the template ?yolo. */
Template.delete('yolo');
/* Deletes the templates ?yolo and ?nolf. */
Template.delete(['yolo', 'nolf']);
Template.get(name)
→ function | string | Array<function | string>Template.get(name)
→ 函数 | 字符串 | 函数或字符串数组 Return the named template definition, or null
on failure.
返回指定的模板定义,或失败时返回 null
。
v2.29.0
: Introduced. v2.29.0
: 引入。name
: (string) Name of the template whose definition should be returned.name
: (字符串) 应返回其定义的模板的名称。/* Returns the template ?yolo, or null if it doesn't exist. */
var yolo = Template.get('yolo');
Template.has(name)
→ boolean Template.has(name)
→ 布尔值 Returns whether the named template exists.
返回指定模板是否存在。
v2.29.0
: Introduced. v2.29.0
: 引入。name
: (string) Name of the template to search for.name
: (字符串)要搜索的模板名称。if (Template.has('yolo')) {
/* A ?yolo template exists. */
}
UI
API UI.alert(message [, options [, closeFn]])
Opens the built-in alert dialog, displaying the given message to the player.
打开内置的警告对话框,向玩家显示给定消息。
v2.0.0
: Introduced. v2.0.0
: 引入。message
: (string) The message to display to the player.message
: (字符串) 向玩家显示的消息。options
: (optional, null | object) The options object. See Dialog.open()
for more information.options
: (可选,null | 对象) 选项对象。更多信息请参阅 Dialog.open()
。closeFn
: (optional, null | function) The function to execute whenever the dialog is closed.closeFn
: (可选,null | 函数) 每次对话框关闭时执行的函数。UI.alert("You smell of elderberries!");
UI.restart([options])
Opens the built-in restart dialog, prompting the player to restart the story.
打开内置的重启对话框,提示玩家重新开始故事。
v2.0.0
: Introduced. v2.0.0
: 引入。options
: (optional, null | object) The options object. See Dialog.open()
for more information.options
:(可选,null | 对象)选项对象。有关更多信息,请参阅 Dialog.open()
。UI.restart();
UI.saves([options [, closeFn]])
Opens the built-in saves dialog.
打开内置保存对话框。
v2.0.0
: Introduced. v2.0.0
: 引入。options
: (optional, null | object) The options object. See Dialog.open()
for more information.options
:(可选,null | 对象)选项对象。有关更多信息,请参阅 Dialog.open()
。closeFn
: (optional, null | function) The function to execute whenever the dialog is closed.closeFn
: (可选,null | 函数) 每次对话框关闭时执行的函数。UI.saves();
UI.settings([options [, closeFn]])
Opens the built-in settings dialog, which is populated from the Setting
API.
打开内置设置对话框,该对话框由 Setting
API 填充。
v2.0.0
: Introduced. v2.0.0
: 引入。options
: (optional, null | object) The options object. See Dialog.open()
for more information.options
:(可选,null | 对象)选项对象。有关更多信息,请参阅 Dialog.open()
。closeFn
: (optional, null | function) The function to execute whenever the dialog is closed.closeFn
: (可选,null | 函数) 每次对话框关闭时执行的函数。UI.settings();
UI.update()
Triggers a :uiupdate
event that causes the update of the dynamically updated sections built-in user interface—e.g., those populated by code passages, like StoryCaption
and StoryMenu
. Automatically invoked during passage navigation.
触发一个 :uiupdate
事件,该事件会导致动态更新的内置用户界面的更新——例如,由代码段落填充的 StoryCaption
和 StoryMenu
。在段落导航期间自动调用。
As all dynamically updated sections of the built-in UI are updated, save for the main passage display, it is recommended that this method be used sparingly.
Ideally, if you need to update these sections of the built-in UI outside of the normal passage navigation update, then you should update only the specific areas you need to rather than the entire UI.
理想情况下,如果您需要在正常段落导航更新之外更新内置 UI 的这些部分,则应仅更新所需的特定区域,而不是整个 UI。
v2.37.0
: Introduced. v2.37.0
: 引入。UI.update();
UI.jumpto([options [, closeFn]])
Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。UI.share([options [, closeFn]])
Deprecated:
This method has been deprecated and should no longer be used.
已弃用:此方法已被弃用,不应再使用。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.37.0
: Deprecated. v2.37.0
: 已废弃。UIBar
API UIBar.destroy()
Completely removes the UI bar and all of its associated styles and event handlers.
完全移除 UI 栏及其所有相关样式和事件处理器。
v2.17.0
: Introduced. v2.17.0
: 引入。UIBar.destroy();
UIBar.hide()
→ UIBar
object UIBar.hide()
→ UIBar
对象 Hides the UI bar. Returns a reference to the UIBar
object for chaining.
隐藏 UI 栏。返回 UIBar
对象的引用以进行链式调用。
Note:
This does not reclaim the space reserved for the UI bar. Thus, a call to UIBar.stow()
may also be necessary. Alternatively, if you simply want the UI bar gone completely and permanently, either using UIBar.destroy()
or the StoryInterface
special passage may be a better choice.
注意:这不会回收为 UI 栏保留的空间。因此,可能还需要调用 UIBar.stow()
。或者,如果您只想完全永久地移除 UI 栏,使用 UIBar.destroy()
或 StoryInterface
特殊段落可能是一个更好的选择。
v2.29.0
: Introduced. v2.29.0
: 引入。UIBar.hide();
UIBar.hide().stow();
UIBar.isHidden()
→ boolean UIBar.isHidden()
→ 布尔值 Returns whether the UI bar is currently hidden.
返回 UI 栏当前是否已隐藏。
v2.29.0
: Introduced. v2.29.0
: 引入。if (UIBar.isHidden()) {
/* code to execute if the UI bar is hidden… */
}
if (!UIBar.isHidden()) {
/* code to execute if the UI bar is not hidden… */
}
UIBar.isStowed()
→ boolean UIBar.isStowed()
→ 布尔值 Returns whether the UI bar is currently stowed.
返回 UI 栏当前是否已收起。
v2.29.0
: Introduced. v2.29.0
: 引入。if (UIBar.isStowed()) {
/* code to execute if the UI bar is stowed… */
}
if (!UIBar.isStowed()) {
/* code to execute if the UI bar is not stowed… */
}
UIBar.show()
→ UIBar
object UIBar.show()
→ UIBar
对象 Shows the UI bar. Returns a reference to the UIBar
object for chaining.
显示 UI 栏。返回对 UIBar
对象的引用以进行链式调用。
v2.29.0
: Introduced. v2.29.0
: 引入。UIBar.show();
UIBar.unstow().show();
UIBar.stow([noAnimation])
→ UIBar
object UIBar.stow([noAnimation])
→ UIBar
对象 Stows the UI bar, so that it takes up less space. Returns a reference to the UIBar
object for chaining.
收起 UI 栏,使其占用更少的空间。返回 UIBar
对象的引用以实现链式调用。
v2.17.0
: Introduced. v2.17.0
: 引入。v2.29.0
: Added returned UIBar
chaining reference.v2.29.0
: 添加了返回的 UIBar
链式引用。noAnimation
: (optional, boolean) Whether to skip the default animation.noAnimation
: (可选,布尔值)是否跳过默认动画。UIBar.stow();
UIBar.stow(true);
UIBar.unstow([noAnimation])
→ UIBar
object UIBar.unstow([noAnimation])
→ UIBar
对象 Unstows the UI bar, so that it is fully accessible again. Returns a reference to the UIBar
object for chaining.
解除 UI 栏的锁定,使其再次完全可访问。返回对 UIBar
对象的引用以进行链式调用。
v2.17.0
: Introduced. v2.17.0
: 引入。v2.29.0
: Added returned UIBar
chaining reference.v2.29.0
: 添加了返回的 UIBar
链接引用。noAnimation
: (optional, boolean) Whether to skip the default animation.noAnimation
: (可选,布尔值)是否跳过默认动画。UIBar.unstow();
UIBar.unstow(true);
UIBar.update()
Deprecated:
This method has been deprecated and should no longer be used. See the UI.update()
static method for its replacement.
已弃用:此方法已被弃用,不应再使用。请参阅 UI.update()
静态方法以获取其替代方案。
v2.29.0
: Introduced. v2.29.0
: 引入。v2.37.0
: Deprecated in favor of UI.update()
.UI.update()
。SugarCube preserves the state of the story as it's being played in a number of ways to both prevent the loss of progress and allow players to save stories. This guide will detail how these features work.
SugarCube 通过多种方式保留故事在游玩过程中的状态,以防止进度丢失并允许玩家保存故事。本指南将详细介绍这些功能的工作原理。
The story history is a collection of moments. A new moment is created whenever passage navigation occurs, and only when passage navigation occurs. Each moment contains data regarding the active passage and the state of all story variables—that is, the ones you use the $
sigil to interact with—as they exist when the moment is created. The history allows players to navigate through these moments.
故事历史是一系列时刻的集合。每当进行篇章导航时,就会创建一个新的时刻,并且仅在发生篇章导航时创建。每个时刻都包含有关活动篇章以及所有故事变量(即您使用 $
符号与之交互的变量)的数据,这些数据是在时刻创建时存在的。历史记录允许玩家在这些时刻之间导航。
The number of moments contained within the story history is, generally, limited, via the Config.history.maxStates
setting. As new moments are added, older moments that exceed the maximum number are expired in order of age, oldest first. Expired moments are recorded in a separate expired collection and can no longer be navigated to. If you limit the moments within the history to 1
, via setting Config.history.maxStates
to 1
, then there will only ever be one moment in the history, but passage navigation is still required for new moments to be created.
故事历史中包含的时刻数量通常受 Config.history.maxStates
设置限制。添加新时刻时,超出最大数量的较旧时刻将按年龄顺序(最老先)过期。过期的时刻将被记录在单独的过期集合中,并且无法再进行导航。如果您通过将 Config.history.maxStates
设置为 1
来限制历史中的时刻为 1
,那么历史中将始终只有一个时刻,但创建新时刻仍需要通过篇章导航。
Note:
All user functions and macros that check for the existence of moments within the history check both the story history and expired moments, so will work as expected even if the history is limited to a single moment as described above.
注意:所有检查历史中是否存在时刻的用户函数和宏都会同时检查故事历史和已过期的时刻,因此即使历史仅限于上述描述的单个时刻,也能按预期工作。
Saving the story records the story's state up until the last moment that was created. This is not necessarily the same as the current state of the story: because moment creation is tied to passage navigation, changes that occur between one passage navigation and the next are not part of the current moment and will not be preserved by a moment until the next navigation, when the next moment is created.
保存故事记录了故事到最后创建的那个时刻的状态。这不一定与故事的当前状态相同:因为时刻的创建与篇章导航相关联,两个篇章导航之间发生的变化不属于当前时刻,并且直到下一次导航、下一个时刻创建时,这些变化才不会被时刻保留。
Consider the following: 考虑以下情况:
:: one passage
<<set $var to 1>>
[[another passage]]
:: another passage
<<link "Click me!">>
<<set $var to 2>>
<</link>>
In the above example, if you save the story after reaching the passage called another passage
, the $var
variable will be saved in the state as 1
, as you would expect. If you click the link that sets the variable to 2
, and then save the story, the $var
variable will still be saved as 1
, because a new moment has not yet been created.
在上面的例子中,如果您在达到名为 another passage
的段落后保存故事, $var
变量将按预期保存为 1
状态。如果您点击将变量设置为 2
的链接,然后保存故事, $var
变量仍然会保存为 1
,因为尚未创建新的时刻。
Note:
Auto saves are occasionally confused with the playthrough session, but they are in fact distinct systems.
备注:自动保存有时会被误认为是游戏试玩会话,但实际上它们是不同的系统。
SugarCube automatically stores the current playthrough state to the browser's session storage whenever a new moment is created. This can be thought of as a special, temporary saved story, which is automatically deleted after the player's current browsing session ends. This temporary playthrough session is intended to prevent players from losing data. Some browsers, particularly mobile ones, will free up memory by unloading web pages that are running in the background. This functionally refreshes the webpage, and can cause users to lose their progress. When SugarCube is reloaded by the browser, it checks if a playthrough session exists and loads it to prevent any inadvertent loss of progress.
SugarCube 在创建新时刻时,会自动将当前游戏试玩状态存储到浏览器的会话存储中。这可以被视为一个特殊的、临时的保存故事,在玩家当前浏览会话结束后会自动删除。这个临时的游戏试玩会话旨在防止玩家丢失数据。一些浏览器,尤其是移动浏览器,会通过卸载后台运行的网页来释放内存。这实际上会刷新网页,并可能导致用户丢失进度。当浏览器重新加载 SugarCube 时,它会检查是否存在游戏试玩会话,并将其加载以防止意外丢失进度。
This feature also prevents players from losing progress if they try to use the browser back and forward buttons to navigate, or if they refresh their browser for any reason. The built-in Restart
button, along with the methods UI.restart()
and Engine.restart()
are provided so that the story can be restarted without restoring a session.
此功能还可以防止玩家在尝试使用浏览器的前进和后退按钮导航或因任何原因刷新浏览器时丢失进度。内置的 Restart
按钮以及 UI.restart()
和 Engine.restart()
方法提供,以便可以在不恢复会话的情况下重新开始故事。
To recap: 回顾:
Note:
A playthrough session is occasionally confused with auto saves, but they are in fact distinct systems.
注意:有时玩家游玩会与自动保存混淆,但实际上它们是不同的系统。
SugarCube features configurable auto saves. Auto saves are otherwise normal browser saves that automatically save either on every turn or only on certain turns, depending on how they're configured.
SugarCube 具有可配置的自动保存功能。自动保存通常是浏览器自动保存,可以在每回合或根据配置只在特定回合自动保存。
See:
Config.saves.maxAutoSave
setting, Config.saves.isAllowed
setting, and Save.browser.auto
API.
查看: Config.saves.maxAutoSave
设置, Config.saves.isAllowed
设置,和 Save.browser.auto
API。
When a save is loaded, the state loaded from the save replaces the current state. This process is the same regardless of where the loaded state is coming from, be it a save or the playthrough session. The previous state is completely lost—the new state is not added to or combined with the current state, instead it replaces it in its entirety. The easiest way to understand this is to look at what happens when you make some changes to StoryInit
and then load a save from before those changes were made. For example:
当加载存档时,从存档加载的状态将替换当前状态。这个过程无论加载的状态来自哪里都是一样的,无论是存档还是游戏进程。之前的状态将完全丢失——新的状态不会添加或合并到当前状态中,而是完全替换。要理解这一点,最简单的方法是看看你在修改 StoryInit
之后,然后加载一个在修改之前所做的存档会发生什么。例如:
:: StoryInit
<<set $x to 0>>
:: Start
$$x is <<if def $x>> $x <<else>> undefined <</if>>
If you run the above, you'll see $x is 0
. Create a save, then edit the code as follows:
如果你运行上述代码,你会看到 $x is 0
。创建一个存档,然后按照以下方式编辑代码:
:: StoryInit
<<set $x to 0>>
<<set $y to 1>>
:: Start
$$x is <<if def $x>> $x <<else>> undefined <</if>>
$$y is <<if def $y>> $y <<else>> undefined <</if>>
Running that, you'll see $x is 0
and $y is 1
. Now, load the save from before the changes were made, and you'll see $y is undefined
, since it doesn't exist at all in the loaded state.
运行后,您将看到 $x is 0
和 $y is 1
。现在,加载更改之前的存档,您将看到 $y is undefined
,因为它在加载的状态中根本不存在。
Whenever your story is first started or, for any reason, restarted—e.g., the browser window/tab was refreshed/reloaded—it undergoes its startup sequence. Several things occur each and every time startup happens, regardless of whether or not a playthrough session will be restored or the starting passage run. First, the CSS, JavaScript, and Widget sections are processed. Next, any init
-tagged passages and the StoryInit
special passage are processed. Finally, one of two things happen (in order): the existing playthrough session is restored, if it exists, elsewise the starting passage is run.
无论故事是首次启动还是由于任何原因重新启动——例如浏览器窗口/标签页刷新/重新加载——它都会执行启动序列。每次启动时都会发生几件事情,无论是否恢复游戏会话或运行起始段落。首先,处理 CSS、JavaScript 和 Widget 部分。接下来,处理任何带有 init
标签的段落和 StoryInit
特殊段落。最后,按顺序发生以下两种情况之一:如果存在,则恢复现有的游戏会话,否则运行起始段落。
Some users have the false impression that StoryInit
is not run when the story is restarted when the playthrough session is restored or autosave is loaded. Code like <<set $y to 1>>
seems to have no effect because the startup state is replaced by the of the incoming state, but they are still executed by the engine. You can see this effect by changing data outside the state. For example, let's return to the example above and change it again:
一些用户有一种错误印象,即当恢复游戏会话或自动保存时,故事重新启动时不会运行 StoryInit
。像 <<set $y to 1>>
这样的代码似乎没有效果,因为启动状态被传入的状态所取代,但它们仍然由引擎执行。您可以通过更改状态之外的数据来看到这种效果。例如,让我们回到上面的例子,并再次更改它:
:: StoryInit
<<set $x to 0>>
<<set setup.y to 1>>
:: Start
$$x is <<if def $x>> $x <<else>> undefined <</if>>
setup.y is <<if def setup.y>> <<= setup.y>> <<else>> undefined <</if>>
You'll see that setup.y
is being set to 1
and displayed properly regardless of whether you load a save or not, because it is not part of the state.
无论是否加载存档,您都会看到 setup.y
被设置为 1
并正确显示,因为它不属于状态的一部分。
When the story is restarted by SugarCube rather than refreshed via the browser, the playthrough session, if any, is not loaded. The CSS, JavaScript, & Widget sections, any init
-tagged passages, and the StoryInit
special passage are processed, as usual, and then the starting passage is rendered.
当故事由 SugarCube 重新启动而不是通过浏览器刷新时,如果有的话,游戏会话不会被加载。CSS、JavaScript 和 Widget 部分,任何 init
标签的段落以及 StoryInit
特殊段落会像往常一样处理,然后渲染起始段落。
As a basic working definition, non-generic object types—i.e., classes—are instantiable objects whose own prototype is not Object
—e.g., Array
is a native non-generic object type.
作为基本的工作定义,非通用对象类型(即类)是可以实例化的对象,其原型不是 Object
——例如, Array
是一个本地的非通用对象类型。
Many of the commonly used native non-generic object types are already fully compatible with and supported for use within story variables—e.g., Array
, Date
, Map
, and Set
. All other non-generic object types, on the other hand, must be made compatible to be successfully stored within story variables.
许多常用的原生非泛型对象类型已经完全兼容并支持在故事变量中使用——例如, Array
、 Date
、 Map
和 Set
。另一方面,所有其他非泛型对象类型,必须进行兼容性处理才能成功存储在故事变量中。
Making custom non-generic object types fully compatible requires that two methods be added to their prototype, .clone()
and .toJSON()
, to support cloning—i.e., deep copying—instances of the type.
制作与通用对象类型完全兼容的自定义对象类型需要向它们的原型中添加两个方法, .clone()
和 .toJSON()
,以支持克隆(即深度复制)该类型的实例。
.clone()
method needs to return a clone of the instance..clone()
方法需要返回实例的克隆。.toJSON()
method needs to return a code string that when evaluated will return a clone of the instance..toJSON()
方法需要返回一个代码字符串,当执行时将返回实例的克隆。In both cases, since the end goal is roughly the same, this means creating a new instance of the base object type and populating it with clones of the original instance's data. There is no one size fits all example for either of these methods because an instance's properties, and the data contained therein, are what determine what you need to do.
在这两种情况下,由于最终目标大致相同,这意味着创建一个新的基对象类型的实例,并用原始实例数据的克隆填充它。对于这两种方法,没有一种通用的示例,因为实例的属性以及其中包含的数据决定了你需要做什么。
See Also:
The Serial.createReviver()
method for additional information on implementing the .toJSON()
method.
参考信息:有关实现 .toJSON()
方法的更多信息,请参阅 Serial.createReviver()
方法。
class
-based syntax (newer, preferred) class
的语法(较新,推荐)Here's a simple example whose constructor takes a single configuration object parameter:
这里有一个简单的示例,其构造函数接受单个配置对象参数:
window.Character = class Character {
constructor(config) {
// Set up our own data properties with some defaults.
this.name = '(none)';
this.race = '(none)';
this.st = 10;
this.dx = 10;
this.iq = 10;
this.ht = 10;
this.hp = 10;
// Clone the given config object's own properties into our own properties.
//
// NOTE: We use the SugarCube built-in `clone()` function to make deep
// copies of each of the properties' values.
Object.keys(config).forEach(prop => {
this[prop] = clone(config[prop]);
});
}
clone() {
// Return a new instance containing our own data.
return new this.constructor(this);
}
toJSON() {
// Return a code string that will create a new instance containing our
// own data.
//
// NOTE: Supplying `this` directly as the `reviveData` parameter to the
// `Serial.createReviver()` call will trigger out of control recursion in
// the serializer, so we must pass it a clone of our own data instead.
var ownData = {};
Object.keys(this).forEach(prop => {
ownData[prop] = clone(this[prop]);
});
return Serial.createReviver(`new ${this.constructor.name}($ReviveData$)`, ownData);
}
};
Creating a new instance of this Character
example would be something like:
创建此 Character
示例的新实例可能如下所示:
<<set $Joe to new Character({
name : 'Joe the Barbarian',
race : 'human',
st : 20,
dx : 12,
iq : 9,
ht : 18,
hp : 18
})>>
Here's a simple example whose constructor takes multiple discrete parameters:
这是一个简单的示例,其构造函数接受多个离散参数:
window.Character = class Character {
constructor(
name,
race,
st,
dx,
iq,
ht,
hp
) {
// Set up our own data properties with the given values or defaults.
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 a new instance containing our own data.
return new this.constructor(
this.name,
this.race,
this.st,
this.dx,
this.iq,
this.ht,
this.hp
);
}
toJSON() {
// Return a code string that will create a new instance containing our
// own data.
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)
));
}
};
Creating a new instance of this Character
example would be something like:
创建此 Character
示例的新实例可能如下所示:
<<set $Joe to new Character(
'Joe the Barbarian',
'human',
20,
12,
9,
18,
18
)>>
function
-based syntax (classic, not recommended) function
的语法(经典,不推荐)Here's a simple example whose constructor takes a single configuration object parameter:
这里有一个简单的示例,其构造函数接受单个配置对象参数:
window.Character = function Character(config) {
// Set up our own data properties with some defaults.
this.name = '(none)';
this.race = '(none)';
this.st = 10;
this.dx = 10;
this.iq = 10;
this.ht = 10;
this.hp = 10;
// Clone the given config object's own properties into our own properties.
//
// NOTE: We use the SugarCube built-in `clone()` function to make deep
// copies of each of the properties' values.
Object.keys(config).forEach(function (prop) {
this[prop] = clone(config[prop]);
}, this);
};
Character.prototype.clone = function () {
// Return a new instance containing our own data.
return new Character(this);
};
Character.prototype.toJSON = function () {
// Return a code string that will create a new instance containing our
// own data.
//
// NOTE: Supplying `this` directly as the `reviveData` parameter to the
// `Serial.createReviver()` call will trigger out of control recursion in
// the serializer, so we must pass it a clone of our own data instead.
var ownData = {};
Object.keys(this).forEach(function (prop) {
ownData[prop] = clone(this[prop]);
}, this);
return Serial.createReviver('new Character($ReviveData$)', ownData);
};
Creating a new instance of this Character
example would be something like:
创建此 Character
示例的新实例可能如下所示:
<<set $Joe to new Character({
name : 'Joe the Barbarian',
race : 'human',
st : 20,
dx : 12,
iq : 9,
ht : 18,
hp : 18
})>>
Here's a simple example whose constructor takes multiple discrete parameters:
这是一个简单的示例,其构造函数接受多个离散参数:
window.Character = function (
name,
race,
st,
dx,
iq,
ht,
hp
) {
// Set up our own data properties with the given values or defaults.
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 a new instance containing our own data.
return new Character(
this.name,
this.race,
this.st,
this.dx,
this.iq,
this.ht,
this.hp
);
};
Character.prototype.toJSON = function () {
// Return a code string that will create a new instance containing our
// own data.
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)
));
};
Creating a new instance of this Character
example would be something like:
创建此 Character
示例的新实例可能如下所示:
<<set $Joe to new Character(
'Joe the Barbarian',
'human',
20,
12,
9,
18,
18
)>>
This is a collection of tips, from how-tos to best practices.
这是一系列提示,从入门到最佳实践。
Suggestions for new entries may be submitted by creating a new issue at SugarCube's source code repository.
可以通过在 SugarCube 的源代码仓库中创建新问题来提交新条目的建议。
Warning:
Navigating back to a previous passage, for whatever reason, can be problematic. There's no way for the system to know ahead of time whether it's safe to re-execute a passage's contents. Even if it did know that, there's no way for it to know which operations may or may not have side-effects—e.g., changing variables. Thus, if you allow players to return to passages, then you should either: ensure the passages contain no code that has side-effects or wrap that code in something to prevent re-execution—e.g., <<if visited() is 1>>side-effects<</if>>
.
警告:无论出于何种原因返回到之前的段落都可能存在问题。系统无法提前知道是否可以重新执行段落的全部内容。即使它知道,也无法知道哪些操作可能或可能不会产生副作用——例如,更改变量。因此,如果您允许玩家返回到段落,那么您应该确保段落不包含具有副作用的代码,或者将代码包裹在防止重新执行的内容中——例如, <<if visited() is 1>>side-effects<</if>>
。
Note:
An alternative to navigating to passages to create menus, inventories, and the like would be to use the Dialog
API.
注意:创建菜单、存货等内容的另一种方法是使用 Dialog
API。
When you have a situation where you're using a set of passages as some kind of menu/inventory/etc and it's possible for the player to interact with several of those passages, or even simply the same one multiple times, then returning them to the passage they were at before entering the menu can be problematic as they're possibly several passages removed from that originating passage—thus, the <<return>>
macro and link constructs like [[Return|previous()]]
will not work.
当您遇到使用一系列段落作为某种菜单/库存等的情况,并且玩家可以与这些段落中的多个进行交互,或者甚至简单地多次与同一个进行交互时,将它们返回到进入菜单之前所在的段落可能会出现问题,因为它们可能已经远离了原始段落——因此, <<return>>
宏和类似 [[Return|previous()]]
的链接结构将无法正常工作。
The most common way to resolve this arbitrarily long return issue is to use a bit of JavaScript to record the last non-menu passage the player visited into a story variable and then to create a link with that.
最常见解决这种任意长返回问题的方法是使用一点 JavaScript 将玩家最后访问的非菜单段落记录到故事变量中,然后创建一个链接指向它。
For instance, you may use one of the following examples—they both do the same thing—to record the last non-menu passage into the $return
story variable.
例如,您可以使用以下示例之一——它们都执行相同的功能——将最后一个非菜单段落记录到 $return
故事变量中。
Via JavaScript (Twine 2: the Story JavaScript, Twine 1/Twee: a script
-tagged passage)
通过 JavaScript(Twine 2:故事 JavaScript,Twine 1/Twee:带有 script
标签的段落)
$(document).on(':passagestart', function (ev) {
if (!ev.passage.tags.includes('noreturn')) {
State.variables.return = ev.passage.name;
}
});
Via macros (best used in the PassageReady
special passage)
通过宏(最好用于 PassageReady
特殊段落)
<<if not tags().includes("noreturn")>>
<<set $return to passage()>>
<</if>>
You'll need to tag each and every one of your menu passages with noreturn
—you may use any tag you wish (e.g., menu
, inventory
), just ensure you change the name in the code if you decide upon another. If necessary, you may also use multiple tags by switching from <Array>.includes()
to <Array>.includesAny()
in whichever of the above examples you choose to use.
您需要为每个菜单段落都加上 noreturn
标签——您可以使用任何您想要的标签(例如, menu
、 inventory
),只需确保如果您决定使用另一个名称,则在代码中更改名称即可。如果需要,您还可以使用多个标签,通过在上面的示例中选择使用的方式在 <Array>.includes()
和 <Array>.includesAny()
之间切换。
In your menu passages, your long return links will simply reference the $return
story variable, like so:
在您的菜单段落中,您的长返回链接将简单地引用 $return
故事变量,如下所示:
→ Using link markup
[[Return|$return]]
→ Using <<link>> macro (separate argument form)
<<link "Return" $return>><</link>>
Warning (Twine 2):
Due to how the Twine 2 automatic passage creation feature currently works, using the link markup form will cause a passage named $return
to be created that will need to be deleted. To avoid this problem, it's suggested that you use the separate argument form of the <<link>>
macro in Twine 2—as shown above.
警告(TWINE 2):由于 Twine 2 自动创建段落功能当前的工作方式,使用链接标记形式将导致创建名为 $return
的段落,该段落需要删除。为了避免这个问题,建议您使用 Twine 2 中 <<link>>
宏的单独参数形式,如上所示。
Media passages are simply a way to embed media into your project—specially tagged passages that contain the data URI of a Base64-encoded media source. Audio, image, video, and VTT passages are supported.
媒体段落只是将媒体嵌入到您的项目中的简单方式——特别标记的段落,其中包含 Base64 编码的媒体源的数据 URI。支持音频、图像、视频和 VTT 段落。
For example, the following is the data URI of a Base64-encoded PNG image of a red dot ():
例如,以下是一个红色圆点的 Base64 编码 PNG 图像的数据 URI( ):
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHE
lEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
v2.0.0
: Image passages. v2.0.0
:图像段落。v2.24.0
: Added audio, video, and VTT passages.v2.24.0
:添加了音频、视频和 VTT 段落。Generally, it's expected that you will use a compiler that supports the automatic creation of media passages, however, they may be created manually.
通常情况下,您应使用支持自动创建媒体段落的编译器,尽管它们也可以手动创建。
Compilers supporting automatic creation of media passages:
支持自动创建媒体段落的编译器:
Warning (Twine 2):
Due to various limitations in its design, if you're using Twine 2 as your IDE/compiler, then it is strongly recommended that you do not create more than a few media passages and definitely do not use large sources.
警告(TWINE 2):由于设计中的各种限制,如果您使用 Twine 2 作为您的 IDE/编译器,那么强烈建议您不要创建过多的媒体段落,并且绝对不要使用大量资源。
To manually create a media passage:
要手动创建媒体段落:
See the MDN article Media formats for HTML audio and video for more information on formats commonly supported in browsers—pay special attention to the Browser compatibility section.
有关浏览器支持的常见格式,请参阅 MDN 文章《HTML 音频和视频媒体格式》——特别关注浏览器兼容性部分。
Note:
As with all special tags, media passage tags are case sensitive, so their spelling and capitalization must be exactly as shown.
注意:与所有特殊标签一样,媒体段落标签是区分大小写的,因此它们的拼写和大小写必须与显示的完全一致。
Passage type 文本类型 | Tag 标签 |
---|---|
Audio passage 音频段落 | Twine.audio |
Image passage 图片段落 | Twine.image |
Video passage 视频段落 | Twine.video |
VTT passage VTT 段落 | Twine.vtt |
This guide is a reference to the icon font used by SugarCube, sc-icons
.
本指南是关于 SugarCube 所使用的图标字体的参考, sc-icons
。
The sc-icons
font is a custom subset of Font Awesome Free (Solid) v5.15.2 (https://fontawesome.com), which is licensed under the SIL OFL 1.1 (https://scripts.sil.org/OFL).
sc-icons
字体是 Font Awesome Free (Solid) v5.15.2 的自定义子集(https://fontawesome.com),该字体受 SIL OFL 1.1 许可(https://scripts.sil.org/OFL)的约束。
The following CSS properties should used with any icon style rule.
以下 CSS 属性应与任何图标样式规则一起使用。
font-family: sc-icons !important;
font-style: normal;
font-weight: normal;
font-variant: normal;
line-height: 1;
speak: never;
text-rendering: auto;
text-transform: none;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
Each icon's hexadecimal reference ID is listed below it. How to use the reference IDs varies based on where you're using them.
每个图标的十六进制引用 ID 列在其下方。使用引用 ID 的方法取决于您使用它们的场景。
\u
. E.g., \uf004
.\u
开头。例如, \uf004
。\
. E.g., \f004
.\
。例如, \f004
。&#x
and append ;
. E.g., 
.&#x
,后缀为 ;
。例如, 
。f002
f004
f005
f00c
f00d
f00e
f010
f011
f013
f015
f019
f023
f026
f027
f028
f02e
f048
f049
f04a
f04b
f04c
f04d
f04e
f050
f051
f052
f053
f054
f055
f056
f057
f058
f059
f05a
f05e
f060
f061
f062
f063
f065
f066
f067
f068
f06a
f06e
f070
f071
f077
f078
f089
f08d
f093
f09c
f0a0
f0c1
f0c2
f0c7
f0c9
f0d0
f0d7
f0d8
f0d9
f0da
f0e7
f0eb
f0fe
f10d
f10e
f110
f127
f137
f138
f139
f13a
f13e
f141
f142
f144
f146
f14a
f150
f151
f152
f185
f186
f188
f191
f1ab
f1dd
f1e0
f1f8
f204
f205
f240
f241
f242
f243
f244
f28b
f28d
f2ea
f2ed
f2f1
f2f9
f31e
f35d
f381
f382
f410
f55a
f56d
f56e
f56f
f574
f5c0
f6a9
f78c
f7d9
f829
f82a
There are many differences between Harlowe and SugarCube, this guide will document some of the most critical you will need to account for if you're coming to SugarCube from a background in Harlowe.
Harlowe 与 SugarCube 之间有许多差异,本指南将记录一些如果你从 Harlowe 背景转向 SugarCube 时需要考虑的最重要的差异。
Aside from general syntax, SugarCube macros do not use hooks, separate arguments differently, and don't allow other macros to be passed as arguments.
除了通用语法外,SugarCube 宏不使用钩子,参数区分方式不同,也不允许将其他宏作为参数传递。
Like in Harlowe, some SugarCube macros accept expressions and others accept discreet arguments. In SugarCube, discreet arguments passed to a macro are separated by spaces instead of commas. To pass expressions or the results of functions to macros as an argument, you must wrap the expression in backquotes (`
).
与 Harlowe 类似,一些 SugarCube 宏接受表达式,而另一些接受离散参数。在 SugarCube 中,传递给宏的离散参数由空格而不是逗号分隔。要将表达式或函数的结果作为参数传递给宏,必须将表达式用反引号(` `
`)括起来。
Additionally, macros in SugarCube do not return values, so macros cannot be used as arguments to other macros. SugarCube provides a variety of functions and methods that may be used instead, and standard JavaScript functions and methods may also be used.
此外,SugarCube 中的宏不返回值,因此宏不能用作其他宏的参数。SugarCube 提供各种函数和方法供替代使用,也可以使用标准的 JavaScript 函数和方法。
Consider the following Harlowe code:
考虑以下 Harlowe 代码:
(link-goto: "Go somewhere else", (either: "this passage", "that passage", "the other passage"))
A version of the above code in SugarCube might look like this:
上述代码在 SugarCube 中的版本可能如下所示:
<<link "Go somewhere else" `either("this passage", "that passage", "the other passage")`>><</link>>
See: Macro Arguments. 参见:宏参数。
Where Harlowe uses its hook syntax (square brackets) to associate a macro with its contents, SugarCube instead uses "container" macros—macros that can have content associated with them have opening and closing tags.
与 Harlowe 使用钩子语法(方括号)将宏与其内容关联不同,SugarCube 使用“容器”宏——可以关联内容的宏具有开标签和闭标签。
Consider the following Harlowe code:
考虑以下 Harlowe 代码:
(if: $var is 1)[
The variable is 1.
]
In SugarCube, you instead open and close the <<if>>
macro itself:
在 SugarCube 中,你而是打开和关闭 <<if>>
宏本身:
<<if $var is 1>>
The variable is 1.
<</if>>
Some macros in Harlowe and SugarCube share a name but work a bit differently. We'll cover some of these differences below.
一些 Harlowe 和 SugarCube 中的宏名称相同,但工作方式略有不同。以下我们将介绍其中的一些差异。
SugarCube does not have any equivalents to Harlowe's (click:)
family of macros. Additionally, SugarCube's normal <<link>>
macro does not have an output element associated with it and is not, by default, a single-use link like its Harlowe equivalent. Both of these features can be constructed in SugarCube, however, using macros like <<linkreplace>>
or by combining <<link>>
macros with DOM macros. Additionally, SugarCube's link macro accepts a passage argument, that, if included, turns any <<link>>
into something similar to Harlowe's (link-goto:)
macro.
SugarCube 没有与 Harlowe 的 (click:)
宏系列等效的功能。此外,SugarCube 的常规 <<link>>
宏没有与之关联的输出元素,并且默认情况下,它不像 Harlowe 的等效宏那样是一个单次使用的链接。然而,在 SugarCube 中,可以使用 <<linkreplace>>
宏或通过组合 <<link>>
宏与 DOM 宏来构建这两个功能。此外,SugarCube 的链接宏接受一个段落参数,如果包含该参数,则任何 <<link>>
都会变成类似于 Harlowe 的 (link-goto:)
宏。
Consider the following Harlowe link 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")
The equivalent SugarCube code for each link might look something like this:
每个链接的等效 SugarCube 代码可能看起来像这样:
<<linkreplace "Hey there.">>Hay is for horses.<</linkreplace>>
<<link "Get some money">><<set $cash += 1>><</link>>
<<link "Move on" "next passage">><</link>>
SugarCube's <<link>>
and <<button>>
macros can also accept the link markup as an argument:
SugarCube 的 <<link>>
和 <<button>>
宏也可以接受链接标记作为参数:
<<link [[Move on|next passage]]>><</link>>
Note:
Harlowe refers to these as "revision macros".
注意:Harlowe 将这些称为“修订宏”。
SugarCube's DOM macros can target any HTML element on the page, not just hooks, and unlike their Harlowe equivalents, they cannot target arbitrary strings. You can use custom style markup or HTML to create the elements, and then target them with a query selector.
SugarCube 的 DOM 宏可以针对页面上的任何 HTML 元素,而不仅仅是钩子,并且与 Harlowe 的等价物不同,它们不能针对任意字符串。您可以使用自定义样式标记或 HTML 来创建元素,然后使用查询选择器来定位它们。
Consider the following Harlowe code:
考虑以下 Harlowe 代码:
(set: _greetings to (a: "hi", "hello", "good day", "greetings"))\
The man says, "|target>[(either: ..._greetings)]."
{
(link-repeat: "Change")[
(replace: ?target)[(either: ..._greetings)]
]
}
The equivalent SugarCube code to achieve a similar result would be:
实现类似效果的 SugarCube 代码如下:
<<set _greetings to ["hi", "hello", "good day", "greetings"]>>\
The man says, "@@#target;<<= _greetings.random()>>@@."
<<link "Change">>
<<replace "#target">><<= _greetings.random()>><</replace>>
<</link>>
Note:
The DOM macros do have a limitation that you should familiarize yourself with.
注意:DOM 宏确实存在一些限制,您应该熟悉这些限制。
Harlowe's implementation of the (goto:)
macro terminates the rendering passage. In SugarCube, the passage is not terminated, and anything in the code below the <<goto>>
macro will have side effects.
Harlowe 对 (goto:)
宏的实现会终止渲染段落。在 SugarCube 中,段落不会被终止,并且 <<goto>>
宏下面的代码将产生副作用。
Consider this Harlowe code:
考虑以下 Harlowe 代码:
:: some passage
(set: $count to 0)
(goto: "next")
(set: $count to it + 1)
:: next
$count <!-- 0 -->
In the above, the second (set:)
macro is never run, and the $count
variable remains at 0.
在上面,第二个 (set:)
宏从未运行,而 $count
变量保持为 0。
The equivalent SugarCube code works a bit differently:
相应的 SugarCube 代码工作方式略有不同:
:: some passage
<<set $count to 0>>
<<goto "next">>
<<set $count += 1>>
:: next
$count /* 1 */
SugarCube does not terminate the parsing of the calling passage, so some care is required when calling <<goto>>
.
SugarCube 不会终止调用段落的解析,因此在调用 <<goto>>
时需要一些小心。
As with <<link>>
and <<button>>
, <<goto>>
can accept link markup as its argument:
与 <<link>>
和 <<button>>
一样, <<goto>>
可以接受链接标记作为其参数:
<<goto [[next]]>>
SugarCube's user input macros, like <<textbox>>
, cannot be nested inside a <<set>>
macro, as you might do with a (prompt:)
and a (set:)
in Harlowe. Instead, the macro is passed a receiver variable which is set to the value input by the user.
SugarCube 的用户输入宏,如 <<textbox>>
,不能嵌套在 <<set>>
宏内部,就像在 Harlowe 中的 (prompt:)
和 (set:)
一样。相反,该宏会传递一个接收器变量,该变量设置为用户输入的值。
For example, if you wanted to ask the user to enter a name, your code may look like this in Harlowe:
例如,如果您想要求用户输入一个名字,您的代码在 Harlowe 中可能看起来像这样:
(set: $name to (prompt: "What is your name?", "Frank"))
In SugarCube, you would likely want to use the <<textbox>>
macro instead, and pass $name
in as the receiving variable:
在 SugarCube 中,您可能会想使用 <<textbox>>
宏,并将 $name
作为接收变量传入:
<label>What is your name? <<textbox "$name" "Frank">></label>
Harlowe's newer input macros, like (dropdown:)
and (cycling-link:)
use "bound" variables, which are similar in concept to SugarCube's receiver variables.
Harlowe 的新输入宏,如 (dropdown:)
和 (cycling-link:)
使用“绑定”变量,其概念与 SugarCube 的接收器变量类似。
Harlowe's implementation of data types differs significantly from SugarCube's. A data type refers to the "type" of data a variable is holding, such as a number, a string, an array, or anything else. Harlowe has stricter typing than SugarCube, requiring authors to call macros like (str:)
or (num:)
on variables to change their type. SugarCube, like JavaScript, uses dynamic typing.
Harlowe 对数据类型的实现与 SugarCube 有显著差异。数据类型指的是变量所持有的“类型”,例如数字、字符串、数组或其他任何类型。Harlowe 的类型检查比 SugarCube 更严格,要求作者在变量上调用宏如 (str:)
或 (num:)
来更改其类型。SugarCube 与 JavaScript 一样,使用动态类型。
SugarCube, like JavaScript, will try to make sense of expressions passed to it by coercing their values if necessary:
SugarCube 与 JavaScript 一样,会尝试理解传递给它的表达式,并在必要时强制转换其值:
<<set $number to 1>>
<<set $string to "2">>
<<= $string + $number>> /* "21" */
In the above case, since the string value "2"
cannot be added to a number value, the number value is coerced into a string, and the two strings are then concatenated. In Harlowe, the same operation will yield an error:
在上述情况下,由于字符串值 "2"
不能添加到数值中,数值会被强制转换为字符串,然后两个字符串被连接起来。在 Harlowe 中,相同的操作将导致错误:
(set: $number to 1)
(set: $string to "2")
(print: $string + $number) <!-- error! -->
You must convert the values to the same type in Harlowe. In SugarCube you can convert them if you need to.
您必须在 Harlowe 中将值转换为相同的类型。在 SugarCube 中,如果需要,您可以进行转换。
In Harlowe: 在 Harlowe 中:
(set: $number to 1)
(set: $string to "2")
(print: $string + $number) <!-- error! -->
(print: $string + (str: $number)) <!-- "21" -->
(print: (num: $string) + $number) <!-- 3 -->
In SugarCube: 在 SugarCube:
<<set $number to 1>>
<<set $string to "2">>
<<= $string + $number>> /* "21" */
<<= $string + String($number)>> /* "21" */
<<= Number($string) + $number>> /* 3 */
Harlowe's arrays, datamaps, and datasets are functionally similar to JavaScript Array
s, Map
s, and Set
s, but with a few key differences. SugarCube requires authors to define and work with these data types using the standard JavaScript methods rather than providing macros for them.
Harlowe 中的数组、数据映射和数据集在功能上类似于 JavaScript 中的 Array
s、 Map
s 和 Set
s,但有一些关键区别。SugarCube 要求作者使用标准的 JavaScript 方法来定义和操作这些数据类型,而不是提供宏来处理它们。
Using an array in Harlowe:
在 Harlowe 中使用数组:
(set: $array to (a:))
(set: $array to it + (a: "something"))
(if: $array contains "something")[…]
In SugarCube: 在 SugarCube 中:
<<set $array to []>>
<<run $array.push("something")>>
<<if $array.includes("something")>>…<</if>>
Using a datamap in Harlowe:
使用 Harlowe 中的数据映射:
(set: $map to (dm: "key", "value"))
(set: $map's key to "another value")
(if: $map contains key)[…]
In SugarCube: 在 SugarCube:
<<set $map to new Map([["key", "value"]])>>
<<run $map.set("key", "another value")>>
<<if $map.has("key")>>…<</if>>
SugarCube also allows the use of JavaScript generic objects, which may be better in some situations than a map:
SugarCube 还允许使用 JavaScript 泛型对象,在某些情况下可能比映射更好
<<set $object to { key : "value" }>>
<<set $object.key to "another value">>
<<if $object.hasOwnProperty("key")>>…<</if>>
Another important difference in the way Harlowe handles its non-primitive data types like arrays, datamaps, and datasets is that they are passed by value rather than passed by reference.
Harlowe 处理其非原始数据类型(如数组、数据映射和数据集)的重要区别在于,它们是通过值传递而不是通过引用传递。
Consider the following Harlowe code:
考虑以下 Harlowe 代码:
(set: $player to (dm: "hp", 100, "mp", 50))
(set: $partyMember to $player)
(set: $partyMember's hp to it - 50)
(print: $player's hp) <!-- 100 -->
(print: $partyMember's hp) <!-- 50 -->
As you can see, Harlowe creates a deep copy/clone of its non-primitive data types each time they're modified.
如您所见,Harlowe 每次修改其非原始数据类型时都会创建其深拷贝/克隆。
In SugarCube, both variables would still point to the same underlying object—at least initially (see below):
在 SugarCube 中,这两个变量仍然会指向同一个底层对象——至少最初是这样的(见下文):
<<set $player to { hp : 100, mp : 50 }>>
<<set $partyMember to $player>>
<<set $partyMember.hp -= 50>>
$player.hp /* 50 */
$partyMember.hp /* 50 */
SugarCube does eventually clone its non-primitive data types as well, but does at the start of passage navigation, rather than each time they're modified.
SugarCube 最终也会克隆其非原始数据类型,但这是在篇章导航开始时,而不是每次修改时。
v2.2.0
: Introduced. v2.2.0
: 引入。In test mode, SugarCube will wrap all macros, and some non-macro markup—e.g., link & image markup—within additional HTML elements, called "debug views" ("views" for short). Views make their associated code visible, thus providing onscreen feedback—they may also be hovered over which, generally, exposes additional information about the underlying code.
在测试模式下,SugarCube 会将所有宏以及一些非宏标记(例如链接和图片标记)包裹在额外的 HTML 元素中,这些元素被称为“调试视图”(简称“视图”)。视图使相关代码可见,从而提供屏幕反馈——也可以悬停查看,通常可以显示有关底层代码的更多信息。
Warning:
Because of the additional HTML elements added by the debug views, some nested markup and selectors may be broken. This only affects test mode.
警告:由于调试视图添加了额外的 HTML 元素,一些嵌套标记和选择器可能会损坏。这仅影响测试模式。
Tip:
In versions of SugarCube ≥v2.23.0, the debugging interface offers additional tools, namely variable watches and arbitrary history navigation.
小贴士:在 SugarCube ≥v2.23.0 版本中,调试界面提供了额外的工具,包括变量监视和任意历史导航。
To enable test mode, use the test option (-t
, --test
).
要启用测试模式,请使用测试选项( -t
, --test
)。
To enable test mode from the Stories screen, click on the story's gear menu and select the Test Story menu item.
要从故事界面启用测试模式,请点击故事的齿轮菜单并选择“测试故事”菜单项。
To enable test mode from the story editor/map screen, click on the Test menu item (right side of the bottom bar).
要启用测试模式,从故事编辑器/地图屏幕,点击底栏右侧的“测试”菜单项。
To enable test mode from the story editor/map screen while starting at a specific passage, hover over a passage and select the menu item.
要启用测试模式,在启动时从特定段落开始,请将鼠标悬停在段落上并选择菜单项。
To enable test mode from the Stories screen, click on the story's gear menu and select the Test Play menu item.
要从“故事”界面启用测试模式,请点击故事的齿轮菜单并选择“测试播放”菜单项。
To enable test mode from the story editor/map screen, click on the Test menu item (right side of the bottom bar).
要从故事编辑器/地图界面启用测试模式,请点击底部栏右侧的“测试”菜单项。
To enable test mode from the story editor/map screen while starting at a specific passage, hover over a passage and select the menu item.
要从故事编辑器/地图界面并从特定段落开始启用测试模式,请悬停在段落上并选择菜单项。
To enable test mode while starting at a specific passage, right-click on a passage and select the Test Play From Here context menu item.
在启动时从特定段落启用测试模式,请右键单击段落并选择“从此处测试播放”上下文菜单项。
Note:
Unfortunately, due to limitations in the current release of Twine 1, the Build menu's Test Play menu item is not able to trigger test mode. You may, however, simply use the Test Play From Here context menu item on the Start
passage to achieve the same result.
注意:遗憾的是,由于 Twine 1 当前版本的限制,构建菜单中的“测试播放”菜单项无法触发测试模式。但是,您可以直接在 Start
段落上使用“从此处测试播放”上下文菜单项来达到相同的效果。
You may forcibly enable test mode manually by setting the Config
object's debug
property to true
. For example:
您可以通过将 Config
对象的 debug
属性设置为 true
来手动强制启用测试模式。例如:
Config.debug = true; // forcibly enable test mode
See:
The Config.debug
setting for more information.
查看 Config.debug
设置以获取更多信息。
The debug bar (bottom right corner of the page) allows you to: watch the values of story and temporary variables, toggle the debug views, and jump to any moment/turn within the history.
调试栏(页面右下角)允许您:监视故事和临时变量的值、切换调试视图,以及跳转到历史中的任何时刻/回合。
The variable watch panel may be toggled via the Watch button. To add a watch for a variable, type its name into the Add field and then either press enter/return or click the button—n.b. depending on the age of your browser, you may also see a list of all current variables when interacting with the Add field. To delete a watch, click the button next to its name in the watch panel. To add watches for all current variables, click the button. To delete all current watches, click the button.
可以通过“监视”按钮切换变量监视面板。要监视一个变量,将其名称输入到“添加”字段中,然后按回车键或点击按钮——请注意,根据您浏览器的版本,在交互“添加”字段时,您也可能看到所有当前变量的列表。要删除监视,请点击监视面板中其名称旁边的按钮。要监视所有当前变量,请点击按钮。要删除所有当前监视,请点击按钮。
The debug views may be toggled via the Views button.
可以通过“视图”按钮切换调试视图。
To jump to any moment/turn within the available history, select the moment/turn from the Turn select field.
要跳转到可用历史中的任何时刻/回合,请从“回合选择”字段中选择时刻/回合。
The debug views themselves may be toggled on and off (default: on) via the Debug View button (top of the UI bar).
调试视图本身可以通过调试视图按钮(UI 栏顶部)开启和关闭(默认开启)。
If you've removed/hidden the UI bar, a construct like the following will allow you to toggle the views on and off:
如果您已删除/隐藏 UI 栏,可以使用以下结构来切换视图的开启和关闭:
<<button "Toggle Debug Views">><<script>>DebugView.toggle()<</script>><</button>>
Note:
That will only toggles the views, test mode must still be enabled first.
注意:这只会切换视图,测试模式必须先启用。
TypeScript bindings for SugarCube APIs can found as the Definitely Typed package: @types/twine-sugarcube
.
TypeScript 绑定 SugarCube API 可以在 Definitely Typed 包中找到: @types/twine-sugarcube
。
To install the package via NPM, use the following command:
要通过 NPM 安装此包,请使用以下命令:
npm install --save-dev @types/twine-sugarcube
This is a reference on how to install SugarCube in Tweego, Twine 2, and Twine 1/Twee.
这是关于如何在 Tweego、Twine 2 和 Twine 1/Twee 中安装 SugarCube 的参考。
Note (Twine 2):
Newer versions of Twine 2 come bundled with a version of SugarCube v2, so you only need to read these instructions if you want to install a newer version of SugarCube v2 than is bundled or a non-standard release.
注意(Twine 2):Twine 2 的新版本自带 SugarCube v2 的版本,因此如果您只想安装比捆绑版本更新的 SugarCube v2 或非标准版本,则需要阅读这些说明。
See Tweego's documentation for more information.
查看 Tweego 的文档以获取更多信息。
There are two primary branches of Twine 2 as far as SugarCube is concerned:
就 SugarCube 而言,Twine 2 有两个主要分支:
Regardless of the version of Twine 2 you're using, follow these instructions to install a local copy of SugarCube v2:
无论您使用的是哪个版本的 Twine 2,请按照以下说明安装 SugarCube v2 的本地副本:
Formats
link in the Twine 2 sidebar.Formats
链接。Add a New Format
tab.Add a New Format
选项卡。format.js
file, based upon the path from step #2, into the textbox and click the +Add
button (see below for examples).format.js
文件的文件 URL 到文本框中,然后点击 +Add
按钮(以下为示例)。Note:
If constructing the file URL from a shell path, ensure that either it does not contain escapes or you properly convert them into the correct URL percent-encoded form.
注意:如果从 shell 路径构造文件 URL,请确保它不包含转义字符,或者您已将其正确转换为正确的 URL 百分编码形式。
If the full path to the contents of the archive is something like:
如果存档内容的完整路径类似于:
/home/soandso/Twine/StoryFormats/SugarCube-2/format.js
Then the file URL to it would be:
那么指向它的文件 URL 将是:
file:///home/soandso/Twine/StoryFormats/SugarCube-2/format.js
If the full path to the contents of the archive is something like:
如果存档内容的完整路径是这样的:
C:\Users\soandso\Documents\Twine\StoryFormats\SugarCube-2\format.js
Then the file URL to it would be (note the changed slashes):
那么指向它的文件 URL 将是(注意斜杠的变化):
file:///C:/Users/soandso/Documents/Twine/StoryFormats/SugarCube-2/format.js
The online SugarCube install, delivered by the jsDelivr CDN, supports only versions of Twine 2 ≥2.1.
在线 SugarCube 安装,由 jsDelivr CDN 提供,仅支持 Twine 2 ≥2.1 版本。
Copy the following URL and paste it into the Add a New Format tab of the Formats menu, from Twine 2's sidebar.
将以下 URL 复制并粘贴到 Twine 2 侧边栏的“添加新格式”选项卡中。
URL: https://cdn.jsdelivr.net/gh/tmedwards/sugarcube-2/dist/format.js
Follow these instructions to install a local copy of SugarCube v2:
按照以下说明安装 SugarCube v2 的本地副本:
targets
directory within.targets
目录。targets
directory and extract it, included directory and all.targets
目录中,并解压,包括所有目录。If you followed the steps correctly, within Twine 1/Twee's targets
directory you should now have a sugarcube-2
directory, which contains several files—e.g., header.html
, sugarcube-2.py
, etc.
如果您正确地遵循了步骤,在 Twine 1/Twee 的 targets
目录中,您现在应该有一个 sugarcube-2
目录,其中包含几个文件——例如, header.html
, sugarcube-2.py
等。
Due to a flaw in the current release of Twine 1/Twee (v1.4.2
), if you rename the directory included in the archive (or simply copy its contents to your current SugarCube v2 install), then you must ensure that the file with the extension .py
(the story format's custom Twine 1 Header class file) within is named the same as the directory—i.e., the name of the directory and .py
file must match.
由于当前 Twine 1/Twee 版本( v1.4.2
)存在缺陷,如果您重命名存档中包含的目录(或将其内容复制到当前 SugarCube v2 安装中),则必须确保目录中的扩展名为 .py
(故事格式的自定义 Twine 1 标头类文件)的文件与目录名称相同——即目录名称和 .py
文件名称必须匹配。
For example, if the name of SugarCube's directory is sugarcube
, then the name of the .py
file within must be sugarcube.py
. Similarly, if the directory is sugarcube-2
, then the name of the .py
file within must be sugarcube-2.py
. Etc.
例如,如果 SugarCube 目录的名称为 sugarcube
,则目录中的 .py
文件名称必须为 sugarcube.py
。同样,如果目录名称为 sugarcube-2
,则目录中的 .py
文件名称必须为 sugarcube-2.py
。等等。
The directory and .py
file names within the archive available for download are already properly matched—as sugarcube-2
and sugarcube-2.py
—and to avoid issues it recommended that you simply do not rename them.
可以下载的存档中的目录和 .py
文件名称已经正确匹配——即 sugarcube-2
和 sugarcube-2.py
,为了避免问题,建议您不要重命名它们。
This is a reference on how to update existing SugarCube code to work with newer versions of SugarCube.
这是一份关于如何将现有的 SugarCube 代码更新以适应 SugarCube 新版本的参考。
Note:
The majority of newer SugarCube versions do not have any changes that would require an update. For those versions that do, the updates are normally completely elective and may be addressed at your leisure, or not at all. Sometimes there are breaking changes, however, and these must be addressed immediately.
注意:大多数新版本的 SugarCube 没有需要进行更新的更改。对于那些确实需要更新的版本,这些更新通常是完全可选的,您可以在方便的时候进行,或者完全不进行。然而,有时会有破坏性更改,这些更改必须立即解决。
Warning:
Some changes within this version are breaking changes that you must address immediately, while others are elective changes that you may address at your leisure. All breaking changes will be so noted.
警告:本版本中的一些更改是破坏性更改,您必须立即解决,而其他更改是可选更改,您可以在方便的时候解决。所有破坏性更改都将予以注明。
Note:
The removals herein are of features that have been deprecated for years. Most are v1
compatibility APIs that have always been deprecated in v2
. Nothing of value has been lost.
注意:此处删除的功能已弃用多年。其中大多数是 v1
兼容性 API,这些 API 在 v2
中一直被弃用。没有任何有价值的内容丢失。
API | Change 变更 |
---|---|
browser |
BREAKING: This deprecated legacy API has been removed. Its replacement is Browser .破坏性更新:已删除此弃用的遗留 API。其替代方案为 Browser 。 |
config |
BREAKING: This deprecated legacy API has been removed. Its replacement is Config .突发:此已弃用的旧版 API 已被移除。其替代方案为 Config 。 |
has |
BREAKING: This deprecated legacy API has been removed. Its replacement is Has .突发:此已弃用的旧版 API 已被移除。其替代方案为 Has 。 |
History |
BREAKING: This deprecated legacy API has been removed. Its replacement is State .突发:此已弃用的旧版 API 已被移除。其替代方案为 State 。 |
state |
BREAKING: This deprecated legacy API has been removed. Its replacement is State .突发:此已弃用的旧版 API 已被移除。其替代方案为 State 。 |
tale |
BREAKING: This deprecated legacy API has been removed. Its replacement is Story .破坏性更新:已删除此弃用的遗留 API。其替代方案为 Story 。 |
TempVariables |
BREAKING: This deprecated legacy API has been removed. Its replacement is State.temporary .破坏性更新:已删除此弃用的遗留 API。其替代方案为 State.temporary 。 |
Array
API Array
糖立方 APIMethod 方法 | Change 修改 |
---|---|
Array.random() |
BREAKING: This deprecated static method has been removed. See the <Array>.random() instance method.破坏性更新:此已弃用的静态方法已被移除。请参阅 <Array>.random() 实例方法。 |
<Array>.contains() |
BREAKING: The polyfill for this instance method has been removed. See the <Array>.includes() instance method.破坏性更新:此实例方法的 polyfill 已被移除。请参阅 <Array>.includes() 实例方法。 |
<Array>.containsAll() |
BREAKING: This instance method has been removed. See the <Array>.includesAll() instance method.突发:此实例方法已被删除。请参阅 <Array>.includesAll() 实例方法。 |
<Array>.containsAny() |
BREAKING: This instance method has been removed. See the <Array>.includesAny() instance method.突发:此实例方法已被删除。请参阅 <Array>.includesAny() 实例方法。 |
<Array>.flatten() |
BREAKING: This instance method has been removed. See the <Array>.flat() instance method while providing a depth parameter of Infinity .突发:此实例方法已被删除。在提供 depth 参数为 Infinity 的同时,请参阅 <Array>.flat() 实例方法。 |
Config
API Config
糖立方 APISetting 设置 | Change 更改 |
---|---|
Config.macros.ifAssignError |
This setting has been deprecated and should no longer be used. See the Config.enableOptionalDebugging setting for its replacement.此设置已被弃用,不应再使用。请参阅 Config.enableOptionalDebugging 设置以获取其替代方案。 |
Config.passages.descriptions |
This setting has been deprecated and should no longer be used. See the Config.saves.descriptions setting for its replacement.此设置已被弃用,不应再使用。请参阅 Config.saves.descriptions 设置以获取替代方案。 |
Config.saves.autoload |
This setting has been deprecated and should no longer be used. The default UI now includes a Continue button, which loads the latest save. If disabling or replacing the default UI, see the Save.browser.continue() method to replicate the functionality.此设置已被弃用,不应再使用。默认用户界面现在包括一个“继续”按钮,该按钮加载最新保存。如果禁用或替换默认用户界面,请参阅 Save.browser.continue() 方法以复制该功能。 |
Config.saves.autosave |
This setting has been deprecated and should no longer be used. See the Config.saves.maxAutoSaves setting to set the number of available auto saves and the Config.saves.isAllowed setting to control when new auto saves are created.此设置已被弃用,不应再使用。请参阅 Config.saves.maxAutoSaves 设置以设置可用的自动保存数量,以及 Config.saves.isAllowed 设置以控制何时创建新的自动保存。 |
Config.saves.isAllowed |
This setting, to which you assign a function, has had the parameters provided to the assigned function changed. See its documentation entry for details. 此设置,您为其分配了函数,已更改提供的参数。请参阅其文档条目以获取详细信息。 |
Config.saves.slots |
This setting has been deprecated and should no longer be used. See the Config.saves.maxSlotSaves setting for its replacement.此设置已被弃用,不应再使用。请参阅 Config.saves.maxSlotSaves 设置以获取替代方案。 |
Config.saves.tryDiskOnMobile |
This setting has been deprecated and should no longer be used. Saving to disk on mobile devices is now unconditionally enabled. 此设置已被弃用,不应再使用。在移动设备上保存到磁盘现在无条件启用。 |
Dialog
API Dialog
糖立方 APIMethod 方法 | Change 更改 |
---|---|
Dialog.addClickHandler() |
BREAKING: This deprecated static method has been removed. 破坏性更新:此弃用的静态方法已被移除。 |
Dialog.setup() |
This static method has been deprecated in favor of the Dialog.create() static method.此静态方法已被弃用,以支持 Dialog.create() 静态方法。 |
JSON
API JSON
糖立方 APIMethod 方法 | Change 更改 |
---|---|
JSON.reviveWrapper() |
This static method has been deprecated in favor of the Serial.createReviver() static method.此静态方法已被弃用,改用 Serial.createReviver() 静态方法。 |
Macro 宏 | Change 更改 |
---|---|
<<actions>> |
This macro has been deprecated. 此宏已弃用。 |
<<choice>> |
This macro has been deprecated. 此宏已弃用。 |
<<click>> |
BREAKING: This deprecated macro has been removed. See the <<link>> macro.破坏性更新:此弃用宏已被移除。请参阅 <<link>> 宏。 |
<<display>> |
BREAKING: This deprecated macro has been removed. See the <<include>> macro.破坏性更新:此弃用宏已被移除。请参阅 <<include>> 宏。 |
<<forget>> |
BREAKING: This deprecated macro has been removed. See the forget() function.突发:此弃用宏已被移除。请参阅 forget() 函数。 |
<<remember>> |
BREAKING: This deprecated macro has been removed. See the memorize() and recall() functions.突发:此弃用宏已被移除。请参阅 memorize() 和 recall() 函数。 |
<<setplaylist>> |
BREAKING: This deprecated macro has been removed. See the <<createplaylist>> macro.突发:此弃用宏已被移除。请参阅 <<createplaylist>> 宏。 |
<<stopallaudio>> |
BREAKING: This deprecated macro has been removed. See the <<masteraudio>> macro.突发:此弃用宏已被移除。请参阅 <<masteraudio>> 宏。 |
MacroContext
API MacroContext
糖立方 APIMember 会员 | Change 更改 |
---|---|
<MacroContext>.contextHas() |
This instance method has been deprecated in favor of the <MacroContext>.contextSome() instance method.此实例方法已被弃用,改用 <MacroContext>.contextSome() 实例方法。 |
<MacroContext>.contextSelect() |
This instance method has been deprecated in favor of the <MacroContext>.contextFind() instance method.此实例方法已被弃用,改用 <MacroContext>.contextFind() 实例方法。 |
<MacroContext>.contextSelectAll() |
This instance method has been deprecated in favor of the <MacroContext>.contextFilter() instance method.此实例方法已被弃用,改用 <MacroContext>.contextFilter() 实例方法。 |
Number
API Number
糖立方 APIMethod 方法 | Change 修改 |
---|---|
<Number>.clamp() |
This instance method has been deprecated. See the Math.clamp() static method.此实例方法已被弃用。请参阅 Math.clamp() 静态方法。 |
Passage
API Passage
糖立方 APIMember 会员 | Change 修改 |
---|---|
<Passage>.domId |
This instance property has been deprecated in favor of the <Passage>.id instance property.此实例属性已被弃用,改用 <Passage>.id 实例属性。 |
<Passage>.title |
This instance property has been deprecated in favor of the <Passage>.name instance property.此实例属性已被弃用,改用 <Passage>.name 实例属性。 |
<Passage>.description() |
This instance method has been deprecated. 此实例方法已被弃用。 |
Save
API Save
糖立方 APIMethod 方法 | Change 修改 |
---|---|
Save.get() |
BREAKING: This static method has been removed. See the Save.browser.auto.entries() and Save.browser.slot.entries() static methods for its closest replacements.突发:此静态方法已被移除。请参阅 Save.browser.auto.entries() 和 Save.browser.slot.entries() 静态方法以获取其最接近的替代方案。 |
Save.clear() |
This static method has been deprecated in favor of the Save.browser.clear() static method.此静态方法已被弃用,以 Save.browser.clear() 静态方法替代。 |
Save.ok() |
This static method has been deprecated in favor of the Save.browser.isEnabled() static method.此静态方法已被弃用,以 Save.browser.isEnabled() 静态方法替代。 |
Save.autosave.delete() |
This static method has been deprecated in favor of the Save.browser.auto.delete() static method.此静态方法已被弃用,以 Save.browser.auto.delete() 静态方法替代。 |
Save.autosave.get() |
This static method has been deprecated in favor of the Save.browser.auto.get() static method.此静态方法已被弃用,建议使用 Save.browser.auto.get() 静态方法。 |
Save.autosave.has() |
This static method has been deprecated in favor of the Save.browser.auto.has() static method.此静态方法已被弃用,建议使用 Save.browser.auto.has() 静态方法。 |
Save.autosave.load() |
This static method has been deprecated in favor of the Save.browser.auto.load() static method.此静态方法已被弃用,建议使用 Save.browser.auto.load() 静态方法。 |
Save.autosave.ok() |
This static method has been deprecated in favor of the Save.browser.auto.isEnabled() static method.此静态方法已被弃用,改用 Save.browser.auto.isEnabled() 静态方法。 |
Save.autosave.save() |
This static method has been deprecated in favor of the Save.browser.auto.save() static method.此静态方法已被弃用,改用 Save.browser.auto.save() 静态方法。 |
Save.slots.length |
This static property has been deprecated in favor of the Config.saves.maxSlotSaves setting.此静态属性已被弃用,改用 Config.saves.maxSlotSaves 设置。 |
Save.slots.count() |
This static method has been deprecated in favor of the Save.browser.slot.size static getter.此静态方法已被弃用,改用 Save.browser.slot.size 静态获取器。 |
Save.slots.delete() |
This static method has been deprecated in favor of the Save.browser.slot.delete() static method.此静态方法已被弃用,改用 Save.browser.slot.delete() 静态方法。 |
Save.slots.get() |
This static method has been deprecated in favor of the Save.browser.slot.get() static method.此静态方法已被弃用,改用 Save.browser.slot.get() 静态方法。 |
Save.slots.has() |
This static method has been deprecated in favor of the Save.browser.slot.has() static method.此静态方法已被弃用,改用 Save.browser.slot.has() 静态方法。 |
Save.slots.isEmpty() |
This static method has been deprecated in favor of the Save.browser.slot.size static getter.此静态方法已被弃用,改用 Save.browser.slot.size 静态获取器。 |
Save.slots.load() |
This static method has been deprecated in favor of the Save.browser.slot.load() static method.此静态方法已被弃用,改用 Save.browser.slot.load() 静态方法。 |
Save.slots.ok() |
This static method has been deprecated in favor of the Save.browser.slot.isEnabled() static method.此静态方法已被弃用,改用 Save.browser.slot.isEnabled() 静态方法。 |
Save.slots.save() |
This static method has been deprecated in favor of the Save.browser.slot.save() static method.此静态方法已被弃用,改用 Save.browser.slot.save() 静态方法。 |
Save.export() |
This static method has been deprecated in favor of the Save.disk.save() static method.此静态方法已被弃用,改用 Save.disk.save() 静态方法。 |
Save.import() |
This static method has been deprecated in favor of the Save.disk.load() static method.此静态方法已被弃用,改用 Save.disk.load() 静态方法。 |
Save.deserialize() |
This static method has been deprecated in favor of the Save.base64.load() static method.此静态方法已被弃用,改用 Save.base64.load() 静态方法。 |
Save.serialize() |
This static method has been deprecated in favor of the Save.base64.save() static method.此静态方法已被弃用,改用 Save.base64.save() 静态方法。 |
Scripting
API Scripting
糖立方 APIMethod 方法 | Change 修改 |
---|---|
Scripting.desugar() |
BREAKING: The undocumented is not to isnot operator mapping has been removed.突发:已移除未记录的 is not 到 isnot 操作符映射。 |
Scripting.parse() |
This static method has been deprecated in favor of the Scripting.desugar() static method.此静态方法已被弃用,改用 Scripting.desugar() 静态方法。 |
State
API State
糖立方 APIMethod 方法 | Change 修改 |
---|---|
State.backward() |
BREAKING: This deprecated static method has been removed. 突发:已移除已弃用的静态方法。 |
State.display() |
BREAKING: This deprecated static method has been removed. 突发:已移除已弃用的静态方法。 |
State.forward() |
BREAKING: This deprecated static method has been removed. 突发:已移除已弃用的静态方法。 |
State.initPRNG() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
State.play() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
State.restart() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
State.show() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
Story
API Story
糖立方 APIMember 会员 | Change 修改 |
---|---|
Story.domId |
This static property has been deprecated in favor of the Story.id static property.此静态属性已被弃用,改用 Story.id 静态属性。 |
Story.title |
This static property has been deprecated in favor of the Story.name static property.此静态属性已被弃用,改用 Story.name 静态属性。 |
StoryInterface
special passage StoryInterface
特殊段落
POSSIBLY BREAKING: The default UI's <div id="story" role="main">
container has been made a core part of the base UI, for both native and custom end user markup. As a consequence, this means that the custom markup generated by using the StoryInterface
special passage may no longer itself contain a #story
element and will be added to the core #story
container, rather than <body>
.
可能破坏性更改:默认 UI 的 <div id="story" role="main">
容器已被纳入基础 UI 的核心部分,适用于原生和自定义用户标记。因此,这意味着使用 StoryInterface
特殊段落生成的自定义标记可能不再包含一个 #story
元素,而是将被添加到核心 #story
容器中,而不是 <body>
。
An example of the new hierarchy:
新层次结构的示例:
<body>
<div id="story" role="main">
<!-- StoryInterface elements added here -->
</div>
</body>
It is strongly recommended that you review your selectors related to the generated markup, both for DOM manipulation and CSS styling, to ensure that they're still functional. Primarily this will affect selectors that use the child combinator (>
) with a body
parent—e.g., body > …
where …
is one the elements within your custom markup.
强烈建议您检查与生成的标记相关的选择器,无论是用于 DOM 操作还是 CSS 样式,以确保它们仍然有效。这主要会影响使用子组合器( >
)与 body
父元素相关的选择器——例如, body > …
其中 …
是您自定义标记中的元素之一。
This change was required to fix a bug related to the interaction between open dialogs and <body>
.
此更改是为了修复与打开对话框和 <body>
之间的交互相关的错误。
String
API String
糖立方 APIMethod 方法 | Change 修改 |
---|---|
<String>.readBracketedList() |
BREAKING: This deprecated instance method has been removed. 紧急通知:此已弃用的实例方法已被移除。 |
UI
API UI
糖立方 APIMethod 方法 | Change 修改 |
---|---|
UI.buildAutoload() |
This static method has been deprecated. 此静态方法已被弃用。 |
UI.addClickHandler() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.body() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.close() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.isOpen() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.open() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.resize() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.setStoryElements() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.setup() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.stow() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UI.unstow() |
BREAKING: This deprecated static method has been removed. 突发:此已弃用的静态方法已被移除。 |
UIBar
toggle and history button markup & styles
The icons of the UI bar history control buttons have been changed from being text content in their markup to a part of their styles, as with most native SugarCube icon bearing buttons.
UI 栏历史控制按钮的图标已从标记中的文本内容更改为其样式的一部分,这与大多数原生的 SugarCube 图标按钮类似。
The styles of the UI bar toggle and history control buttons have been simplified. If you've customized the styling of any of these buttons, then it is strongly recommended that you review the ui-bar.css
file for exact details.
UI 栏的切换和历史控制按钮的样式已简化。如果您已自定义这些按钮的样式,则强烈建议您查看 ui-bar.css
文件以获取详细信息。
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Config
API Config
糖立方 APIProperty 属性 | Change 修改 |
---|---|
Config.history.maxStates |
This setting property has been updated to disallow unlimited states. 此设置属性已被更新,不允许无限状态。 |
Config.saves.onLoad |
This setting property has been deprecated in favor of the Save Events API, specifically the Save.onLoad.add static method.此设置属性已被弃用,转而使用 Save 事件 API,特别是 Save.onLoad.add 静态方法。 |
Config.saves.onSave |
This setting property has been deprecated in favor of the Save Events API, specifically the Save.onSave.add static method.此设置属性已被弃用,转而使用 Save 事件 API,特别是 Save.onSave.add 静态方法。 |
Macro 宏 | Change 修改 |
---|---|
<<widget>> |
The special $args story variable has been deprecated in favor of the _args_ temporary variable.特殊的 $args 故事变量已被弃用,改为使用 _args_ 临时变量。 |
Warning:
All changes within this version are breaking changes that you must address immediately.
警告:本版本中所有更改均为破坏性更改,您必须立即解决。
Parser 解析器 | Change 修改 |
---|---|
HTML tag HTML 标签 | The parser has been updated to disallow use of the evaluation attribute directive on the data-setter content attribute. They were never supposed to be combined.解析器已更新,禁止在 data-setter 内容属性上使用 evaluation 属性指令。它们本不应该结合使用。 |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Config
API Config
糖立方 APIProperty 属性 | Change 修改 |
---|---|
Config.saves.autosave |
This setting property has been updated to accept function values and its acceptance of string values has been deprecated. String values will still be accepted for further releases of v2, however, switching to an array is recommended—e.g., the string value "autosave" would become the array ["autosave"] . See the Config.saves.autosave property for more information.此设置属性已更新为接受函数值,其接受字符串值的做法已被弃用。然而,字符串值仍将在 v2 的后续版本中接受,但建议切换到数组——例如,字符串值 "autosave" 将变为数组 ["autosave"] 。有关更多信息,请参阅 Config.saves.autosave 属性。 |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Dialog
API Dialog
糖立方 APIMethod 方法 | Change 修改 |
---|---|
Dialog.addClickHandler() |
This method has been deprecated and should no longer be used. The core of what it does is simply to wrap a call to Dialog.open() within a call to <jQuery>.ariaClick() , which can be done directly and with greater flexibility.此方法已被弃用,不应再使用。它的核心功能仅仅是将 Dialog.open() 的调用封装在 <jQuery>.ariaClick() 的调用中,这可以直接进行,并且具有更高的灵活性。 |
Macro 宏 | Change 修改 |
---|---|
<<track>> (of: <<createplaylist>> ) <<track>> (属于: <<createplaylist>> ) |
The <<createplaylist>> macro's <<track>> child macro has had its copy keyword deprecated in favor of own . See the <<createplaylist>> macro for more information.<<createplaylist>> 宏的 <<跟踪>> 子宏已将 copy 关键字弃用,改用 own 。有关更多信息,请参阅 <<createplaylist>> 宏。 |
<<forget>> |
The <<forget>> macro has been deprecated in favor of the forget() function.<<forget>> 宏已被弃用,改用 forget() 函数。 |
<<remember>> |
The <<remember>> macro has been deprecated in favor of the memorize() and recall() functions.<<remember>> 宏已被弃用,改用 memorize() 和 recall() 函数。 |
Method 方法 | Change 修改 |
---|---|
<Array>.flatten() |
This method has been deprecated in favor of the <Array>.flat() method.此方法已被弃用,改用 <Array>.flat() 方法。 |
State
API State
糖立方 APIMethod 方法 | Change 修改 |
---|---|
State.initPRNG() |
This method has been deprecated in favor of the State.prng.init() method.此方法已被弃用,推荐使用 State.prng.init() 方法。 |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Macro 宏 | Change 修改 |
---|---|
<<cacheaudio>> |
The <<cacheaudio>> macro's original optional format specifier syntax, format:formatId;… , has been deprecated in favor of the new syntax, formatId|… ..<<cacheaudio>> 宏原始的可选格式说明符语法, format:formatId;… ,已被弃用,改用新的语法, formatId|… .. |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Method 方法 | Change 修改 |
---|---|
Array.random() |
This method has been deprecated and should no longer be used. In general, look to the <Array>.random() method instead. If you need a random member from an array-like object or iterable, use the Array.from() method to convert it to an array, then use <Array>.random() —e.g., Array.from(something).random() .此方法已被弃用,不应再使用。通常,请查找使用 <Array>.random() 方法。如果您需要从类似数组的对象或可迭代对象中获取随机成员,请使用 Array.from() 方法将其转换为数组,然后使用 <Array>.random() ——例如, Array.from(something).random() 。 |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Macro 宏 | Change 修改 |
---|---|
<<display>> |
The <<display>> macro has been deprecated in favor of the <<include>> macro.<<display>> 宏已被弃用,改为使用 <<include>> 宏。 |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Method 方法 | Change 修改 |
---|---|
<Array>.contains() |
The <Array>.contains() method has been deprecated in favor of the <Array>.includes() method.
<Array>.contains() 方法已被弃用,推荐使用 <Array>.includes() 方法。 |
<Array>.containsAll() |
The <Array>.containsAll() method has been deprecated in favor of the <Array>.includesAll() method.
<Array>.containsAll() 方法已被弃用,推荐使用 <Array>.includesAll() 方法。 |
<Array>.containsAny() |
The <Array>.containsAny() method has been deprecated in favor of the <Array>.includesAny() method.
<Array>.containsAny() 方法已被弃用,推荐使用 <Array>.includesAny() 方法。 |
strings
object strings
对象The strings
API object has been replaced by the l10nStrings
object. See the Localization guide for more information.
strings
API 对象已被 l10nStrings
对象替换。有关更多信息,请参阅本地化指南。
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
Macro 宏 | Change 修改 |
---|---|
<<click>> |
The <<click>> macro has been deprecated in favor of the <<link>> macro.该 <<click>> 宏已被弃用,改用 <<link>> 宏。 |
<<playlist>> |
The <<playlist>> macro has had its argument list changed, for compatibility with <<createplaylist>> . See the <<playlist>> macro for more information.<<playlist>> 宏的参数列表已更改,以与 <<createplaylist>> 宏兼容。有关更多信息,请参阅 <<playlist>> 宏。 |
<<setplaylist>> |
The <<setplaylist>> macro has been deprecated in favor of the <<createplaylist>> macro.<<setplaylist>> 宏已被弃用,以 <<createplaylist>> 宏替代。 |
<<stopallaudio>> |
The <<stopallaudio>> macro has been deprecated in favor of <<audio ":all" stop>> . See the <<audio>> macro for more information.<<stopallaudio>> 宏已被弃用,以 <<audio ":all" stop>> 替代。有关更多信息,请参阅 <<audio>> 宏。 |
All changes within this version are elective changes that you may address at your leisure.
本版本内的所有更改均为可选更改,您可以在空闲时进行处理。
config
API config
糖立方 APIThe config
API has been renamed Config
for better consistency with the other APIs.
config
API 已更名为 Config
,以与其他 API 保持更好的一致性。
State
API State
糖立方 APISeveral State
API methods have moved to the new Engine
API. See the Engine
API docs for more information.
一些 State
API 方法已迁移到新的 Engine
API。请参阅 Engine
API 文档以获取更多信息。
Old State method 旧 State 方法 |
New Engine method 新的 Engine 方法 |
---|---|
State.backward() |
Engine.backward() |
State.display() |
Engine.display() 1 |
State.forward() |
Engine.forward() |
State.play() |
Engine.play() |
State.restart() |
Engine.restart() |
State.show() |
Engine.show() |
Engine.display()
static methods exists, it, like State.display()
before it, is deprecated. See the Engine.play()
static method for the replacement. NOTE: Their parameters differ, so read the description of Engine.play()
carefully.Engine.display()
静态方法仍然存在,但它,就像之前的 State.display()
一样,已被弃用。请参阅 Engine.play()
静态方法以获取替代方案。注意:它们的参数不同,因此请仔细阅读 Engine.play()
的描述。UI
API UI
糖立方 APISeveral UI
API methods have moved to the new Dialog
API. See the Dialog
API docs for more information.
一些 UI
API 方法已迁移到新的 Dialog
API。请参阅 Dialog
API 文档以获取更多信息。
Old UI method 旧 UI 方法 |
New Dialog method 新的 Dialog 方法 |
---|---|
UI.addClickHandler() |
Dialog.addClickHandler() |
UI.body() |
Dialog.body() |
UI.close() |
Dialog.close() |
UI.isOpen() |
Dialog.isOpen() |
UI.open() |
Dialog.open() |
UI.setup() |
Dialog.setup() |
Warning:
All changes within this version are breaking changes that you must address immediately.
警告:本版本中所有更改均为破坏性更改,您必须立即解决。
The HTML & CSS have undergone significant changes. See the HTML
and CSS
docs for more information.
HTML 与 CSS 经历了重大变化。请参阅 HTML
和 CSS
文档以获取更多信息。
Passage 段落 | Change 修改 |
---|---|
MenuOptions |
The MenuOptions special passage has been removed. See the Options system section for more information.MenuOptions 特殊段落已被删除。请参阅选项系统部分以获取更多信息。 |
MenuShare |
The MenuShare special passage has been removed. See the StoryShare special passage.MenuShare 特殊段落已被删除。请参阅 StoryShare 特殊段落。 |
MenuStory |
The MenuStory special passage has been removed. See the StoryMenu special passage.MenuStory 特殊段落已被删除。参见 StoryMenu 特殊段落。 |
config
object config
对象The config
object has been renamed to Config
and some of its properties have also changed. See the Config
API docs for more information.
该 config
对象已被重命名为 Config
,并且其一些属性也发生了变化。请参阅 Config
API 文档以获取更多信息。
Property 属性 | Change 修改 |
---|---|
config.altPassageDescription |
Changed the config.altPassageDescription property to Config.passages.descriptions .将 config.altPassageDescription 属性更改为 Config.passages.descriptions 。 |
config.disableHistoryControls |
Changed the config.disableHistoryControls property to Config.history.controls . This change also inverted the meaning of the property, so take note of that.将 config.disableHistoryControls 属性更改为 Config.history.controls 。此更改还反转了属性的语义,请注意这一点。 |
config.disableHistoryTracking |
Replaced the config.disableHistoryTracking property with Config.history.maxStates . The new property works differently, so take note of that.将 config.disableHistoryTracking 属性替换为 Config.history.maxStates 。新属性的工作方式不同,请注意这一点。 |
config.displayPassageTitles |
Changed the config.displayPassageTitles property to Config.passages.displayTitles .将 config.displayPassageTitles 属性更改为 Config.passages.displayTitles 。 |
config.historyMode |
Removed the config.historyMode property. It's unnecessary since there's now only one history mode in the engine.删除了 config.historyMode 属性。由于引擎中现在只有一个历史模式,因此此属性不再必要。 |
config.macros.disableIfAssignmentError |
Changed the config.macros.disableIfAssignmentError property to Config.macros.ifAssignmentError . This change also inverted the meaning of the property, so take note of that.将 config.macros.disableIfAssignmentError 属性更改为 Config.macros.ifAssignmentError 。此更改还反转了属性的语义,请注意这一点。 |
config.passageTransitionOut |
Changed the config.passageTransitionOut property to Config.passages.transitionOut . Additionally, it no longer accepts a boolean value, which has been replaced by the name of the animating property (necessitated by changes to browser handling of transition animations).将 config.passageTransitionOut 属性更改为 Config.passages.transitionOut 。此外,它不再接受布尔值,这已被动画属性的名称所取代(这是由于浏览器对过渡动画的处理方式发生变化所必需的)。 |
config.startPassage |
Changed the config.startPassage property to Config.passages.start .修改了 config.startPassage 属性为 Config.passages.start 。 |
config.updatePageElements |
Changed the config.updatePageElements property to Config.ui.updateStoryElements .将 config.updatePageElements 属性更改为 Config.ui.updateStoryElements 。 |
state
)state
)The History
API object has been renamed to State
and some of its methods have also changed. Furthermore, it is no longer instantiated into the legacy state
object—which still exists, so legacy code will continue to work. See the State
API docs for more information.
History
API 对象已被重命名为 State
,其中一些方法也发生了变化。此外,它不再实例化为遗留的 state
对象——该对象仍然存在,因此遗留代码将继续工作。有关更多信息,请参阅 State
API 文档。
The State.display()
method—formerly state.display()
—is no longer overridable, meaning it cannot be wrapped—e.g., the "StoryRegions" 3rd-party add-ons do this. See Navigation Events or Tasks.
State.display()
方法——以前称为 state.display()
——现在不再可覆盖,这意味着它不能被包装——例如,“StoryRegions”第三方插件就是这样做的。请参阅导航事件或任务。
Calling the State.prng.init()
method—formerly History.initPRNG()
—outside of story initialization will now throw an error. It has always been required that the call happen during story initialization, the only change is the throwing of the error.
现在在故事初始化之外调用 State.prng.init()
方法——以前称为 History.initPRNG()
——将引发错误。调用必须在故事初始化期间发生,唯一的变化是现在会引发错误。
Math.random()
is no longer replaced by the integrated seedable PRNG when State.prng.init()
is called. See either the built-in functions random()
& randomFloat()
or the State.random()
method, if you need direct access to the PRNG—since it returns a call to either Math.random()
or the seedable PRNG, as appropriate.
当调用 State.prng.init()
时, Math.random()
将不再被集成的可播种伪随机数生成器替换。如果需要直接访问伪随机数生成器,请参阅内置函数 random()
& randomFloat()
或 State.random()
方法——因为它会根据需要返回对 Math.random()
或可播种伪随机数生成器的调用。
The Macros
API object has been renamed to Macro
and several of its methods have also changed, for better consistency with the other APIs. Furthermore, it is no longer instantiated into the legacy macros
object—which still exists, so SugarCube-compatible legacy macros will continue to work. See the Macro
API docs for more information.
Macros
API 对象已被重命名为 Macro
,并且其一些方法也进行了更改,以更好地与其他 API 保持一致性。此外,它不再实例化为传统的 macros
对象——该对象仍然存在,因此与 SugarCube 兼容的传统宏将继续工作。有关更多信息,请参阅 Macro
API 文档。
Macro 宏 | Change 修改 |
---|---|
<<back>> & <<return>> |
Replaced the ungainly link text syntax—<<back::linktext "…">> /<<return::linktext "…">> —with l10nStrings object properties—l10nStrings.macroBackText and l10nStrings.macroReturnText .将笨拙的链接文本语法( <<back::linktext "…">> / <<return::linktext "…">> )替换为 l10nStrings 对象属性( l10nStrings.macroBackText 和 l10nStrings.macroReturnText )。 |
<<if>> & <<elseif>> |
The <<if>> macro will now, optionally, return an error if the JavaScript = assignment operator is used (default: enabled). Configured via the Config.macros.ifAssignmentError config property.现在, <<if>> 宏将可选地返回错误,如果使用 JavaScript = 赋值运算符(默认:启用)。通过 Config.macros.ifAssignmentError 配置属性进行配置。 |
Options macros 选项宏 | The various Options macros have been removed. See the Options system section for more information. 各种选项宏已被移除。请参阅选项系统部分以获取更多信息。 |
The entire Options system—MenuOptions
special passage, options
special variable, and associated macros—has been scrapped for numerous reasons—it was always a hack, required copious amounts of boilerplate code to be useful, etc. It is replaced by the Setting
API and settings
special variable. See the Setting
API docs for more information.
由于诸多原因,整个选项系统( MenuOptions
特殊段落, options
特殊变量以及相关宏)已被废弃——它始终是一个漏洞,需要大量样板代码才能发挥作用等。它被 Setting
API 和 settings
特殊变量所取代。请参阅 Setting
API 文档以获取更多信息。
The SaveSystem
API object has been renamed to Save
and several of its methods have also changed, for better consistency with the other APIs. See the Save
API docs for more information.
SaveSystem
API 对象已被重命名为 Save
,并且其部分方法也进行了更改,以更好地与其他 API 保持一致性。请参阅 Save
API 文档以获取更多信息。
The UISystem
API object has been split into two APIs Dialog
and UI
, and some of its methods have also changed. In particular, the parameter list for the Dialog.setup()
method has changed. See the Dialog
API and UI
API docs for more information.
UISystem
API 对象已拆分为两个 API Dialog
和 UI
,其中一些方法也发生了变化。特别是, Dialog.setup()
方法的参数列表已更改。请参阅 Dialog
API 和 UI
API 文档以获取更多信息。
This is a reference for localizing SugarCube's default UI text, in general, and its l10nStrings
object specifically.
这是本地化 SugarCube 默认 UI 文本的参考,特别是其 l10nStrings
对象。
Note:
If you're simply looking to download ready-to-use localizations, see SugarCube's website (under Downloads > Localizations).
注意:如果您只是想下载现成的本地化版本,请访问 SugarCube 网站(在“下载”>“本地化”下)。
v2.0.0
: Introduced. v2.0.0
: 引入。v2.10.0
: Added l10nStrings
object. Deprecated strings
object.l10nStrings
对象。已弃用 strings
对象。strings
vs. l10nStrings
strings
与 l10nStrings
的说明Prior to SugarCube v2.10.0
, the strings localization object was named strings
. The new l10nStrings
object has a simpler, flatter, set of properties and better support for replacement strings. Unfortunately, this means that the two objects are incompatible.
在 SugarCube v2.10.0
之前,字符串本地化对象被命名为 strings
。新的 l10nStrings
对象具有更简单、更扁平的属性集,并更好地支持替换字符串。不幸的是,这意味着这两个对象不兼容。
To ensure backwards compatibility of existing strings
objects, if one exists within a project's scripts, the older object is mapped to the new l10nStrings
object.
为确保现有 strings
对象的向后兼容性,如果项目脚本中存在,则将旧对象映射到新的 l10nStrings
对象。
The capitalization and punctuation used within the default replacement strings is deliberate, especially within the error and warning strings. You would do well to keep your translations similar when possible.
默认替换字符串中使用的首字母大小写和标点符号是故意的,尤其是在错误和警告字符串中。在可能的情况下,请尽量保持翻译的相似性。
Replacement patterns have the format {NAME}
—e.g., {textIdentity}
—where NAME is the name of a property within either the l10nStrings
object or, in a few cases, an object supplied locally where the string is used—these instances will be commented.
替换模式具有以下格式 {NAME}
——例如, {textIdentity}
——其中 NAME 是 l10nStrings
对象中或,在少数情况下,是本地提供的对象中某个属性的名称——这些实例将被注释。
By convention, properties starting with an underscore—e.g., _warningOutroDegraded
—are used as templates, only being included within other localized strings. Feel free to add your own if that makes localization easier—e.g., for gender, plurals, and whatnot. As an example, the default replacement strings make use of this to handle various warning intros and outros.
按照惯例,以下划线开头的属性——例如, _warningOutroDegraded
——用作模板,仅在其他本地化字符串中包含。如果这使本地化更容易,请随时添加自己的模板——例如,用于性别、复数等。例如,默认替换字符串就是利用这一点来处理各种警告开头和结尾。
In use, replacement patterns are replaced recursively, so replacement strings may contain patterns whose replacements contain other patterns. Because replacement is recursive, care must be taken to ensure infinite loops are not created—the system will detect an infinite loop and throw an error.
在使用过程中,替换模式会递归地替换,因此替换字符串可能包含其替换内容中还有其他模式的模式。由于替换是递归的,必须小心以确保不会创建无限循环——系统将检测到无限循环并抛出错误。
Properties on the strings localization object (l10nStrings
) should be set within your project's JavaScript section (Twine 2: the Story JavaScript; Twine 1/Twee: a script
-tagged passage) to override the defaults.
字符串本地化对象( l10nStrings
)的属性应在您的项目 JavaScript 部分(Twine 2:故事 JavaScript;Twine 1/Twee:带有 script
标签的段落)中设置,以覆盖默认值。
For the template that should be used as the basis of localizations, see the locale/l10n-template.js
file @github.com.
关于用作本地化基础的模板,请参阅 locale/l10n-template.js
文件@github.com。
// Changing the project's reported identity to "story"
l10nStrings.textIdentity = "story";
// Changing the text of all dialog OK buttons to "Eeyup"
l10nStrings.ok = "Eeyup";
// Localizing the title of the Restart dialog (n.b. machine translations, for example only)
l10nStrings.restartTitle = "Neustart"; // German (de)
l10nStrings.restartTitle = "Reiniciar"; // Spanish (es)