Compare commits
93 Commits
Author | SHA1 | Date |
---|---|---|
projectmoon | 86df3c5d1f | |
projectmoon | 38a7e50c5c | |
projectmoon | e309fd1fc6 | |
projectmoon | 9262fe2cac | |
projectmoon | 724a781e7c | |
projectmoon | ef074beb96 | |
projectmoon | 81a69f329a | |
projectmoon | c9e7efa61d | |
projectmoon | f295f2b7b6 | |
projectmoon | 090ce9be45 | |
projectmoon | 2a6dff3e07 | |
projectmoon | 952f35d53a | |
projectmoon | 552daa4746 | |
projectmoon | c514b85510 | |
projectmoon | 6eb81f43d5 | |
projectmoon | 44b1e0f649 | |
projectmoon | a8ccdc9cce | |
projectmoon | 13ce7b3ee6 | |
projectmoon | 6f09a11586 | |
projectmoon | ee3ec18e06 | |
projectmoon | 126548d868 | |
Matthew Sparks | 7e7e9e534e | |
Matthew Sparks | 2d9853fbf0 | |
Matthew Sparks | 3d6210b32d | |
Matthew Sparks | 8b5973475f | |
Matthew Sparks | 1992ef4e08 | |
Matthew Sparks | f904e3a948 | |
Matthew Sparks | 8317f40f61 | |
Matthew Sparks | 069ee47364 | |
Matthew Sparks | dc242182f4 | |
Matthew Sparks | 15163ac11d | |
Matthew Sparks | 1860eaf378 | |
Matthew Sparks | 2654887d8c | |
projectmoon | 125f3d0cee | |
projectmoon | a4c3d34a97 | |
projectmoon | 86fbb05e54 | |
projectmoon | 661a943672 | |
projectmoon | d65715dee6 | |
projectmoon | 55a3bfb861 | |
projectmoon | 0050810182 | |
projectmoon | 3ba546d4a4 | |
projectmoon | ffded7b572 | |
projectmoon | cf93d14913 | |
projectmoon | cf6dd96b34 | |
projectmoon | c8c6f4d6f0 | |
projectmoon | 2488429edb | |
projectmoon | f68d5ffcc1 | |
projectmoon | 473e899275 | |
projectmoon | 1f03837bfe | |
projectmoon | 0059e3d133 | |
matthew | 915b82d0aa | |
projectmoon | cab856241d | |
projectmoon | 764426382a | |
projectmoon | b4321721c4 | |
projectmoon | 494d28486e | |
projectmoon | b7393c1907 | |
projectmoon | 3d2eb14cd3 | |
projectmoon | 53339282e0 | |
projectmoon | 7050cf037a | |
projectmoon | 0c0ddafd03 | |
projectmoon | 7f0bdc1e82 | |
projectmoon | 0ca7ad4db0 | |
projectmoon | 59be127430 | |
projectmoon | e9c0a184bd | |
projectmoon | 589d0e0dbf | |
projectmoon | 892ccf73e3 | |
projectmoon | 896acee5ba | |
projectmoon | d70df44d2a | |
projectmoon | 5f15e62c6d | |
projectmoon | ed3b582aad | |
projectmoon | 49db0062a3 | |
projectmoon | 4ae871224a | |
projectmoon | 1ebd13e912 | |
projectmoon | 8f5b6f0636 | |
projectmoon | 5b3d174edc | |
projectmoon | 495df13fe6 | |
projectmoon | de92fc8488 | |
projectmoon | b05129ad9f | |
projectmoon | 5d002e5063 | |
projectmoon | 849a1b6a14 | |
projectmoon | 97be5d5ccb | |
projectmoon | 395753e8a9 | |
projectmoon | df0248d99a | |
projectmoon | 76214bc790 | |
projectmoon | 921c4cd644 | |
projectmoon | 8c2a90e86b | |
projectmoon | 926dae57fb | |
projectmoon | 4557498ac6 | |
projectmoon | ca34841d86 | |
projectmoon | c1ec7366e4 | |
projectmoon | a84d4fd869 | |
projectmoon | 34ee2c6e5d | |
projectmoon | 9de74d05a9 |
|
@ -3,18 +3,20 @@ name: build-and-test
|
|||
|
||||
steps:
|
||||
- name: test
|
||||
image: rust:1.51
|
||||
image: rust:1.80
|
||||
commands:
|
||||
- apt-get update
|
||||
- apt-get install -y cmake
|
||||
- rustup component add rustfmt
|
||||
- cargo build --verbose --all
|
||||
- cargo test --verbose --all
|
||||
|
||||
- name: docker
|
||||
image: plugins/docker
|
||||
when:
|
||||
branch:
|
||||
- master
|
||||
ref:
|
||||
- refs/tags/v*
|
||||
- refs/heads/master
|
||||
settings:
|
||||
auto_tag: true
|
||||
username:
|
||||
|
|
File diff suppressed because it is too large
Load Diff
48
Cargo.toml
48
Cargo.toml
|
@ -1,44 +1,6 @@
|
|||
[package]
|
||||
name = "tenebrous-dicebot"
|
||||
version = "0.10.0"
|
||||
authors = ["Taylor C. Richberger <taywee@gmx.com>", "projectmoon <projectmoon@agnos.is>"]
|
||||
edition = "2018"
|
||||
license = 'AGPL-3.0-or-later'
|
||||
description = 'An async Matrix dice bot for role-playing games'
|
||||
readme = 'README.md'
|
||||
repository = 'https://git.agnos.is/projectmoon/matrix-dicebot'
|
||||
keywords = ["games", "dice", "matrix", "bot"]
|
||||
categories = ["games"]
|
||||
[workspace]
|
||||
|
||||
[dependencies]
|
||||
log = "0.4"
|
||||
tracing-subscriber = "0.2"
|
||||
toml = "0.5"
|
||||
nom = "5"
|
||||
rand = "0.8"
|
||||
thiserror = "1.0"
|
||||
itertools = "0.10"
|
||||
async-trait = "0.1"
|
||||
url = "2.1"
|
||||
dirs = "3.0"
|
||||
indoc = "1.0"
|
||||
combine = "4.5"
|
||||
futures = "0.3"
|
||||
html2text = "0.2"
|
||||
phf = { version = "0.8", features = ["macros"] }
|
||||
matrix-sdk = { git = "https://github.com/matrix-org/matrix-rust-sdk", branch = "master" }
|
||||
refinery = { version = "0.5", features = ["rusqlite"]}
|
||||
barrel = { version = "0.6", features = ["sqlite3"] }
|
||||
tempfile = "3"
|
||||
|
||||
[dependencies.sqlx]
|
||||
version = "0.5"
|
||||
features = [ "offline", "sqlite", "runtime-tokio-native-tls" ]
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1"
|
||||
features = ['derive']
|
||||
|
||||
[dependencies.tokio]
|
||||
version = "1"
|
||||
features = [ "full" ]
|
||||
members = [
|
||||
"dicebot",
|
||||
"rpc"
|
||||
]
|
||||
|
|
14
Dockerfile
14
Dockerfile
|
@ -1,16 +1,15 @@
|
|||
# Builder image with development dependencies.
|
||||
FROM bougyman/voidlinux:glibc as builder
|
||||
FROM ghcr.io/void-linux/void-linux:latest-mini-x86_64 as builder
|
||||
RUN xbps-install -S
|
||||
RUN xbps-install -yu xbps
|
||||
RUN xbps-install -Syu
|
||||
RUN xbps-install -Sy base-devel rustup cargo cmake wget gnupg
|
||||
RUN xbps-install -Sy base-devel rustup cmake wget gnupg
|
||||
RUN xbps-install -Sy openssl-devel libstdc++-devel
|
||||
RUN rustup-init -qy
|
||||
|
||||
# Install tini for signal processing and zombie killing
|
||||
ENV TINI_VERSION v0.19.0
|
||||
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /usr/local/bin/tini
|
||||
ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini.asc /tini.asc
|
||||
RUN gpg --batch --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 595E85A6B1B4779EA4DAAEC70B588DFF0527A9B7 \
|
||||
&& gpg --batch --verify /tini.asc /usr/local/bin/tini
|
||||
RUN chmod +x /usr/local/bin/tini
|
||||
|
||||
# Build dicebot
|
||||
|
@ -20,7 +19,10 @@ ADD . ./
|
|||
RUN . /root/.cargo/env && cargo build --release
|
||||
|
||||
# Final image
|
||||
FROM bougyman/voidlinux:tiny
|
||||
FROM ghcr.io/void-linux/void-linux:latest-mini-x86_64
|
||||
RUN xbps-install -S
|
||||
RUN xbps-install -yu xbps
|
||||
RUN xbps-install -Syu
|
||||
RUN xbps-install -Sy ca-certificates libstdc++
|
||||
COPY --from=builder \
|
||||
/root/src/target/release/dicebot \
|
||||
|
|
14
LICENSE
14
LICENSE
|
@ -1,16 +1,12 @@
|
|||
This software project is governed by the terms of the Affero GNU
|
||||
General Public License. Portions of the code come from the original
|
||||
This software is governed by the terms of the Affero GNU General
|
||||
Public License. Portions of the code come from the original
|
||||
MIT-licensed project, and the terms of the MIT license also apply to
|
||||
those portions. Some portions of the code are also taken from the Rust
|
||||
Matrix SDK examples, which are governed by the MIT license. In files
|
||||
that are partially or wholly subject to the MIT license in addition to
|
||||
the Affero GNU General Public License, this is noted with a header at
|
||||
the top of the file.
|
||||
those portions. In files that are partially or wholly subject to the
|
||||
MIT license in addition to the Affero GNU General Public License, this
|
||||
is noted with a header at the top of the file.
|
||||
|
||||
Original upstream project: https://gitlab.com/Taywee/axfive-matrix-dicebot
|
||||
|
||||
Rust Matrix SDK: https://github.com/matrix-org/matrix-rust-sdk
|
||||
|
||||
For code from the original project that is governed by the MIT license
|
||||
in addition to the Affero GNU General Public License, the following
|
||||
terms apply:
|
||||
|
|
48
README.md
48
README.md
|
@ -1,6 +1,7 @@
|
|||
# Tenebrous Dicebot
|
||||
|
||||
[![Build Status](https://drone.agnos.is/api/badges/projectmoon/tenebrous-dicebot/status.svg)](https://drone.agnos.is/projectmoon/tenebrous-dicebot)
|
||||
[![Matrix Chat](https://img.shields.io/matrix/tenebrous:agnos.is?label=matrix&server_fqdn=matrix.org)][matrix-room]
|
||||
|
||||
_This repository is hosted on [Agnos.is Git][main-repo] and mirrored
|
||||
to [GitHub][github-repo]._
|
||||
|
@ -24,6 +25,23 @@ System.
|
|||
* Works in encrypted or unencrypted Matrix rooms.
|
||||
* Storing variables created by the user.
|
||||
|
||||
## Support and Community
|
||||
|
||||
The project has a Matrix room at [#tenebrous:agnos.is][matrix-room].
|
||||
It is also possible to make a post in [GitHub
|
||||
Discussions][github-discussions].
|
||||
|
||||
For reporting bugs, we prefer that you open an issue on
|
||||
[git.agnos.is][agnosis-git-issues]. However, you may also open an
|
||||
issue on [GitHub][github-issues].
|
||||
|
||||
### Development and Contributions
|
||||
|
||||
All development occurs on [git.agnos.is][main-repo]. If you wish to
|
||||
contribute, please open a pull request there. In some cases, pull
|
||||
requests from GitHub may be accepted. All contributions must be
|
||||
licensed under [AGPL 3.0 or later][agpl] to be accepted.
|
||||
|
||||
## Building and Installation
|
||||
|
||||
### Docker Image
|
||||
|
@ -46,6 +64,17 @@ root of the repository.
|
|||
After pulling or building the image, see [instructions on how to use
|
||||
the Docker image](#running-the-bot).
|
||||
|
||||
### Install from crates.io
|
||||
|
||||
The project can be from [crates.io][crates-io]. To install it, execute
|
||||
`cargo install tenebrous-dicebot`. This will make the following
|
||||
executables available on your system:
|
||||
|
||||
* `dicebot`: Main dicebot executable.
|
||||
* `dicebot-cmd`: Run dicebot commands from the command line.
|
||||
* `dicebot_migrate`: Standalone database migrator (not required).
|
||||
* `tonic_client`: Test client for the gRPC connection (not required).
|
||||
|
||||
### Build from Source
|
||||
|
||||
Precompiled executables are not yet available. Clone this repository
|
||||
|
@ -89,8 +118,16 @@ expressions.
|
|||
!r 3d12 - 5d2 + 3 - 7d3 + 20d20
|
||||
```
|
||||
|
||||
This system does not yet have the capability to handle things like D&D
|
||||
5e advantage or disadvantage.
|
||||
#### Keep/Drop Dice
|
||||
The bot supports either keeping the highest dice in a roll, or
|
||||
dropping the highest dice in a roll. This allows the bot to handle
|
||||
things like D&D 5e advantage or disadvantage.
|
||||
|
||||
```
|
||||
!roll 2d20k1
|
||||
!r 2d20dh1 + 5
|
||||
!r 10d10k5 + 10d10dh5 - 2
|
||||
```
|
||||
|
||||
### Storytelling System
|
||||
|
||||
|
@ -241,6 +278,7 @@ The most basic plans are:
|
|||
* Perhaps some sort of character sheet integration. But for that, we
|
||||
would need a sheet service.
|
||||
* Use environment variables instead of config file in Docker image.
|
||||
* Per-system game rules.
|
||||
|
||||
## Credits
|
||||
|
||||
|
@ -254,3 +292,9 @@ support added for Chronicles of Darkness and Call of Cthulhu.
|
|||
[main-repo]: https://git.agnos.is/projectmoon/tenebrous-dicebot
|
||||
[github-repo]: https://github.com/ProjectMoon/matrix-dicebot
|
||||
[roadmap]: https://git.agnos.is/projectmoon/tenebrous-dicebot/wiki/Roadmap
|
||||
[crates-io]: https://crates.io/crates/tenebrous-dicebot
|
||||
[matrix-room]: https://matrix.to/#/#tenebrous:agnos.is
|
||||
[agnosis-git-issues]: https://git.agnos.is/projectmoon/tenebrous-dicebot/issues
|
||||
[github-discussions]: https://github.com/ProjectMoon/matrix-dicebot/discussions
|
||||
[github-issues]: https://github.com/ProjectMoon/matrix-dicebot/issues
|
||||
[agpl]: https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
|
|
@ -0,0 +1,57 @@
|
|||
[package]
|
||||
name = "tenebrous-dicebot"
|
||||
version = "0.13.2"
|
||||
rust-version = "1.68"
|
||||
authors = ["projectmoon <projectmoon@agnos.is>", "Taylor C. Richberger <taywee@gmx.com>"]
|
||||
edition = "2018"
|
||||
license = 'AGPL-3.0-or-later'
|
||||
description = 'An async Matrix dice bot for role-playing games'
|
||||
readme = '../README.md'
|
||||
repository = 'https://git.agnos.is/projectmoon/matrix-dicebot'
|
||||
keywords = ["games", "dice", "matrix", "bot"]
|
||||
categories = ["games"]
|
||||
|
||||
[build-dependencies]
|
||||
tonic-build = "0.4"
|
||||
|
||||
[dependencies]
|
||||
# indexmap version locked fixes a dependency cycle.
|
||||
# indexmap = "=1.6.2"
|
||||
log = "0.4"
|
||||
tracing-subscriber = "0.2"
|
||||
toml = "0.5"
|
||||
nom = "5"
|
||||
rand = "0.8"
|
||||
rust-argon2 = "0.8"
|
||||
thiserror = "1.0"
|
||||
itertools = "0.10"
|
||||
async-trait = "0.1"
|
||||
url = "2.1"
|
||||
dirs = "3.0"
|
||||
indoc = "1.0"
|
||||
combine = "4.5"
|
||||
futures = "0.3"
|
||||
html2text = "0.2"
|
||||
phf = { version = "0.8", features = ["macros"] }
|
||||
matrix-sdk = { version = "0.6" }
|
||||
refinery = { version = "0.8", features = ["rusqlite"]}
|
||||
barrel = { version = "0.7", features = ["sqlite3"] }
|
||||
strum = { version = "0.22", features = ["derive"] }
|
||||
tempfile = "3"
|
||||
substring = "1.4"
|
||||
fuse-rust = "0.2"
|
||||
tonic = "0.4"
|
||||
prost = "0.7"
|
||||
tenebrous-rpc = { path = "../rpc", version = "0.1.0" }
|
||||
|
||||
[dependencies.sqlx]
|
||||
version = "0.6"
|
||||
features = [ "offline", "sqlite", "runtime-tokio-native-tls" ]
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1"
|
||||
features = ['derive']
|
||||
|
||||
[dependencies.tokio]
|
||||
version = "1"
|
||||
features = [ "full" ]
|
|
@ -18,6 +18,26 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"26903a92a7de34df3e227fe599e41ae1bb61612eb80befad398383af36df0ce4": {
|
||||
"query": "DELETE FROM accounts WHERE user_id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
}
|
||||
},
|
||||
"2d4a32735da04509c2e3c4f99bef79ef699964f58ae332b0611f3de088596e1e": {
|
||||
"query": "INSERT INTO accounts (user_id, password, account_status)\n VALUES (?, ?, ?)\n ON CONFLICT(user_id) DO\n UPDATE SET password = ?, account_status = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 5
|
||||
},
|
||||
"nullable": []
|
||||
}
|
||||
},
|
||||
"59313c67900a1a9399389720b522e572f181ae503559cd2b49d6305acb9e2207": {
|
||||
"query": "SELECT key, value as \"value: i32\" FROM user_variables\n WHERE room_id = ? AND user_id = ?",
|
||||
"describe": {
|
||||
|
@ -60,6 +80,16 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"667b26343ce44e1c48ac689ce887ef6a0558a2ce199f7372a5dce58672499c5a": {
|
||||
"query": "INSERT INTO user_state (user_id, active_room)\n VALUES (?, ?)\n ON CONFLICT(user_id) DO\n UPDATE SET active_room = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 3
|
||||
},
|
||||
"nullable": []
|
||||
}
|
||||
},
|
||||
"711d222911c1258365a6a0de1fe00eeec4686fd3589e976e225ad599e7cfc75d": {
|
||||
"query": "SELECT count(*) as \"count: i32\" FROM user_variables\n WHERE room_id = ? and user_id = ?",
|
||||
"describe": {
|
||||
|
@ -78,66 +108,6 @@
|
|||
]
|
||||
}
|
||||
},
|
||||
"7248c8ae30bbe4bc5866e80cc277312c7f8cb9af5a8801fd8eaf178fd99eae18": {
|
||||
"query": "SELECT room_id FROM room_users\n WHERE username = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "room_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
}
|
||||
},
|
||||
"97f5d58f62baca51efd8c295ca6737d1240923c69c973621cd0a718ac9eed99f": {
|
||||
"query": "SELECT room_id, room_name FROM room_info\n WHERE room_id = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "room_id",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
},
|
||||
{
|
||||
"name": "room_name",
|
||||
"ordinal": 1,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false,
|
||||
false
|
||||
]
|
||||
}
|
||||
},
|
||||
"b302d586e5ac4c72c2970361ea5a5936c0b8c6dad10033c626a0ce0404cadb25": {
|
||||
"query": "SELECT username FROM room_users\n WHERE room_id = ?",
|
||||
"describe": {
|
||||
"columns": [
|
||||
{
|
||||
"name": "username",
|
||||
"ordinal": 0,
|
||||
"type_info": "Text"
|
||||
}
|
||||
],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": [
|
||||
false
|
||||
]
|
||||
}
|
||||
},
|
||||
"bba0fc255e7c30d1d2d9468c68ba38db6e8a13be035aa1152933ba9247b14f8c": {
|
||||
"query": "SELECT event_id FROM room_events\n WHERE room_id = ? AND event_id = ?",
|
||||
"describe": {
|
||||
|
@ -155,5 +125,15 @@
|
|||
false
|
||||
]
|
||||
}
|
||||
},
|
||||
"dce9bb45cf954054a920ee8b53852c6d562e3588d76bbfaa1433d8309d4e4921": {
|
||||
"query": "DELETE FROM user_state WHERE user_id = ?",
|
||||
"describe": {
|
||||
"columns": [],
|
||||
"parameters": {
|
||||
"Right": 1
|
||||
},
|
||||
"nullable": []
|
||||
}
|
||||
}
|
||||
}
|
|
@ -6,23 +6,52 @@
|
|||
use std::fmt;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
||||
//Old stuff, for regular dice rolling. To be moved elsewhere.
|
||||
|
||||
/// A basic dice roll, in XdY notation, like "1d4" or "3d6".
|
||||
/// Optionally supports D&D advantage/disadvantge keep-or-drop
|
||||
/// functionality.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub struct Dice {
|
||||
pub(crate) count: u32,
|
||||
pub(crate) sides: u32,
|
||||
pub(crate) keep_drop: KeepOrDrop,
|
||||
}
|
||||
|
||||
/// Enum indicating how to handle bonuses or penalties using extra
|
||||
/// dice. If set to Keep, the roll will keep the highest X number of
|
||||
/// dice in the roll, and add those together. If set to Drop, the
|
||||
/// opposite is performed, and the lowest X number of dice are added
|
||||
/// instead. If set to None, then all dice in the roll are added up as
|
||||
/// normal.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum KeepOrDrop {
|
||||
/// Keep only the X highest dice for adding up to the total.
|
||||
Keep(u32),
|
||||
|
||||
/// Keep only the X lowest dice (i.e. drop the highest) for adding
|
||||
/// up to the total.
|
||||
Drop(u32),
|
||||
|
||||
/// Add up all dice in the roll for the total.
|
||||
None,
|
||||
}
|
||||
|
||||
impl fmt::Display for Dice {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}d{}", self.count, self.sides)
|
||||
match self.keep_drop {
|
||||
KeepOrDrop::Keep(keep) => write!(f, "{}d{}k{}", self.count, self.sides, keep),
|
||||
KeepOrDrop::Drop(drop) => write!(f, "{}d{}dh{}", self.count, self.sides, drop),
|
||||
KeepOrDrop::None => write!(f, "{}d{}", self.count, self.sides),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dice {
|
||||
pub fn new(count: u32, sides: u32) -> Dice {
|
||||
Dice { count, sides }
|
||||
pub fn new(count: u32, sides: u32, keep_drop: KeepOrDrop) -> Dice {
|
||||
Dice {
|
||||
count,
|
||||
sides,
|
||||
keep_drop,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,360 @@
|
|||
/**
|
||||
* In addition to the terms of the AGPL, this file is governed by the
|
||||
* terms of the MIT license, from the original axfive-matrix-dicebot
|
||||
* project.
|
||||
*/
|
||||
use nom::bytes::complete::take_while;
|
||||
use nom::error::ErrorKind as NomErrorKind;
|
||||
use nom::Err as NomErr;
|
||||
use nom::{
|
||||
alt, bytes::complete::tag, character::complete::digit1, complete, many0, named,
|
||||
sequence::tuple, tag, IResult,
|
||||
};
|
||||
|
||||
use super::dice::*;
|
||||
|
||||
//******************************
|
||||
//Legacy Code
|
||||
//******************************
|
||||
|
||||
fn is_whitespace(input: char) -> bool {
|
||||
input == ' ' || input == '\n' || input == '\t' || input == '\r'
|
||||
}
|
||||
|
||||
/// Eat whitespace, returning it
|
||||
pub fn eat_whitespace(input: &str) -> IResult<&str, &str> {
|
||||
let (input, whitespace) = take_while(is_whitespace)(input)?;
|
||||
Ok((input, whitespace))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
enum Sign {
|
||||
Plus,
|
||||
Minus,
|
||||
}
|
||||
|
||||
/// Intermediate parsed value for a keep-drop expression to indicate
|
||||
/// which one it is.
|
||||
enum ParsedKeepOrDrop<'a> {
|
||||
Keep(&'a str),
|
||||
Drop(&'a str),
|
||||
NotPresent,
|
||||
}
|
||||
|
||||
macro_rules! too_big {
|
||||
($input: expr) => {
|
||||
NomErr::Error(($input, NomErrorKind::TooLarge))
|
||||
};
|
||||
}
|
||||
|
||||
/// Parse a dice expression. Does not eat whitespace
|
||||
fn parse_dice(input: &str) -> IResult<&str, Dice> {
|
||||
let (input, (count, _, sides)) = tuple((digit1, tag("d"), digit1))(input)?;
|
||||
let count: u32 = count.parse().map_err(|_| too_big!(count))?;
|
||||
let sides = sides.parse().map_err(|_| too_big!(sides))?;
|
||||
let (input, keep_drop) = parse_keep_or_drop(input, count)?;
|
||||
Ok((input, Dice::new(count, sides, keep_drop)))
|
||||
}
|
||||
|
||||
/// Extract keep/drop number as a string. Fails if the value is not a
|
||||
/// string.
|
||||
fn parse_keep_or_drop_text<'a>(
|
||||
symbol: &'a str,
|
||||
input: &'a str,
|
||||
) -> IResult<&'a str, ParsedKeepOrDrop<'a>> {
|
||||
let (parsed_kd, input) = match tuple::<&str, _, (_, _), _>((tag(symbol), digit1))(input) {
|
||||
// if ok, one of the expressions is present
|
||||
Ok((rest, (_, kd_expr))) => match symbol {
|
||||
"k" => (ParsedKeepOrDrop::Keep(kd_expr), rest),
|
||||
"dh" => (ParsedKeepOrDrop::Drop(kd_expr), rest),
|
||||
_ => panic!("Unrecogized keep-drop symbol: {}", symbol),
|
||||
},
|
||||
// otherwise absent (attempt to keep all dice)
|
||||
Err(_) => (ParsedKeepOrDrop::NotPresent, input),
|
||||
};
|
||||
|
||||
Ok((input, parsed_kd))
|
||||
}
|
||||
|
||||
/// Parse keep/drop expression, which consits of "k" or "dh" following
|
||||
/// a dice expression. For example, "1d4h3" or "1d4dh2".
|
||||
fn parse_keep_or_drop<'a>(input: &'a str, count: u32) -> IResult<&'a str, KeepOrDrop> {
|
||||
let (input, keep) = parse_keep_or_drop_text("k", input)?;
|
||||
let (input, drop) = parse_keep_or_drop_text("dh", input)?;
|
||||
|
||||
use ParsedKeepOrDrop::*;
|
||||
let keep_drop: KeepOrDrop = match (keep, drop) {
|
||||
//Potential valid Keep expression.
|
||||
(Keep(keep), NotPresent) => match keep.parse().map_err(|_| too_big!(input))? {
|
||||
_i if _i > count || _i == 0 => Ok(KeepOrDrop::None),
|
||||
i => Ok(KeepOrDrop::Keep(i)),
|
||||
},
|
||||
//Potential valid Drop expression.
|
||||
(NotPresent, Drop(drop)) => match drop.parse().map_err(|_| too_big!(input))? {
|
||||
_i if _i >= count => Ok(KeepOrDrop::None),
|
||||
i => Ok(KeepOrDrop::Drop(i)),
|
||||
},
|
||||
//No Keep or Drop specified; regular behavior.
|
||||
(NotPresent, NotPresent) => Ok(KeepOrDrop::None),
|
||||
//Anything else is an error.
|
||||
_ => Err(NomErr::Error((input, NomErrorKind::Many1))),
|
||||
}?;
|
||||
|
||||
Ok((input, keep_drop))
|
||||
}
|
||||
|
||||
// Parse a single digit expression. Does not eat whitespace
|
||||
fn parse_bonus(input: &str) -> IResult<&str, u32> {
|
||||
let (input, bonus) = digit1(input)?;
|
||||
Ok((input, bonus.parse().unwrap()))
|
||||
}
|
||||
|
||||
// Parse a sign expression. Eats whitespace.
|
||||
fn parse_sign(input: &str) -> IResult<&str, Sign> {
|
||||
let (input, _) = eat_whitespace(input)?;
|
||||
named!(sign(&str) -> Sign, alt!(
|
||||
complete!(tag!("+")) => { |_| Sign::Plus } |
|
||||
complete!(tag!("-")) => { |_| Sign::Minus }
|
||||
));
|
||||
|
||||
let (input, sign) = sign(input)?;
|
||||
Ok((input, sign))
|
||||
}
|
||||
|
||||
// Parse an element expression. Eats whitespace.
|
||||
fn parse_element(input: &str) -> IResult<&str, Element> {
|
||||
let (input, _) = eat_whitespace(input)?;
|
||||
named!(element(&str) -> Element, alt!(
|
||||
parse_dice => { |d| Element::Dice(d) } |
|
||||
parse_bonus => { |b| Element::Bonus(b) }
|
||||
));
|
||||
|
||||
let (input, element) = element(input)?;
|
||||
Ok((input, element))
|
||||
}
|
||||
|
||||
// Parse a signed element expression. Eats whitespace.
|
||||
fn parse_signed_element(input: &str) -> IResult<&str, SignedElement> {
|
||||
let (input, _) = eat_whitespace(input)?;
|
||||
let (input, sign) = parse_sign(input)?;
|
||||
let (input, _) = eat_whitespace(input)?;
|
||||
|
||||
let (input, element) = parse_element(input)?;
|
||||
let element = match sign {
|
||||
Sign::Plus => SignedElement::Positive(element),
|
||||
Sign::Minus => SignedElement::Negative(element),
|
||||
};
|
||||
Ok((input, element))
|
||||
}
|
||||
|
||||
// Parse a full element expression. Eats whitespace.
|
||||
pub fn parse_element_expression(input: &str) -> IResult<&str, ElementExpression> {
|
||||
named!(first_element(&str) -> SignedElement, alt!(
|
||||
parse_signed_element => { |e| e } |
|
||||
parse_element => { |e| SignedElement::Positive(e) }
|
||||
));
|
||||
let (input, first) = first_element(input)?;
|
||||
let (input, rest) = if input.trim().is_empty() {
|
||||
(input, vec![first])
|
||||
} else {
|
||||
named!(rest_elements(&str) -> Vec<SignedElement>, many0!(parse_signed_element));
|
||||
let (input, mut rest) = rest_elements(input)?;
|
||||
rest.insert(0, first);
|
||||
(input, rest)
|
||||
};
|
||||
|
||||
Ok((input, ElementExpression(rest)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn dice_test() {
|
||||
assert_eq!(
|
||||
parse_dice("2d4"),
|
||||
Ok(("", Dice::new(2, 4, KeepOrDrop::None)))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("20d40"),
|
||||
Ok(("", Dice::new(20, 40, KeepOrDrop::None)))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("8d7"),
|
||||
Ok(("", Dice::new(8, 7, KeepOrDrop::None)))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("2d20k1"),
|
||||
Ok(("", Dice::new(2, 20, KeepOrDrop::Keep(1))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("100d10k90"),
|
||||
Ok(("", Dice::new(100, 10, KeepOrDrop::Keep(90))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("11d10k10"),
|
||||
Ok(("", Dice::new(11, 10, KeepOrDrop::Keep(10))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("12d10k11"),
|
||||
Ok(("", Dice::new(12, 10, KeepOrDrop::Keep(11))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("12d10k13"),
|
||||
Ok(("", Dice::new(12, 10, KeepOrDrop::None)))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("12d10k0"),
|
||||
Ok(("", Dice::new(12, 10, KeepOrDrop::None)))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("20d40dh5"),
|
||||
Ok(("", Dice::new(20, 40, KeepOrDrop::Drop(5))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("8d7dh9"),
|
||||
Ok(("", Dice::new(8, 7, KeepOrDrop::None)))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_dice("8d7dh8"),
|
||||
Ok(("", Dice::new(8, 7, KeepOrDrop::None)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cant_have_both_keep_and_drop_test() {
|
||||
let res = parse_dice("1d4k3dh2");
|
||||
assert!(res.is_err());
|
||||
match res {
|
||||
Err(NomErr::Error((_, kind))) => {
|
||||
assert_eq!(kind, NomErrorKind::Many1);
|
||||
}
|
||||
_ => panic!("Got success, expected error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_number_of_dice_doesnt_crash_test() {
|
||||
let res = parse_dice("64378631476346123874527551481376547657868536d4");
|
||||
assert!(res.is_err());
|
||||
match res {
|
||||
Err(NomErr::Error((input, kind))) => {
|
||||
assert_eq!(kind, NomErrorKind::TooLarge);
|
||||
assert_eq!(input, "64378631476346123874527551481376547657868536");
|
||||
}
|
||||
_ => panic!("Got success, expected error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_number_of_sides_doesnt_crash_test() {
|
||||
let res = parse_dice("1d423562312587425472658956278456298376234876");
|
||||
assert!(res.is_err());
|
||||
match res {
|
||||
Err(NomErr::Error((input, kind))) => {
|
||||
assert_eq!(kind, NomErrorKind::TooLarge);
|
||||
assert_eq!(input, "423562312587425472658956278456298376234876");
|
||||
}
|
||||
_ => panic!("Got success, expected error"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn element_test() {
|
||||
assert_eq!(
|
||||
parse_element(" \t\n\r\n 8d7 \n"),
|
||||
Ok((" \n", Element::Dice(Dice::new(8, 7, KeepOrDrop::None))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_element(" \t\n\r\n 3d20k2 \n"),
|
||||
Ok((" \n", Element::Dice(Dice::new(3, 20, KeepOrDrop::Keep(2)))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_element(" \t\n\r\n 8 \n"),
|
||||
Ok((" \n", Element::Bonus(8)))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signed_element_test() {
|
||||
assert_eq!(
|
||||
parse_signed_element("+ 7"),
|
||||
Ok(("", SignedElement::Positive(Element::Bonus(7))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_signed_element(" \t\n\r\n- 8 \n"),
|
||||
Ok((" \n", SignedElement::Negative(Element::Bonus(8))))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_signed_element(" \t\n\r\n- 8d4 \n"),
|
||||
Ok((
|
||||
" \n",
|
||||
SignedElement::Negative(Element::Dice(Dice::new(8, 4, KeepOrDrop::None)))
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_signed_element(" \t\n\r\n- 8d4k4 \n"),
|
||||
Ok((
|
||||
" \n",
|
||||
SignedElement::Negative(Element::Dice(Dice::new(8, 4, KeepOrDrop::Keep(4))))
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_signed_element(" \t\n\r\n+ 8d4 \n"),
|
||||
Ok((
|
||||
" \n",
|
||||
SignedElement::Positive(Element::Dice(Dice::new(8, 4, KeepOrDrop::None)))
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn element_expression_test() {
|
||||
assert_eq!(
|
||||
parse_element_expression("8d4"),
|
||||
Ok((
|
||||
"",
|
||||
ElementExpression(vec![SignedElement::Positive(Element::Dice(Dice::new(
|
||||
8,
|
||||
4,
|
||||
KeepOrDrop::None
|
||||
)))])
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_element_expression("\t2d20k1 + 5"),
|
||||
Ok((
|
||||
"",
|
||||
ElementExpression(vec![
|
||||
SignedElement::Positive(Element::Dice(Dice::new(2, 20, KeepOrDrop::Keep(1)))),
|
||||
SignedElement::Positive(Element::Bonus(5)),
|
||||
])
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_element_expression(" - 8d4 \n "),
|
||||
Ok((
|
||||
" \n ",
|
||||
ElementExpression(vec![SignedElement::Negative(Element::Dice(Dice::new(
|
||||
8,
|
||||
4,
|
||||
KeepOrDrop::None
|
||||
)))])
|
||||
))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_element_expression("\t3d4k2 + 7 - 5 - 6d12dh3 + 1d1 + 53 1d5 "),
|
||||
Ok((
|
||||
" 1d5 ",
|
||||
ElementExpression(vec![
|
||||
SignedElement::Positive(Element::Dice(Dice::new(3, 4, KeepOrDrop::Keep(2)))),
|
||||
SignedElement::Positive(Element::Bonus(7)),
|
||||
SignedElement::Negative(Element::Bonus(5)),
|
||||
SignedElement::Negative(Element::Dice(Dice::new(6, 12, KeepOrDrop::Drop(3)))),
|
||||
SignedElement::Positive(Element::Dice(Dice::new(1, 1, KeepOrDrop::None))),
|
||||
SignedElement::Positive(Element::Bonus(53)),
|
||||
])
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
|
@ -4,6 +4,7 @@
|
|||
* project.
|
||||
*/
|
||||
use crate::basic::dice;
|
||||
use crate::basic::dice::KeepOrDrop;
|
||||
use rand::prelude::*;
|
||||
use std::fmt;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
|
@ -19,15 +20,27 @@ pub trait Rolled {
|
|||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub struct DiceRoll(pub Vec<u32>);
|
||||
/// array of rolls in order, how many dice to keep, and how many to drop
|
||||
/// keep indicates how many of the highest dice to keep
|
||||
/// drop indicates how many of the highest dice to drop
|
||||
pub struct DiceRoll (pub Vec<u32>, usize, usize);
|
||||
|
||||
impl DiceRoll {
|
||||
pub fn rolls(&self) -> &[u32] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn keep(&self) -> usize {
|
||||
self.1
|
||||
}
|
||||
|
||||
pub fn drop(&self) -> usize {
|
||||
self.2
|
||||
}
|
||||
|
||||
// only count kept dice in total
|
||||
pub fn total(&self) -> u32 {
|
||||
self.0.iter().sum()
|
||||
self.0[self.2..self.1].iter().sum()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -41,11 +54,21 @@ impl fmt::Display for DiceRoll {
|
|||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{}", self.rolled_value())?;
|
||||
let rolls = self.rolls();
|
||||
let mut iter = rolls.iter();
|
||||
let keep = self.keep();
|
||||
let drop = self.drop();
|
||||
let mut iter = rolls.iter().enumerate();
|
||||
if let Some(first) = iter.next() {
|
||||
write!(f, " ({}", first)?;
|
||||
if drop != 0 {
|
||||
write!(f, " ([{}]", first.1)?;
|
||||
} else {
|
||||
write!(f, " ({}", first.1)?;
|
||||
}
|
||||
for roll in iter {
|
||||
write!(f, " + {}", roll)?;
|
||||
if roll.0 >= keep || roll.0 < drop {
|
||||
write!(f, " + [{}]", roll.1)?;
|
||||
} else {
|
||||
write!(f, " + {}", roll.1)?;
|
||||
}
|
||||
}
|
||||
write!(f, ")")?;
|
||||
}
|
||||
|
@ -58,11 +81,17 @@ impl Roll for dice::Dice {
|
|||
|
||||
fn roll(&self) -> DiceRoll {
|
||||
let mut rng = rand::thread_rng();
|
||||
let rolls: Vec<_> = (0..self.count)
|
||||
let mut rolls: Vec<_> = (0..self.count)
|
||||
.map(|_| rng.gen_range(1..=self.sides))
|
||||
.collect();
|
||||
// sort rolls in descending order
|
||||
rolls.sort_by(|a, b| b.cmp(a));
|
||||
|
||||
DiceRoll(rolls)
|
||||
match self.keep_drop {
|
||||
KeepOrDrop::Keep(k) => DiceRoll(rolls,k as usize, 0),
|
||||
KeepOrDrop::Drop(dh) => DiceRoll(rolls,self.count as usize, dh as usize),
|
||||
KeepOrDrop::None => DiceRoll(rolls,self.count as usize, 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -198,18 +227,26 @@ mod tests {
|
|||
use super::*;
|
||||
#[test]
|
||||
fn dice_roll_display_test() {
|
||||
assert_eq!(DiceRoll(vec![1, 3, 4]).to_string(), "8 (1 + 3 + 4)");
|
||||
assert_eq!(DiceRoll(vec![]).to_string(), "0");
|
||||
assert_eq!(DiceRoll(vec![1, 3, 4], 3, 0).to_string(), "8 (1 + 3 + 4)");
|
||||
assert_eq!(DiceRoll(vec![], 0, 0).to_string(), "0");
|
||||
assert_eq!(
|
||||
DiceRoll(vec![4, 7, 2, 10]).to_string(),
|
||||
DiceRoll(vec![4, 7, 2, 10], 4, 0).to_string(),
|
||||
"23 (4 + 7 + 2 + 10)"
|
||||
);
|
||||
assert_eq!(
|
||||
DiceRoll(vec![20, 13, 11, 10], 3, 0).to_string(),
|
||||
"44 (20 + 13 + 11 + [10])"
|
||||
);
|
||||
assert_eq!(
|
||||
DiceRoll(vec![20, 13, 11, 10], 4, 1).to_string(),
|
||||
"34 ([20] + 13 + 11 + 10)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn element_roll_display_test() {
|
||||
assert_eq!(
|
||||
ElementRoll::Dice(DiceRoll(vec![1, 3, 4])).to_string(),
|
||||
ElementRoll::Dice(DiceRoll(vec![1, 3, 4], 3, 0)).to_string(),
|
||||
"8 (1 + 3 + 4)"
|
||||
);
|
||||
assert_eq!(ElementRoll::Bonus(7).to_string(), "7");
|
||||
|
@ -218,11 +255,11 @@ mod tests {
|
|||
#[test]
|
||||
fn signed_element_roll_display_test( |