Reputation: 41
Beginner python user here. I'm writing some code for a basic attack in an rpg, and it looks like this:
import random
class attack:
health = 300
for i in range(1):
if (random.uniform(0, 10)) <= int(8.2):
health = health - 50
print("Your attack hit.\n" + "The monster's health is at " + str(health))
else:
print("Your attack missed.\n" + "The monster's health is at " + str(health))
When the attack hits, this is what's printed:
Your attack hit.
The monster's health is at 250
I'm trying to continuously subtract from the heath until it goes down to zero. How do I write this so that 50 continuously subtracts from 300 whenever I run the program (instead of just staying at 250)?
Upvotes: 0
Views: 2072
Reputation:
It is better if you use a function, instead of a class, and you can use a while loop to keep on attacking into health is smaller then 0.
import random
def attack():
health = 300
while health > 0:
if (random.uniform(0, 10)) <= int(8.2):
health -= 50
print("Your attack hit.\n" + "The monster's health is at " + str(health))
else:
print("Your attack missed.\n" + "The monster's health is at " + str(health))
attack()
Upvotes: 0
Reputation: 15956
Your loop is only executing once.
for i in range(1):
If you want it to run until health
is 0
, you'll need a while
loop:
while health > 0:
Upvotes: 2
Reputation: 678
You can use a while
loop- it'll run until the condition's met (in this case, until health is 0):
while health > 0:
if (random.uniform(0, 10)) <= int(8.2):
health = health - 50
print("Your attack hit.\n" + "The monster's health is at " + str(health))
else:
print("Your attack missed.\n" + "The monster's health is at " + str(health))
Upvotes: 3
Reputation: 9059
Use a while loop like
while health > 0:
if (random.uniform(0, 10)) <= int(8.2):
health = health - 50
print("Your attack hit.\n" + "The monster's health is at " + str(health))
else:
print("Your attack missed.\n" + "The monster's health is at " + str(health))
https://docs.python.org/3/reference/compound_stmts.html#the-while-statement
Upvotes: 2