restructure into dice module

This commit is contained in:
Taylor C. Richberger 2020-04-20 11:19:50 -06:00
parent 9121497d17
commit a9e1ccbf2e
5 changed files with 89 additions and 28 deletions

1
Cargo.lock generated
View File

@ -26,6 +26,7 @@ name = "axfive-matrix-dicebot"
version = "0.1.0"
dependencies = [
"nom",
"rand",
"reqwest",
"serde",
"serde_json",

44
src/dice.rs Normal file
View File

@ -0,0 +1,44 @@
pub mod parser;
use std::ops::{Deref, DerefMut};
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct Dice {
pub(crate) count: u32,
pub(crate) sides: u32,
}
impl Dice {
fn new(count: u32, sides: u32) -> Dice {
Dice { count, sides }
}
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Element {
Dice(Dice),
Bonus(u32),
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum SignedElement {
Positive(Element),
Negative(Element),
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ElementExpression(Vec<SignedElement>);
impl Deref for ElementExpression {
type Target = Vec<SignedElement>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ElementExpression {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}

View File

@ -7,39 +7,14 @@ use nom::{
tag, IResult,
};
#[derive(Debug, PartialEq, Eq)]
struct Dice {
count: u32,
sides: u32,
}
use crate::dice::{Dice, Element, SignedElement, ElementExpression};
impl Dice {
fn new(count: u32, sides: u32) -> Dice {
Dice { count, sides }
}
}
#[derive(Debug, PartialEq, Eq)]
enum Element {
Dice(Dice),
Bonus(u32),
}
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum Sign {
Plus,
Minus,
}
#[derive(Debug, PartialEq, Eq)]
enum SignedElement {
Positive(Element),
Negative(Element),
}
#[derive(Debug, PartialEq, Eq)]
struct ElementExpression(Vec<SignedElement>);
fn is_whitespace(input: char) -> bool {
input == ' ' || input == '\n' || input == '\t' || input == '\r'
}
@ -205,3 +180,4 @@ mod tests {
);
}
}

View File

@ -1,3 +1,4 @@
pub mod bot;
pub mod dice;
pub mod matrix;
pub mod parser;
pub mod roll;

39
src/roll.rs Normal file
View File

@ -0,0 +1,39 @@
use rand::prelude::*;
use crate::dice;
pub trait Roll {
type Output;
fn roll(&self) -> Self::Output;
}
impl Roll for dice::Dice {
type Output = u32;
fn roll(&self) -> u32 {
let mut rng = rand::thread_rng();
(0..self.count).map(|_| rng.gen_range(1, self.sides + 1)).sum()
}
}
impl Roll for dice::Element {
type Output = u32;
fn roll(&self) -> u32 {
match self {
dice::Element::Dice(d) => d.roll(),
dice::Element::Bonus(b) => *b,
}
}
}
impl Roll for dice::SignedElement {
type Output = i32;
fn roll(&self) -> i32 {
match self {
dice::SignedElement::Positive(e) => e.roll() as i32,
dice::SignedElement::Negative(e) => -(e.roll() as i32),
}
}
}