com.riversoforion.zambezi.dice.Dice.java Source code

Java tutorial

Introduction

Here is the source code for com.riversoforion.zambezi.dice.Dice.java

Source

/*
 * Copyright (c) 2011, Eric McIntyre
 * All rights reserved.
 *
 * This software is under the BSD license.
 * http://www.opensource.org/licenses/bsd-license.php
 */
package com.riversoforion.zambezi.dice;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;

import org.apache.commons.lang3.builder.CompareToBuilder;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;

/**
 * @author macdaddy
 */
public class Dice implements Iterable<Die>, Comparable<Dice> {

    private Collection<Die> dice = new ArrayList<Die>();

    public Dice(int count, int sides) {

        for (int i = 0; i < count; i++) {
            dice.add(new Die(sides));
        }
    }

    public Dice(Die... dice) {

        this.dice.addAll(Arrays.asList(dice));
    }

    public Dice(Collection<Die> dice) {

        this.dice.addAll(dice);
    }

    public Iterable<Die> roll() {

        for (Die die : this) {
            die.roll();
        }
        return this;
    }

    public Dice sort() {

        return new SortedDice(this);
    }

    @Override
    public Iterator<Die> iterator() {

        return dice.iterator();
    }

    @Override
    public boolean equals(Object obj) {

        if (obj == null || !(obj instanceof Dice))
            return false;
        if (obj == this)
            return true;
        Dice other = (Dice) obj;
        return new EqualsBuilder().append(this.dice, other.dice).isEquals();
    }

    @Override
    public int hashCode() {

        return new HashCodeBuilder().append(this.dice).toHashCode();
    }

    @Override
    public int compareTo(Dice other) {

        if (other == null)
            return 1;
        return new CompareToBuilder().append(this.dice, other.dice).toComparison();
    }

    @Override
    public String toString() {

        return new ToStringBuilder(this).append(this.dice).toString();
    }

    private class SortedDice extends Dice {

        private Dice delegate;

        private SortedDice(Dice delegate) {

            this.delegate = delegate;
        }

        @Override
        public Iterator<Die> iterator() {

            SortedSet<Die> dice = new TreeSet<Die>(delegate.dice);
            return dice.iterator();
        }
    }
}