Two questions about style and some simple math

MRAB google at mrabarnett.plus.com
Mon Jan 19 20:54:01 EST 2009


Spoofy wrote:
> Hello everybody!
> 
> Though I'm a hobby programmer for years now (mainly small hackery 
> things) I still have big problems getting "real" things to work.
> 
> I'm currently trying to write a simple RPG and have problems with the 
> following:
> 
> 1.
> 
> Characters have a "courage" attribute that basically determins who has 
> the first attack in a fight. After some trying, I came up with this 
> (sorry, not really working code, but what I made from interactive 
> experimentation):
> 
> def first_attack(player1,  player2):
>     diff = player1.attributes.courage - player2.attributes.courage
>     players = (player,  player2)
>     return players[diff + random.randint(-diff,  diff) < 0]
> 
> To make it more realistic, I randomized it a little bit and this seems 
> to work for low courage values. But when the courage values are high 
> (100 and such) it fails (the chance to have the first attack drops the 
> higher the values are). My math is really bad and I have problems to 
> understand what's happenning here. I suspect the greater range for 
> randint() is the problem, but I don't really get why.
> 
> Any tips would be greatly appreciated.
> 
[snip]

Try:

def first_attack(player1,  player2):
     total_courage = player1.attributes.courage + player2.attributes.courage
     players = (player,  player2)
     return players[random.randrange(0, total_courage) < 
player1.attributes.courage]




More information about the Python-list mailing list