Note that there are some explanatory texts on larger screens.

plurals
  1. POTime intervals between loops in python 3
    text
    copied!<p>This is a class I created to handle an "autoattack" in a project I am working on. It works well enough (it is close for 1 attack per second, not as fair with 2, and for some reason 3 and greater are pretty spot on) Is there a more efficient way to handle this?</p> <pre><code>import time import random ### your critical percentage critStat = 20 ### enemy block percentage eBlockchance = 12 ### your hit percentage hitStat = 90 ### Your attack speed is X/second. (ie. 2.4 would be 2.4 attacks per second) atkSpeed = 1 ### This works perfectly, probably a better way though. def atkInterval(atkSpeed): """Sets the attack interval to 1 second divided by the attack speed""" start = time.time() end = 0 while end &lt;= 1/atkSpeed : end = time.time()- start ### Change parameters to the real algorithm def atkDamage(strength, defense): """computes damage as strength - defense""" base = strength - defense damage = random.randint(base/2, base) ## Raised an arror when not divisible by 2 if hitChance(hitStat) == False: print("Miss!") return 0 else: if enemyBlock(eBlockchance) == True: print("Blocked!") return 0 else: if critChance(critStat) == True: print(int(damage*1.5), "Crit!") return int(damage * 1.5) else: return damage ### Critical Strike chance takes a whole number def critChance(critStat): """If your crit chance is higher than random 1-100 returns true or false""" chance = random.randint(1, 100) if chance &lt;= critStat: return True else: return False ### Block chance is the same as crit def enemyBlock(eBlockchance): """If enemy crit chance is higher than random 1-100 return true or false""" chance = random.randint(1,100) if chance &lt;= eBlockchance: return True else: return False ### Hit percentage def hitChance(hitStat): """if hit chance is higher than random 1-100 return true/false""" chance = random.randint(1,100) if chance &gt; hitStat: return False else: return True ### The main function sets enemy health to 1000 and loops damage until health &lt; 0. def main(): health = 1000 numAttacks = 0 start = time.time() while health &gt; 0: atkInterval(atkSpeed) health -= atkDamage(100,0) numAttacks+=1 print("Health remaining:", health) end = time.time() - start print("It took", numAttacks, "attacks and", end, "Seconds") main() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload