Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Dice Roller RPG Roller

Heidi Ulrich
Heidi Ulrich
4,624 Points

This dice game doesn't work

I've gone through all the steps and to me it all works.

If I make a myturn = Hand.roll(2) it returns me a list of two D20 instances, both rolled a random number.

If I go lucky=Hand(myturn).total on that, lucky contains the total of those two dice values. What's wrong with that?

dice.py
import random


class Die:
    def __init__(self, sides=2):
        if sides < 2:
            raise ValueError("Can't have fewer than two sides")
        self.sides = sides
        self.value = random.randint(1, sides)

    def __int__(self):
        return self.value

    def __add__(self, other):
        return int(self) + other

    def __radd__(self, other):
        return self + other

class D20(Die):
    def __init__(self):
        super().__init__(sides=20)
hands.py
class Hand(list):     

    @property
    def total(self):
        return sum(self)

    def roll(number):
        outcome = []
        for i in range(number):
            outcome.append(D20())
        return outcome

Hi Heidi, I went back and looked at the code I submitted to pass this challenge. In my hands.py, I do several other things I don't see in your code. first I used init () method like we did in other exercises so that I would have a way to create a new instance of hand for each set of die rolls. Because I will need to roll the dice I used from dice import Die and from dice import D20. Finally I reviewed the section on @classmethod. It is needed so that you can call the method .roll() against the class. Hope that helps.

1 Answer

Heidi Ulrich
Heidi Ulrich
4,624 Points

Thank you Frank, for your answer! Unfortunately it is a comment, I cannot rate it... I invite you to post it again as answer because I think it will work. Thanks for not giving away the prize but pointing me to the things I'm currently missing.

Yes, a few things - like the init() and the import, I think I had them, but squashed them out at some point... I bet to avoid erroneous clutter that could block the code from passing.