Yahtzee in Python: Counting Individual Numbers

Now that I’ve got the “special” hands done, the other part I will need to support is the ability to score the “top of the card.” This means that I will need to be able to count (and score) ones, twos, threes, fours, fives, and sixes. The get_counts() and count_of() methods that we build in the previous post to help us with finding full houses will come in handy here. As a reminder, the methods in question look like this:

    def get_counts(self) -> tuple:
        Get the count of each number appearing in the hand.
        e.g. - a hand of [3, 3, 4, 4, 1] will return (1, 0, 2, 2, 0, 0)
        :return: A tuple of integers with the value at each index indicating the number of occurences of number n-1 in
        the hand.
        retval = tuple(self.hand.count(i) for i in range(1, self.num_sides+1))
        return retval

    def count_of(self, num: int) -> int:
        return self.hand.count(num)

Using these two methods, I’ve got two ways to figure out the scores for the individual numbers. Simply, the score for an individual number is:

    def get_score_for_number(self, number):
        return self.count_of(number) * number

Hopefully it’s becoming apparent that taking the time to build some of the methods in the SimpleHand class is starting to pay off! The next step for me is to write one more helper method, update my unit tests and then put all of this together and use it to build a scorecard. Once I’m there, I’ll be able to simulate a full game!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top