Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我的变量不改变它的值?_Python_Variables - Fatal编程技术网

Python 为什么我的变量不改变它的值?

Python 为什么我的变量不改变它的值?,python,variables,Python,Variables,我一直在做一个基于文本的游戏。我已经到了一个地步,我正试图做一场战斗。我让敌人的生命值下降,但当我再次击中它时,敌人的生命值回到了我最初设定的值。我希望这些帮助 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)')

我一直在做一个基于文本的游戏。我已经到了一个地步,我正试图做一场战斗。我让敌人的生命值下降,但当我再次击中它时,敌人的生命值回到了我最初设定的值。我希望这些帮助

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)

看到了吗?上面是正在运行的程序。我不明白为什么没有更改该值。

因为您正在迭代开始时初始化它。所以只要移动鼠标就行了

enemyhp= 50
在while循环之前,像这样

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

只是为了好玩,我扩展了您的示例程序,以包括一些更高级的语言结构。也许你会觉得它很有趣: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()

x!=y或z不会将x与y和z进行比较。它被解析为x!=y或z,这不是你想要的。如果你想检查某物是否是几个选项中的一个,你需要的是x而不是y,z。这只是问题的一部分。当你做的时候,你就行了!='“用剑击中老鼠”或“逃跑”:有缺陷,因为“逃跑”的计算结果始终为true,它不是将“do”与两个字符串进行比较,而是将do与第一个字符串进行比较,并使用始终为true的值对其进行ORing。