2013-11-24 3 views
-2

Я делаю текстовую игру. Я дошел до точки, где я пытаюсь сражаться. У меня враг hp идет вниз, но когда я ударил его снова, враг hp вернулся к тому, что я изначально задал. Надеюсь, это поможет.Почему моя переменная не меняет свои значения?

while do != 'hit rat with sword' or 'run away': 
    enemyhp= 50 
    enemyattack= [0,1,3] 
    OldSwordattack= [0,1,4] 
    print('What do you do?(attack or run away)') 
    do=input() 
    if do == 'run away': 
     print('You can\'t leave mom like that!') 
    if do == 'hit rat with sword': 
     hit= random.choice(OldSwordattack) 
     if hit == OldSwordattack[0]: 
      print('Your swing missed') 
      print('Enemy\'s HP=' + str(enemyhp)) 
     if hit == OldSwordattack[1]: 
      print('Your swing hit, but very lightly.') 
      enemyhp= enemyhp - 1 
      print('Enemy\'s HP=' + str(enemyhp)) 
     if hit == OldSwordattack[2]: 
      print('Your swing hit head on!') 
      enemyhp= enemyhp - 4 
      print('Enemy\'s HP=' + str(enemyhp)) 

>In front of mom you see a giant, yellow-teethed rat. 
>What do you do?(attack or run away) 
>hit rat with sword 
>Your swing hit, but very lightly. 
>Enemy's HP=49 
>What do you do?(attack or run away) 
>hit rat with sword 
>Your swing hit, but very lightly. 
>Enemy's HP=49 
>What do you do?(attack or run away) 

Вы видите? Вышеупомянутая программа работает. Я не понимаю, почему значение не изменяется.

+1

'x! = Y или z' не сравнивает' x' с 'y' и' z'. Он анализируется как '(x! = Y) или z', что вы не хотите. Если вы хотите проверить, является ли что-то одним из нескольких вариантов, вы хотите «x не в (y, z)». – user2357112

ответ

0

потому что вы инициализируете его в начале итерации. Так просто переместить

enemyhp= 50 

перед циклом в то время, как этот

enemyhp= 50 
while do != 'hit rat with sword' or 'run away': 
+0

Это только часть проблемы. строка 'while do! = 'ударяет крысу с мечом' или« убегает »:' ошибочен, потому что «убежать» всегда оценивает значение true, это не сравнение «do» с обеими строками, это сравнение выполняется с первой строкой и ORing его с всегда истинным значением. – Crast

0

Просто для удовольствия я расширил свой пример программы, чтобы включить некоторые более продвинутые языковые конструкции. Можете ли вы найти это интересным: (Python 3)

import random 
import re 

def dice(s, reg=re.compile('(\d+d\d+|\+|\-|\d+)')): 
    """ 
    Executes D+D-style dice rolls, ie '2d6 + 3' 
    """ 
    total = 0 
    sign = 1 
    for symbol in reg.findall(s): 
     if symbol == '+': 
      sign = 1 
     elif symbol == '-': 
      sign = -1 
     elif 'd' in symbol: 
      d,s = [int(k) for k in symbol.split('d')] 
      for i in range(d): 
       total += sign * random.randint(1, s) 
     else: 
      total += sign * int(symbol) 
    return total    

class Character(): 
    def __init__(self, name, attack, defense, health, weapon): 
     self.name = name 
     self.attack = attack 
     self.defense = defense 
     self.health = health 
     self.weapon = weapon 

    def hit(self, target): 
     if self.is_dead: 
      print('{} is trying to become a zombie!'.format(self.name)) 
      return 0 

     attack = self.attack + self.weapon.attack_bonus + dice('2d6') 
     defense = target.defense + dice('2d6') 
     if attack > defense: 
      damage = int(random.random() * min(attack - defense + 1, self.weapon.damage + 1)) 
      target.health -= damage 
      print('{} does {} damage to {} with {}'.format(self.name, damage, target.name, self.weapon.name)) 
      return damage 
     else: 
      print('{} misses {}'.format(self.name, target.name)) 
      return 0 

    @property 
    def is_dead(self): 
     return self.health <= 0 

class Weapon(): 
    def __init__(self, name, attack_bonus, damage): 
     self.name   = name 
     self.attack_bonus = attack_bonus 
     self.damage  = damage 

def main(): 
    name = input("So, what's your name? ") 

    me = Character(name,   4, 6, 60, Weapon('Old Sword', 2, 4)) 
    mom = Character('Mom',  2, 2, 50, Weapon('Broom',  0, 1)) 
    rat = Character('Crazed Rat', 5, 2, 40, Weapon('Teeth',  1, 2)) 

    print("You are helping your mother clean the basement when a Crazed Rat attacks. " 
      "You grab your Grandfather's sword from the wall and leap to defend her!") 

    actors = {me, mom, rat} 
    coward = False 
    killer = None 
    while (me in actors or mom in actors) and rat in actors: 
     x = random.choice(list(actors)) 
     if x is mom: 
      mom.hit(rat) 
      if rat.is_dead: 
       killer = mom 
       actors -= {rat} 
     elif x is rat: 
      target = random.choice(list(actors - {rat})) 
      rat.hit(target) 
      if target.is_dead: 
       actors -= {target} 
       if target is mom: 
        print('Your mother crumples to the floor. AARGH! This rat must die!') 
        me.attack += 2 
       else: 
        print('Well... this is awkward. Looks like Mom will have to finish the job alone...') 
     else: # your turn! 
      print('Me: {}, Mom: {}, Rat: {}'.format(me.health, 0 if mom.is_dead else mom.health, rat.health)) 
      do = input('What will you do? [hit] the rat, [run] away, or [swap] weapons with Mom? ') 
      if do == 'hit': 
       me.hit(rat) 
       if rat.is_dead: 
        killer = me 
        actors -= {rat} 
      elif do == 'run': 
       if me.health < 20: 
        actors -= {me} 
        coward = True 
       else: 
        print("Don't be such a baby! Get that rat!") 
      elif do == 'swap': 
       me.weapon, mom.weapon = mom.weapon, me.weapon 
       print('You are now armed with the {}'.format(me.weapon.name)) 
      else: 
       print('Stop wasting time!') 

    if rat.is_dead: 
     if mom.is_dead: 
      print('The rat is gone - but at a terrible cost.') 
     elif me.is_dead: 
      print("Your mother buries you with your trusty sword by your side and the rat at your feet.") 
     elif coward: 
      print("The rat is gone - but you'd better keep running!") 
     elif killer is me: 
      print("Hurrah! Your mother is very impressed, and treats you to a nice cup of tea.") 
     else: 
      print('Your mother kills the rat! Treat her to a nice cup of tea before finishing the basement.') 
    else: 
     print('I, for one, hail our new rat overlords.') 

if __name__=="__main__": 
    main() 
Смежные вопросы