So, I have this battle scenario here:
def band_attack():
global new_ship
print('Bandits attack!')
s.sleep(1)
c = r.random()
if c < 0.5:
print('Bandits missed!')
elif 0.5 < c < 0.7:
c = r.random()
new_ship = new_ship - int(c)
print('Your ship was hit for', c, 'damage!')
print('Your ship now has', int(new_ship), 'health!')
else:
new_ship = new_ship - int(c)
print('Critical strike! You were hit for', c, 'damage!')
print('Your ship now has', int(new_ship), 'health!')
if new_ship <= 0:
print('You\'ve been destroyed!')
else:
Fight.band_fight()
Fight
is the class holding all the battle functions, r
is the random
module, s
is the time
module, band_attack
is a function where you attack.
I want the damage obviously to be whole numbers above 0
, hence why I turn the random function output to an integer.
It should be outputting a number greater than 0
, or if it is 0
, should just be a miss, but I'm clearly missing something. Maybe someone else can figure out what I'm missing?
CodePudding user response:
The call to random.random()
will always return a floating-point number in the range [0.0, 1.0)
as per the documentation.
When you cast the result to int
(by calling the int(c)
), you are asking for the integer part of that float
which is always equal to zero for floats in that range.
There are two ways to fix this: either multiply the result of random.random()
by 10
or use the random.randint(a, b)
, which returns a random integer N
, such that a <= N <= b
. You will need to adjust your conditions accordingly.
You mentioned in the comments that you are worried about seeding the random number generator when using random.randint(a, b)
but since the seed function affects the module's random number generator itself all functions (randint, choice, randrange) will behave as expected.
CodePudding user response:
The random()
function from the random module (which I assume is what you named r) returns a float between 0 and 1. You can't pass a float into int()
. The best alternative would be to use either randint(x, y)
(where x and y denote the range in which you want your random damage to be), or stick to random()
and mulitply it by the upper limit of that intended range.