2.2 KiB
Dice Lab Assessment
Everything works as expected. Nice work!
Checkpoint 1
I love your decision to comment your code, and to write the generalized
function findn
. Within that function, your loop iterating over die
faces works fine, but checking whether nmuch[die]
is initialized
will become tiresome after a while. There's a nice idiom for this,
using defaultdict. A defaultdict is like a normal dict, but when you
first access a key, its value is initialized for you if it's not
already present.
from collections import defaultdict
def findn(self, nofakind):
nmuch = defaultdict(int)
for die in dice.faces():
nmuch[die] += 1
if nmuch[die] == nofakind:
return True
return False
Just a little cleaner :)
Checkpoint 2
Within your yachtzee_goals
, I'm guessing that you probably had a feeling
that copying the same method over into multiple classes wasn't the best way
to do it--this would be a perfect place to use a subclass or a mixin,
python's approach to inheritance and multiple inheritance respectively.
Comments
I think I was thinking of objects pretty literally as "things" one can do stuff to or with, e.g. dice that can be rolled. Goals don't immediately jump out as me in the same way...
I quite agree! This was actually one of my goals in this unit--to move from more concrete instantiations of classes (e.g. modeling dice) to less concrete (e.g. modeling Goals, or, in the game project, things like Strategies.
I imagine if I were to try doing this in unit 1 or 2, instead of treating the game as an object interacting with other objects (the dice and goals), it'd probably be some sort of loop with functions being called to mimic the methods and a declaration of a lot of global variables to keep track of things like score...
Yes, exactly! The beauty of encapsulating this kind of behavior within classes really starts to shine when your projects get bigger; if you have n components in a project, there are n^2 possible interactions if everything potentially interacts with everything. Debugging becomes impossible.
You have some really lovely reflections in these git comments :)