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 Yatzy Scoring

nakalkucing
nakalkucing
12,964 Points

Yatzy Scoring trouble. No matter what I roll I get back zero points. Help please!

I've rewatched the video multiple times and can't figure out my mistake. Here's a link to the video. Here's a Fork of my workspace. Thanks in advance. :)

Here's the code:

# File: dice.py
import random


class Die:
    def __init__(self, sides=2, value=0):
        if not sides >= 2:
            raise ValueError("Must have at least 2 sides")
        if not isinstance(sides, int):
            raise ValueError("Sides must be a whole number")
        self.value = value or random.randint(1, sides)

    def __int__(self):
        return self.value

    def __eq__(self, other):
        return int(self) == other

    def __ne__(self, other):
        return int(self) != other# Or:   return not int (self) == other

    def __gt__(self, other):
        return int(self) > other

    def __lt__(self, other):
        return int(self) < other

    def __ge__(self, other):
        return int(self) > other or int(self) == other#Or:    return int(self) >= other

    def __le__(self, other):
        return int(self) < other or int(self) == other#Or:    return int(self) <= other

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

    def __radd__(self, other):
        return int(self) + other# Or:   return self + other

    def __repr__(self):
        return str(self.value)


class D6(Die):
    def __init__(self, value=0):
        super().__init__(sides=6, value=value)
# File: scoresheets.py
class YatzyScoresheet:
    def score_ones(self, hand):
        return sum(hand.ones)

    def score_twos(self, hand):
        return sum(hand.twos)

    def score_threes(self, hand):
        return sum(hand.threes)

    def score_fours(self, hand):
        return sum(hand.fours)

    def score_fives(self, hand):
        return sum(hand.fives)

    def score_sixes(self, hand):
        return sum(hand.sixes)

    def _score_set(self, hand, set_size):
        scores = [0]
        for worth, count in hand._sets.items():
            if count == set_size:
                scores.append(worth*set_size)
            return max(scores)

    def score_one_pair(self, hand):
        return self._score_set(hand, 2)
# File: hands.py
from dice import D6


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

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

    def _by_value(self, value):
        dice = []
        for die in self:
            if die == value:
                dice.append(die)
        return dice


class YatzyHand(Hand):
    def __init__(self, *args, **kwargs):
        super().__init__(size=5, die_class=D6, *args, **kwargs)

    @property
    def ones(self):
        return self._by_value(1)

    @property
    def twos(self):
        return self._by_value(2)

    @property
    def threes(self):
        return self._by_value(3)

    @property
    def fours(self):
        return self._by_value(4)

    @property
    def fives(self):
        return self._by_value(5)

    @property
    def sixes(self):
        return self._by_value(6)

    @property
    def _sets(self):
        return {
            1: len(self.ones),
            2: len(self.twos),
            3: len(self.threes),
            4: len(self.fours),
            5: len(self.fives),
            6: len(self.sixes)
        }

These were all in the same folder.

Ray Karyshyn
Ray Karyshyn
13,443 Points

Hi nakalkucing,

Your fork link does not work.

nakalkucing
nakalkucing
12,964 Points

Hi Ray Karyshyn ,

I tried retyping the link and it seems to work now. Would you mind trying it again for me? :)

Thanks,

Nakal

Michael Hulet
Michael Hulet
47,912 Points

Hey! I was about to take a look at this, but the workspace fork link 404s again. Perhaps you could just copy/paste your code here?

nakalkucing
nakalkucing
12,964 Points

Ok. I'll have it up in a moment. :)

nakalkucing
nakalkucing
12,964 Points

Sorry. The link only works sometimes. I got it to work for a minute. But it seems to have stopped again. :(

2 Answers

Michael Hulet
Michael Hulet
47,912 Points

In general, your code looks great. You've just made a simple indentation error, which is fairly easy to do and can be frustrating to debug, so I feel your pain on this one. The problem is in your _score_set method of your YatzyScoresheet class. Here's what you have now:

def _score_set(self, hand, set_size):
        scores = [0]
        for worth, count in hand._sets.items():
            if count == set_size:
                scores.append(worth*set_size)
            return max(scores)

Let's walk through this. You have scores initialized to be a list with just a 0 in it, and you iterate over the items in hand. On the first iteration, count is not equal to set_size, so nothing is appended to scores, but then your loop stops without continuing onto the next iteration. This happens because it hits a return statement, which immediately stops execution of your method and gives back a value. In this case, you're giving back the largest value in scores, and since the only value in scores right now is 0, you get back 0 every time.

Instead, you want your method to return after all iterations of the loop has run and the scores array is properly built up. To do this, you just need to move your return statement onto the same indentation level as your for loop, instead of indented to be inside it, like this:

def _score_set(self, hand, set_size):
        scores = [0]
        for worth, count in hand._sets.items():
            if count == set_size:
                scores.append(worth*set_size)
        return max(scores)

After just deleting 4 spaces before your return statement, your code works just fine. Great job!

nakalkucing
nakalkucing
12,964 Points

Thanks so much Michael Hulet! It works great! :)

Ryan McGuire
Ryan McGuire
3,758 Points

My indentation was off in Hands.py line 19 and was getting the same problem. Took a while to find!