Refactored code

This commit is contained in:
Beefki 2017-11-02 02:38:49 -05:00
parent 20af27423b
commit 1aae111af1
4 changed files with 44 additions and 25 deletions

View File

@ -1,27 +1,27 @@
extern crate libroller; extern crate libroller;
use libroller::config::Config; //use libroller::config::Config;
use libroller::roll::Roll;
use std::env; use std::env;
fn main() { fn main() {
let roll = Config::new(&mut env::args()); // let roll = Config::new(&mut env::args());
for rolls in &roll.unwrap_or_else(|e| {println!("Application error: {}", e); let rolls = Roll::from_args(&mut env::args()).unwrap_or_else(|err| {
std::process::exit(1)}) eprintln!("Error occured:{}", err);
{ std::process::exit(1)
let x = rolls.to_roll().unwrap_or_else(|e| { println!("Application error: {}", e);
std::process::exit(1);
}); });
if x.number() > 1 && x.number() < 26 { for roll in rolls {
if roll.number() > 1 && roll.number() < 26 {
let mut total = 0; let mut total = 0;
println!("You're rolling {}", x); println!("You're rolling {}", roll);
for value in x.rolls() { for value in roll.rolls() {
println!("You rolled: {}", value); println!("You rolled: {}", value);
total += value; total += value;
} }
println!("Total value of dice = {}", total); println!("Total value of dice = {}", total);
println!(""); println!("");
}else { }else {
println!("You're rolling {}", x); println!("You're rolling {}", roll);
println!("Total: {}", x.total()) println!("Total: {}", roll.total())
} }
} }
} }

View File

@ -52,8 +52,8 @@ impl Config {
/// Converts a `Config` into a `Roll`. Returns a `Result` that's /// Converts a `Config` into a `Roll`. Returns a `Result` that's
/// either `Ok(Roll)` or an `Err(_)` /// either `Ok(Roll)` or an `Err(_)`
pub fn to_roll(&self) -> Result<Roll, ParseIntError> { pub fn to_roll(&self) -> Result<Roll, ParseIntError> {
let number = self.first.parse::<u32>()?; let number = self.first.parse::<usize>()?;
let die = self.second.parse::<u32>()?; let die = self.second.parse::<usize>()?;
Ok(Roll::new(number, die)) Ok(Roll::new(number, die))
} }

View File

@ -2,6 +2,9 @@
pub extern crate rand; pub extern crate rand;
pub mod roll; pub mod roll;
pub mod config; pub mod config;
//pub mod error;
pub use roll::*; pub use roll::*;
pub use roll::Roll; pub use roll::Roll;
pub use std::{num, io};
//pub use error::RollError;

View File

@ -1,19 +1,21 @@
//! A struct in which our data is held for rolling. By ensuring that //! A struct in which our data is held for rolling. By ensuring that
//! only `u32`s are used we prevent the need for additional type //! only `usize`s are used we prevent the need for additional type
//! checking at time of use. */ //! checking at time of use. */
extern crate rand; extern crate rand;
use rand::Rng; use rand::Rng;
use std::fmt; use std::fmt;
use std::num::ParseIntError;
use super::std;
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
pub struct Roll { pub struct Roll {
die: u32, die: usize,
number: u32, number: usize,
} }
impl Roll { impl Roll {
/// A fn to create new `Roll` structs, private to prevent /// A fn to create new `Roll` structs, private to prevent
/// being used outside the library. /// being used outside the library.
pub fn new(number: u32, die: u32) -> Roll { pub fn new(number: usize, die: usize) -> Roll {
Roll { Roll {
die: die, die: die,
number: number, number: number,
@ -27,37 +29,51 @@ impl Roll {
/// let x = Roll::new(&2, &6); /// let x = Roll::new(&2, &6);
/// assert!(x.number() == 2); /// assert!(x.number() == 2);
/// ``` /// ```
pub fn number(&self) -> u32 { pub fn number(&self) -> usize {
self.number self.number
} }
/// Returns the value stored in the die field of a roll. /// Returns the value stored in the die field of a roll.
/// Allows the fields of `Roll` to be private (and unchangable) /// Allows the fields of `Roll` to be private (and unchangable)
/// while still allowing access to act on their internal value /// while still allowing access to act on their internal value
pub fn die(&self) -> u32 { pub fn die(&self) -> usize {
self.die self.die
} }
/// Creates a Vector to hold each of the values rolled. Making /// Creates a Vector to hold each of the values rolled. Making
///a Vector ensures the ability to work on exactly the same ///a Vector ensures the ability to work on exactly the same
///die rolls easily and accurately, since calling the `Roll` ///die rolls easily and accurately, since calling the `Roll`
///iterator again will produce new results. ///iterator again will produce new results.
pub fn rolls(self) -> Vec<u32> { pub fn rolls(self) -> Vec<usize> {
self.collect() self.collect()
} }
/// Used on a `Roll` to return only the final value, ignoring /// Used on a `Roll` to return only the final value, ignoring
///the values used to add up to that result. Allows `.total()` ///the values used to add up to that result. Allows `.total()`
///syntax when used ///syntax when used
pub fn total(self) -> u32 { pub fn total(self) -> usize {
self.sum() self.sum()
} }
pub fn from_args(args: &mut std::env::Args) -> Result<Vec<Roll>, ParseIntError> {
args.next();
let mut total: Vec<Roll> = vec![];
while args.len() >= 2 {
let roll: Vec<String> = args.take(2).collect();
total.push(Roll::new(
roll[0].parse::<usize>()?,
roll[1].parse::<usize>()?,
)
);
}
Ok(total)
}
} }
/// Turns `Roll` into an `Iterator`, causing it to create a series of random /// Turns `Roll` into an `Iterator`, causing it to create a series of random
///numbers between 1 and the chosen die size. It counts down the number field ///numbers between 1 and the chosen die size. It counts down the number field
///of the `Roll` and returns `None` to end the iteration. It's only capable of ///of the `Roll` and returns `None` to end the iteration. It's only capable of
///returning u32 values, which should never be a problem. ///returning usize values, which should never be a problem.
impl Iterator for Roll { impl Iterator for Roll {
type Item = u32; type Item = usize;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.number != 0 { if self.number != 0 {