python - Variable assignment in function -
i'm writing basic fighting game , trying make each attack subtracts amount of attack enemy's health , prints enemy's current health. however, health resets original amount after run script once , loop it. how can resign enemies health current health?
here script:
import random  while true:     health = 20     enemy_health = 20      def punch():         mylist = (xrange(0,3))         x = random.choice(mylist)         if x == 3:             print"your hit effective enemy lost 3 hp"             print("enemy health is" enemy_health - x)         if x == 2:             print "your punch effective enemy lost 2 hp"             print("enemy health is" enemy_health - x)         if x == 1:             print "enemy lost 1 point"             print("enemy health is" enemy_health - x)      def kick():         mylist = (xrange(0,5))         x = random.choice(mylist)         if x > 3:             "%d" % x             print"your kick effective enemy lost %d hp"             print("enemy health is", enemy_health - x)         if x > 1 < 3:             "%d" % x             print "your kick effective enemy lost %d hp"             print("enemy health is" enemy_health - x)         if x == 1:             print "enemy lost 1 point"             print("enemy health is" enemy_health - x)      def attackchoice(c):         if c == "punch":             punch()         if c == "kick":             kick()      c = raw_input("choice attack\nkick or punch: ")     attackchoice(c)   i want print:
choose attack kick or punch:kick enemy lost 3 hp enemy's heath 17 choose attack kick or punch:punch enemy lost 1 hp enemy's health 16      
- as blender pointed out not changing value of enemy_health subtracting x , printing without assigning value back.
 - move initial assignment out of while loops.
 - you have string thing in kick code
 - use randint instead of building list , picking one
 
maybe like:
import random health = 20 enemy_health = 20  def punch():     global enemy_health     x = random.randint(1,3)     enemy_health -= x     if x == 3:         print"your hit effective enemy lost 3 hp"     if x == 2:         print "your punch effective enemy lost 2 hp"     if x == 1:         print "enemy lost 1 point"     print "enemy health is", enemy_health  def kick():     global enemy_health     x = random.randint(1,5)     enemy_health -= x     if x > 3:         print "your kick effective enemy lost %d hp" % x     if x > 1 < 3:         print "your kick effective enemy lost %d hp" % x     if x == 1:         print "enemy lost 1 point"     print "enemy health is", enemy_health  def attackchoice(c):     if c == "punch":         punch()     if c == "kick":         kick()  while true:     c = raw_input("choice attack\nkick or punch: ")     attackchoice(c)      
Comments
Post a Comment