继续循环回到初始值python

时间:2018-06-21 00:56:42

标签: python loops break

尝试学习python仅3周时间,因此我无法完全确定自己在做什么。我试图制作一个简短而又愚蠢的简短游戏,在该游戏中,我使用randint在玩家与计算机之间的战斗中给出随机值。健康值不断循环回到原始值,我似乎无法弄清楚为什么...一直在寻找几天。我稍作休息以停止战斗,但它的“健康”值均未达到零。感谢您的帮助。

from random import randint

n = input()
print ('Welcome, ', n, ' Choose your weapon: Sword, Axe, or Mace.')
b = input()

if b == {'Sword'}:
    print ('Good Choice ', (n), ' the Sword will keep you safe.')
elif b == {'Axe'}:
    print ('Good Choice ', (n), ' the Axe will do some damage.')
elif b == {'Mace'}:
    print ('Probably a bad choice ', (n), ' the mace is heavy and slow but may protect you.')

print ('The Knight Approaches! ', (n), ', Get your', (b),' and get ready!')


player = 50 
knight = 50

battle = True

while player >= 0  or knight >= 0:

    if b == 'Sword':
        k2 = (knight - randint(3,4)) 
        p2 = (player - randint(2,6))
        print ('You have struck the knight!  His health is now', k2)
        print ('He has hit you as well!  Your health is now', p2)

    elif b == 'Axe':
        print ('You have struck the knight!  His health is now', knight - randint(2,6))
        print ('He has hit you as well!  Your health is now', player - randint(3,4))

    elif b == 'Mace':
        print ('You have struck the knight!  His health is now', knight - randint(0,7))
        print ('He has hit you as well!  Your health is now', player - randint(2,6))

    if player <= 0: 
        print ('You have died...')
    elif knight <= 0:
        print ('You have won!')

    break

print ('Good Game')

4 个答案:

答案 0 :(得分:0)

除了玩家选择剑以外,您不会更改健康值。在打印信息时,您尚未设置变量。请注意,当b =='Sword'时,只有k2 =(knight-randint(3,4))或p2。

答案 1 :(得分:0)

计算fetch()的结果不会更改knight的值。

我想您可能想要这样的东西:

knight - randint(2,6)

答案 2 :(得分:0)

您正在打印k2和p2,它们分别在每次运行时分配,并且没有上一次运行的内存。即您的玩家和骑士变量永远不会改变。为什么不这样做:

if b == 'Sword':
        knight = knight - randint(3,4) 
        player = player - randint(2,6)
        print ('You have struck the knight!  His health is now', knight)
        print ('He has hit you as well!  Your health is now', player)

答案 3 :(得分:0)

在第24行开始的代码块中:if b =='Sword':

与其使用k2和p2来重新分配骑士和玩家健康,请使用与初始分配相同的变量,而不是循环,玩家和骑士。

knight = (knight - randint(3,4))
player = (player - randint(2,6))

每次运行循环时,将使用更新的健康值。