Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Dice Roller RPG Roller

please help

I have no idea why this is not working. Can someone tell me whats wrong with my code?

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
import D20 from dice.py

class Hand(list):

    def __init__(self, die_class = None , size = 0, *args, **kwargs):
        if not die_class:
            raise ValueError("You must provide a die class.")
        super().__init__()
        for _ in range(size):
            self.append(die_class())


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

    @classmethod
    def roll(cls,size):
        return cls(die_class = D20, size)

2 Answers

This code:

    for _ in range(size):
        self.append(die_class())

needs to be in your roll method and part of your return. You'll need to add the self.value and self. sides back to the main class method. Then take out the super().init, as its not needed. For the roll method you basically need an empty list, your for loop, and the return of that list. Since its a class method, you don't use self, you use cls. Mine looked like below:

@classmethod     
def roll(cls, number_of_dice, die_type = D20):
    hand = []
    for d in range(number_of_dice):
        hand.append(die_type)
    return cls(hand)

Awesome, thank you for the help!