kusabi / dice
PHP桌面骰子库
1.0.2
2020-11-06 14:29 UTC
Requires
- php: >=5.6
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- phpunit/phpunit: ^5.7
- symfony/var-dumper: ^3.4
README
一个用于模拟桌面游戏(如《龙与地下城》)骰子的库。
兼容性和依赖项
此库与PHP版本5.6、7.0、7.1、7.2、7.3和7.4兼容。
此库没有依赖项。
安装
使用composer安装非常简单。
composer require kusabi/dice
或者只需将其添加到您的composer.json
文件中
{ "require": { "kusabi/dice": "^1.0" } }
使用库
使用库的最简单方法是使用Dice工厂类。
一个简单的例子是
use Kusabi\Dice\DiceFactory; $result = DiceFactory::createFromString('5d12+4')->getRoll();
使用骰子类
此库包含4种骰子实现,当一起使用时可以模拟大量的可能性。
第一个类是Dice
。
Dice
对象可以代表桌面游戏中大多数基本的投掷。
它接受3个可选参数来设置面数、乘数和偏移量。
如果没有参数,它将默认代表1d6。
use Kusabi\Dice\Dice; $dice = new Dice(12, 2, 5); $min = $dice->getMinimumRoll(); $max = $dice->getMaximumRoll(); $result = $dice->getRoll(); $string = (string) $dice; // 2d12+5
使用单个骰子类
其他三个骰子类可以组合使用,以创建更复杂的骰子设置。
第一个是SingleDice
。一个SingleDice
对象接受一个参数,表示其面数。
use Kusabi\Dice\SingleDice; $dice = new SingleDice(4); $min = $dice->getMinimumRoll(); $max = $dice->getMaximumRoll(); $result = $dice->getRoll(); $string = (string) $dice; // 1d4
使用骰子修饰器类
DiceModifier
类使用装饰器模式来增强DiceInterface
另一个实现的输出。
它接受两个参数,第一个是实现DiceInterface
的对象,第二个是用于增强结果的整数。
下面的示例模拟了如何表示1D12+4
。
use Kusabi\Dice\SingleDice; use Kusabi\Dice\DiceModifier; $dice = new DiceModifier(New SingleDice(12), 4); $min = $dice->getMinimumRoll(); $max = $dice->getMaximumRoll(); $result = $dice->getRoll();
使用骰子组类
DiceGroup
可以将多个DiceInterface
实现组合在一起,并返回所有这些实现的输出总和。
因为其中之一可以是Dice
、SingleDice
、DiceModifier
或甚至另一个DiceGroup
,并且因为此对象本身可以放入一个DiceModifier
实例中,所以可能性相当充分。
下面的示例模拟了如何表示5D12+4
。
use Kusabi\Dice\Dice; use Kusabi\Dice\DiceModifier; use Kusabi\Dice\DiceGroup; use Kusabi\Dice\SingleDice; $dice = new DiceModifier( new DiceGroup( new SingleDice(12), new SingleDice(12), new SingleDice(12), new Dice(12), new Dice(12) ), 4 ); $min = $dice->getMinimumRoll(); $max = $dice->getMaximumRoll(); $result = $dice->getRoll();
使用骰子工厂
DiceFactory
使创建骰子实现变得简单。
您可以直接传递骰子的常用字符串形式,而不是找出如何构建它。
use Kusabi\Dice\DiceFactory; $dice = DiceFactory::createFromString('5d12+4'); $min = $dice->getMinimumRoll(); $max = $dice->getMaximumRoll(); $result = $dice->getRoll();
或者更简单
use Kusabi\Dice\DiceFactory; $result = DiceFactory::createFromString('5d12+4')->getRoll();
如果类无法解析字符串,将抛出/InvalidArgumentException
,因此请确保您有相应的计划。
use Kusabi\Dice\DiceFactory; try { $result = DiceFactory::createFromString('5d12+4')->getRoll(); } catch(\InvalidArgumentException $exception) { echo "Could not parse the string"; }