fr-esco / php-dice
通用的RPG骰子滚动语法和库。
v1.0.0
2016-05-03 12:16 UTC
Requires
- php: >=5.4
This package is not auto-updated.
Last update: 2024-09-20 18:54:10 UTC
README
通用的RPG骰子滚动语法和库。
入门
php-dice设计为即插即用。这意味着安装需要最少的步骤。
下载
可以使用composer安装php-dice。运行以下命令下载并安装php-dice
composer require "fr-esco/php-dice"
用法
如index.php所示,一旦引入库,您就可以实例化解析器
$parser = new dice\Parser;
然后,您可以解析您的表达式
$result = $parser->parse($expression);
在您的代码中稍后,您可以评估解析结果,返回的对象可以用于调试目的
$result->evaluate();
最后,您可以分别运行以打印解析表达式的原始字符串表示或其美化版本
echo $result; # or echo $result->render();
最终结果存储在其value属性中。
$result->value;
异常处理
您应该始终在try / catch块中封装解析阶段
try { $result = $parser->parse($expression); } catch (dice\SyntaxError $ex) { $stack = ['Syntax error:', $ex->getMessage(), 'At line', $ex->grammarLine, 'column', $ex->grammarColumn, 'offset', $ex->grammarOffset]; echo implode(' ', $stack); }
自定义
您还可以提供自定义的范围,其中包含要评估的附加函数或变量
$result = $parser->parse($expression, [ 'foo' => 2, 'bar' => function () { return 3; }, ], '\custom\namespace\Scope');
您可以使用关联数组提供自定义范围,键可以是您表达式中可能出现的至少2个字符长的字符串,值可以是任何数字或要执行的功能(有关示例,请参阅DefaultScope实现)。
您还可以指定自己的Scope类,该类必须扩展dice\Scope。
示例
- 表达式(不区分大小写):
d6 + foo * bar() / defaultSides + min(d12, 2d4) + rerollBelow(5, 3d6) - 评估后渲染:
{ 1d6 : [ 2 ] } + { foo : 2 } * { bar ( ): 3 } / { defaultSides : 6 } + { min ( { 1d12 : [ 10 ] }, { 2d4 : [ 1, 2 ] } ): 3 } + { rerollBelow ( 5, { 3d6 : [ 6, 6, 4 ] } ): 18 } - 字符串化版本:
1d6 + foo * bar() / defaultSides + min(1d12, 2d4) + rerollBelow(5, 3d6) - 值(掷骰子结果):
24
开发
技术栈
语法是用PEG.js构建的。其PHP版本是由php-pegjs生成的。
自定义
如果您需要自定义grammar/dice.pegphp,您可以通过JavaScript重新生成src/Parser
# Install node modules npm install # Build dice\Parser for PHP npm run build
视觉测试
使用您喜欢的web服务器提供index.php,然后浏览到https:///php-dice/index.php。
您可以在文本框中输入要解析的表达式,并通过点击“掷骰子”按钮提交表单。
详细信息将在下方显示。
许可
php-dice在MIT许可下发布。有关详细信息,请参阅附带的LICENSE.md。