首页 > 解决方案 > 继续循环回初始值python

问题描述

我只尝试学习 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')

标签: pythonloopsbreak

解决方案


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


推荐阅读