1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//##################################################################################################
//******************************************* DEPENDENCIES  ****************************************
//##################################################################################################


use dice::Die;
use std::cmp::Eq;
use std::ops::Add;
use std::hash::Hash;
use std::collections::HashMap;
use std::slice::{IterMut,Iter};
use std::fmt::{Display,Formatter,Result};


//##################################################################################################
//**************************************** STRUCT DECLARATIONS *************************************
//##################################################################################################


//==================================================================================================
/// A collection of dice.
//==================================================================================================

pub struct DiceCollection<T: Die> {

    /// Internal collection of dice
    dice: Vec<T>,                       
}


//##################################################################################################
//************************************* STRUCT IMPLEMENTATIONS *************************************
//##################################################################################################


//==================================================================================================
impl<T: Die> DiceCollection<T> {
//==================================================================================================

    //==============================================================================================
    /// Pseudo-constructor for DiceCollection.
    //----------------------------------------------------------------------------------------------
    /// ##### Return Value
    /// An empty DiceCollection
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    ///
    /// // Create a new dice collection and add a standard 6-sided die to it
    /// let mut dice = DiceCollection::<NumericDie>::new();
    /// dice.add(NumericDie::new(1, 1, 6, None));
    ///
    /// assert_eq!(dice.size(), 1);
    /// # }
    /// ```
    //==============================================================================================
    
    pub fn new() -> Self {
        DiceCollection { dice: Vec::new() }
    }


    //==============================================================================================
    /// Add a die to the collection.
    ///
    //----------------------------------------------------------------------------------------------
    /// ##### Parameters
    ///
    /// die : die to add to collection
    ///
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    ///
    /// A mutable reference to the collection
    ///
    //----------------------------------------------------------------------------------------------
    /// # Examples
    ///
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    ///
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie());
    /// dice.add(mkdie());
    /// dice.add(mkdie());
    ///
    /// assert_eq!(dice.size(), 3);
    /// # }
    /// ```
    ///
    //----------------------------------------------------------------------------------------------
    /// This operation may also be chained:
    ///
    /// ```
    /// # extern crate ezra;
    /// # use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie())
    ///     .add(mkdie())
    ///     .add(mkdie());
    ///
    /// assert_eq!(dice.size(), 3);
    /// # }
    /// ```
    //==============================================================================================

    pub fn add(&mut self, die: T) -> &mut Self {
        self.dice.push(die);
        self
    }

    
    //==============================================================================================
    /// Remove all dice from the collection.
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    /// A mutable reference to the DiceCollection
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    ///
    /// let mut dice = DiceCollection::<NumericDie>::new();
    /// dice.add(NumericDie::new(1, 1, 6, None));
    ///
    /// assert_eq!(dice.size(), 1);
    ///
    /// dice.clear();
    /// assert!(dice.is_empty());
    /// # }
    /// ```
    //----------------------------------------------------------------------------------------------
    /// This operation may also be chained:
    ///
    /// ```
    /// # extern crate ezra;
    /// # use ezra::dice::{DiceCollection,NumericDie};
    /// # fn main() {
    /// let mut dice = DiceCollection::<NumericDie>::new();
    /// dice.add(NumericDie::new(1, 1, 6, None));
    ///
    /// assert!(dice.clear().is_empty());
    /// # }
    /// ```
    //==============================================================================================

    pub fn clear(&mut self) ->  &mut Self {
        self.dice.clear();
        self
    }


    //==============================================================================================
    /// Roll all dice in the collection.
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    /// A mutable reference to the DiceCollection
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    /// 
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie())
    ///     .add(mkdie())
    ///     .add(mkdie())
    ///     .roll_all();
    ///
    /// println!("After 1 roll, the sum of the dice is {}", dice.total());
    /// # }
    /// ```
    //----------------------------------------------------------------------------------------------
    /// This operation may also be chained:
    ///
    /// ```
    /// # extern crate ezra;
    /// # use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie()).roll_all().roll_all().roll_all();
    /// 
    /// println!("After 3 roll, the sum of the dice is {}", dice.total());
    /// # }
    /// ```
    //==============================================================================================

    pub fn roll_all(&mut self) -> &mut Self {
        for die in self.dice.iter_mut() {
            die.roll();
        }
        self
    }


    //==============================================================================================
    /// Determine if the collection contains dice.
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    /// - true : no dice are in the collection
    /// - false : the collection contains one or more dice
    //----------------------------------------------------------------------------------------------
    ///
    /// # Examples
    ///
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    ///
    /// let mut dice = DiceCollection::new();
    /// assert!(dice.is_empty());
    ///
    /// dice.add(NumericDie::new(1, 1, 6, None));
    /// assert!(!dice.is_empty());
    /// # }
    /// ```
    //==============================================================================================

    pub fn is_empty(&self) -> bool {
        self.dice.is_empty()
    }


    //==============================================================================================
    /// Obtain the number of dice in the collection.
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    /// The number of dice in the collection
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{DiceCollection,NumericDie};
    /// # fn main() {
    ///
    /// let mut dice = DiceCollection::new();
    /// assert_eq!(dice.size(), 0);
    ///
    /// dice.add(NumericDie::new(1, 1, 6, None));
    /// assert_eq!(dice.size(), 1);
    /// # }
    /// ```
    //==============================================================================================

    pub fn size(&self) -> usize {
        self.dice.len()
    }


    //==============================================================================================
    /// Obtain an immutable iterator across all dice in the collection
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    ///
    /// An immutable iterator across all dice in the collection
    //----------------------------------------------------------------------------------------------
    /// # Exampes
    ///
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{Die,DiceCollection, NumericDie};
    /// # fn main() {
    ///
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie())
    ///     .add(mkdie())
    ///     .add(mkdie());
    ///
    /// for (i,die) in dice.iter().enumerate() {
    ///     println!("Die {} has value {}.", i, die.get_value());
    /// }
    /// # }
    /// ```
    //==============================================================================================

    pub fn iter(&self) -> Iter<T> {
        self.dice.iter()
    }

    
    //==============================================================================================
    /// Obtain a mutable iterator across all dice in the collection.
    //----------------------------------------------------------------------------------------------
    /// ##### Return Value
    /// A mutable iterator across all dice in the collection.
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{Die,DiceCollection,NumericDie};
    /// # fn main() {
    ///
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie())
    ///     .add(mkdie())
    ///     .add(mkdie());
    ///
    /// for die in dice.iter_mut() {
    ///     die.roll();
    /// }
    ///
    /// println!("After rolling each die once, their total is {}", dice.total());
    /// # }
    /// ```
    //==============================================================================================

    pub fn iter_mut(&mut self) -> IterMut<T> {
        self.dice.iter_mut()
    }
}


