[Tutor] Risk Dice Program

Alan Gauld alan.gauld at btinternet.com
Wed Jan 28 00:09:34 CET 2015


On 27/01/15 19:12, Dillon Cortez wrote:
> problem is that if any of the offensive dice is bigger
 > than only one of the defensive dice,
> the program shows the offense as the winner,

> def winner():
>      if o_die1 > d_die1 or d_die2:
>          print "The offense has won"

The problem is that the computer reads that differently to you.

It sees it as

      if (o_die1 > d_die1) or d_die2:

Now, due to how Python evaluates logical 'or' expressions,
it knows that if the first part is True it doesn't need to evaluate
the second part so, if d_die1 is less that o_die1 then it returns True 
and all is well.

But if d_die1 is greater that o_die1 it then returns the value
of the second expression in the 'or', namely d_die2. Which is not
what you want in this case.

To get round that you need to explicitly compare o_die1
to both values:

      if (o_die1 > d_die1) or (o_die1 > d_die2):

You don't strictly need the parens but I prefer to keep them there
to remind me of what's going on.

You could tidy up the code slightly by using a loop:

for die in [o_die1, o_die2,o_die3]:
    if die > d_die1 or d > d_die2:
       print 'offense won'
else:
    print 'defense won'

This is more extendible if you increase the number of die.

A further change caters for more defensive die too:

for od in [o_die1, o_die2, o_die3]:
    if any(od > dd for dd in [d_die1, d_die2]):
       print 'offense won'
else:
    print 'defense won'


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list