[Tutor] Silly Dice Game
John Fouhy
john at fouhy.net
Sat Apr 29 14:40:25 CEST 2006
On 30/04/06, John Connors <oztriking at hotmail.com> wrote:
> The wife and I play a silly dice game and I thought it would be a good
> challange for me to write it as a program. No specific question, just
> wondering if my technique is ok and is there anything that could be done
> better. The 2 hardest things I find as a python beginner who has no real
> need to learn a programming language other than curiosity and too much spare
> time, are thinking of something to program and then knowing if what I have
> written could be done more efficiently.
Hi John,
If I were you, I would look at separating more of my program out into
functions. Good use of functions will make your program more
readable, easier to debug, and easier to change, should the rules of
your dice game change :-)
So, your basic game structure is (correct me if I'm wrong):
while True:
roll some dice
check if we've won anything
The "check if we've won anything" section seems like an excellent
place to start writing functions.
For example, you have:
#check if all dice are the same
for fatChance in range(1,7):
if dieList.count(fatChance) == 6:
score += 5000
dieLeft = 0
print "\nYou rolled all %d's, WoW!!!" % (fatChance)
#check for a straight
if dieList == [1,2,3,4,5,6]:
score += 1500
dieLeft = 0
print "\nYou rolled a straight"
#check for 3 pairs
if dieLeft == 6:
if dieList[0] == dieList[1] and dieList[2] == dieList[3] and
dieList[4] == dieList[5]:
score += 1500
dieLeft = 0
print"\nYou rolled three pairs"
We could change this as follows:
def checkSame(dieList):
""" Check if all the dice are the same. """
return len(set(dieList)) == 1
def checkStraight(dieList):
""" Check if the die list is a straight. """
return set(dieList) == set(range(1, 7))
def checkThreePairs(dieList):
""" Check if the die list comprises three pairs. """
dieList = sorted(dieList)
return dieList[0] == dieList[1] and dieList[2] == dieList[3] and
dieList[4] == dieList[5]
These functions would go at the top of your code somewhere. Then, we
can change your if statement to something like this:
if checkSame(dieList):
score += 5000
dieLeft = 0
print "\nYou rolled all %d's, WoW!!!" % dieList[0]
elif checkStraight(dieList):
score += 1500
dieLeft = 0
print 'You rolled a straight.'
elif checkThreePairs(dieList):
score += 1500
dieLeft = 0
print 'You rolled three pairs.'
Now, we could go even furthere here, by observing that a lot of this
is still the same. So, maybe we could build a little data structure:
tests = [(checkSame, 5000, 'You rolled all the same!'),
(checkStraight, 1500, 'You rolled a straight.'),
(checkThreePairs, 1500, 'You rolled three pairs.')]
for test, points, message in tests:
if test(dieList):
score += points
dieLeft = 0
print message
break
Do you understand what is going on there?
--
John.
More information about the Tutor
mailing list