//==================================================================================================
impl<V: Add<V,Output=V>, T: Die<ValueType=V>> DiceCollection<T> {
//==================================================================================================


    //==============================================================================================
    /// Calculate the sum of all dice values.
    ///
    /// In order to use this method, the associated ValueType of the dice in the collection must
    /// implement the Add trait.
    //----------------------------------------------------------------------------------------------
    /// ##### Return value
    /// The sum of all dice values
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{NumericDie,DiceCollection};
    /// # fn main() {
    /// 
    /// let mkdie = || { NumericDie::new(1, 1, 6, None) };
    /// let mut dice = DiceCollection::<NumericDie>::new();
    ///
    /// dice.add(mkdie())
    ///     .add(mkdie())
    ///     .add(mkdie())
    ///     .roll_all();
    ///
    /// println!("After 1 roll, the sum of the dice is {}", dice.total());
    /// # }
    /// ```
    //==============================================================================================

    pub fn total(&self) -> V {
        let mut total = self.dice[0].get_value();
        for die in self.dice.iter().skip(1) {
            total = total + die.get_value();
        }
        total
    }
}


//==================================================================================================
impl<V: Eq + Hash, T: Die<ValueType=V>> DiceCollection<T> {
//==================================================================================================

    
    //==============================================================================================
    /// Produce a summary of the state of all dice in the collection.
    ///
    /// The summary is a table of value types and their occurence count within the dice values in
    /// the DiceCollection. In order to use this function, the associated ValueType of the dice in
    /// the collection must implement the Eq and Hash traits.
    //----------------------------------------------------------------------------------------------
    /// ##### Return Value
    /// A HashMap with keys for each possible die value, with values corresponding to the number of
    /// occurrences of that key in the multiset of die values in the collection.
    //----------------------------------------------------------------------------------------------
    /// # Examples
    /// ```
    /// # extern crate ezra;
    /// use ezra::dice::{ValueDie,DiceCollection};
    /// # fn main() {
    ///
    /// // Values a die may have
    /// #[derive(Copy,Clone,Debug,Hash,Eq,PartialEq)]
    /// enum DiceValues {
    ///     Value1,
    ///     Value2,
    ///     Value3,
    /// }
    ///
    /// let values = vec![DiceValues::Value1, DiceValues::Value2, DiceValues::Value3];
    /// let mkdie = || { ValueDie::new(values, None) };
    /// let mut dice = DiceCollection::<ValueDie<DiceValues>>::new();
    /// dice.roll_all();
    ///
    /// let summary = dice.summary();
    /// for key in summary.keys() {
    ///     println!("Value {:?} occured {} time(s)", key, summary.get(key).unwrap()); 
    /// }
    /// # }
    /// ```
    //==============================================================================================
    pub fn summary(&self) -> HashMap<T::ValueType, usize> {
        use std::collections::HashMap;
        let mut result = HashMap::new();
        for die in self.dice.iter() {
            for value in die.values() {
                result.insert(value, 0);
            }
        }
        for die in self.dice.iter() {
            let oldval = *result.get(&die.get_value()).unwrap();
            result.insert(die.get_value(),  oldval + 1);
        }
        result
    }
}


//==================================================================================================
impl<T: Die + Display> Display for DiceCollection<T> {
//==================================================================================================


    //==============================================================================================
    fn fmt(&self, f: &mut Formatter) -> Result {
    //----------------------------------------------------------------------------------------------
    // Print the DiceCollection using the given formatter.
    //----------------------------------------------------------------------------------------------
    // TAKES:   f -> formatter with which to print the DiceCollection
    //
    // RETURNS: Ok(())   -> printed DiceCollection without error
    //          Err(...) -> something went wrong while attempting to print the DiceCollection
    //==============================================================================================

        let mut result = "{".to_string() + &format!("{}", self.dice[0]) ;
        for die in self.dice.iter().skip(1) {
            result = result + &format!(", {}", die);
        }
        write!(f, "{}", result)
    }
}