> For the complete documentation index, see [llms.txt](https://raster.gitbook.io/zh-hans_choicescript-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://raster.gitbook.io/zh-hans_choicescript-guide/rand.md).

# Rand

## 随机｜Rand

`*rand` 命令用于在指定范围内（例如 0-100）生成随机数，并将该值赋给一个数值\[\[变量类型|变量]]。

{% hint style="info" %}
请注意

如果您想将玩家引导至一个完全随机的\[\[场景]]文件，有一个专门用于此目的的命令：\[\[Goto random scene|\*goto\_random\_scene]]
{% endhint %}

## 用法｜Usage

`*rand` 通常与一个根据需要创建的新的 `*temp` 变量一起使用，但您也可以对在 \[\[startup.txt]] 中创建的任何数值变量使用 `*rand`。

```
*temp dieroll 0

*rand dieroll 0 7
```

在上述示例中，我们创建了一个名为"dieroll"的临时变量，然后为其分配了一个介于 0 到 7 之间（包含 0 和 7）的随机值。

现在，我们可以像使用其他数值变量一样使用变量"dieroll"，通常是在 `*if` 语句中。

## 注意事项与技巧｜Notes and tips

如果您倾向于在不同时间、出于多种不同目的频繁使用 `*rand`，那么最好在 `startup.txt` 中为此目的（例如 dieroll）声明一个单一的数值变量，并在需要时直接使用它——这至少可以避免您反复临时创建新的 `*temp` 变量。

注意：在 ChoiceScript 游戏中过度使用随机性会使全面测试所有可能性变得更加困难。

## 已知的 `*rand` 相关 bug 及解决方法｜Known `*rand`-related bug & workaround

ChoiceScript 中存在一个与 `*rand` 相关的小 bug。如果玩家当前处于使用了 `*rand` 的场景页面时选择进入状态界面，那么在退出状态界面并返回该场景页面时，`*rand` 命令会再次运行，生成新的随机值。

根据您使用 `*rand` 的具体情况，某些时候这可能不会造成太大影响。但如果会产生影响——或者您只是无法确定——防止此问题的解决方法是：将 `*rand` 命令放置在与实际使用其生成值的页面分开（即前一个）的“页面”上，例如放在更早的 `*choice` 或 `*page_break` 之前。采用类似以下的方式应该就足够了：

```
You carefully open the chest at arm's length, wary of traps . . .

*temp treasure

*rand treasure 50 100

*page_break It creaks open . . .

You gasp in amazement, finding ${treasure} gold coins in the chest!

*set gold + treasure
```

在上述情况下，若缺少那个至关重要的 `*page_break` 指令，每当玩家进入并退出状态界面时——只要他或她仍停留在该特定场景页面——`*rand` 命令就会重新运行（且“宝藏”的显示数值将随之改变）。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://raster.gitbook.io/zh-hans_choicescript-guide/rand.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
