Thread: Designing Data Structures for Dice Rolling

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    An idea, for good or ill:
    Code:
    class Die {
        public:
            int Roll();
            Die(std::vector<int> possible_sides);
        private:
            int number_of_sides;
            std::vector<int> sides;
    };
    
    Die::Die(std::vector<int> possible_sides) :
        number_of_sides(possible_sides.size()), sides(possible_sides.begin(), possible_sides.end())
    {
    }
    
    int Die::Roll() {
        return sides[rand()%number_of_sides];
    }
    In other words, each die knows what the markings on its sides are and returns whichever one is rolled. Using a vector is a little awkward (ok, a lot awkward, unless there's a nice easy way to build a vector with values {-1,0,0,0,1,1} that I've missed to pass into the constructor), but I wasn't sure if you were always using d6. If so, then just make it an array of six, pass in an array of 6 and be done with it.

    EDIT: Holy cow, I'm sorry, I thought I was in the C++ board. Alright. Ignore the vector part, and the class part, and just everything. I still think that each die should know its markings and return. For penance, a C version:
    Code:
    struct Die {
        int number_of_sides;
        int *sides;
    };
    
    int createDie(int n, int *sidelist, struct Die *newdie) {
        newdie->number_of_sides = n;
        newdie->sides = malloc(n*sizeof(int));
        if (newdie->sides == NULL) {
            return 1; /*bad things*/
        }
        for (int i = 0; i < n; i++) {
            newdie->sides[i] = sidelist[i];
        }
        return 0;
    }
    
    int RollDie(struct Die die) {
        return die.sides[rand()%die.number_of_sides];
    }
    Last edited by tabstop; 02-26-2009 at 11:50 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. i need advice about data structures
    By sawer in forum C Programming
    Replies: 2
    Last Post: 04-22-2006, 03:40 AM
  2. Need some help regarding data structures
    By Afrinux in forum C Programming
    Replies: 15
    Last Post: 01-28-2006, 05:19 AM
  3. array of structures, data from file
    By nomi in forum C Programming
    Replies: 5
    Last Post: 01-11-2004, 01:42 PM
  4. C diamonds and perls :°)
    By Carlos in forum A Brief History of Cprogramming.com
    Replies: 7
    Last Post: 05-16-2003, 10:19 PM
  5. need help with data structures
    By straightedgekid in forum C++ Programming
    Replies: 0
    Last Post: 10-05-2001, 02:17 PM

Tags for this Thread