Python 继续循环回初始值
我尝试学习python才3周,所以我不能完全确定我在做什么。我想做一个简单而愚蠢的小游戏,在玩家和电脑之间的战斗中,我用randint给出一个随机值。健康值一直循环回到原始值,我似乎不明白为什么。。。我已经找了好几天了。我加入了一个中断来阻止这场战斗,但它不会让“健康”达到零。谢谢你的帮助Python 继续循环回初始值,python,loops,break,Python,Loops,Break,我尝试学习python才3周,所以我不能完全确定我在做什么。我想做一个简单而愚蠢的小游戏,在玩家和电脑之间的战斗中,我用randint给出一个随机值。健康值一直循环回到原始值,我似乎不明白为什么。。。我已经找了好几天了。我加入了一个中断来阻止这场战斗,但它不会让“健康”达到零。谢谢你的帮助 from random import randint n = input() print ('Welcome, ', n, ' Choose your weapon: Sword, Axe, or Mace
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')
来自随机导入randint
n=输入()
打印(‘欢迎,’,n,‘选择你的武器:剑、斧头或狼牙棒’)
b=输入()
如果b=={'Swarme'}:
印刷体(‘好的选择’,(n),‘剑会保护你的安全’)
elif b=={'Axe'}:
打印('Good Choice',(n),'斧头会造成一些伤害')
elif b=={'Mace'}:
打印(‘可能是个错误的选择’,(n),‘狼牙棒又重又慢,但可以保护你。’
打印(‘骑士接近!’,(n),‘准备好’,(b),‘准备好!’
玩家=50
骑士=50
战斗=真实
当玩家>=0或骑士>=0时:
如果b==‘剑’:
k2=(奈特-兰迪特(3,4))
p2=(玩家-兰丁(2,6))
打印('你击中了骑士!他的健康现在',k2)
打印('他也打了你!你现在的健康状况',p2)
elif b==‘斧头’:
打印('你已经击中了骑士!他的健康现在是',骑士-兰丁(2,6))
print('他也打了你!你现在的健康状况很好',player-randint(3,4))
elif b==‘梅斯’:
打印('你已经击中了骑士!他的生命值现在为',骑士-randint(0,7))
打印('他也打了你!你现在的健康状况很好',玩家-兰丁(2,6))
如果玩家你在任何时候都不会改变你的生命值,除非玩家拿起剑。打印信息时,尚未设置变量。请注意,当b=‘剑’时,只有k2=(骑士-兰丁(3,4))或p2。计算骑士-兰丁(2,6)
的结果不会更改骑士的值
我想你可能想要这样的东西:
damage = randint(2, 6)
knight = knight - damage
您正在打印k2和p2,它们在每次运行时都会重新分配,并且没有上一次运行的内存。i、 你的玩家和骑士变量永远不会改变。为什么不干脆做:
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)
在从第24行开始的代码块中:如果b==‘剑’: 不要使用k2和p2来重新分配骑士和玩家的生命值,而是使用与循环外的初始分配相同的变量“玩家和骑士”
knight = (knight - randint(3,4))
player = (player - randint(2,6))
每次循环运行时,都将使用更新的运行状况值。只有当
b=='swarm'
时,才可以更改运行状况值。其他时候,你打印信息,但从不设置变量。即使这样,也没有任何变化。他计算了k2
,但随后它只被打印出来,从未重新分配回原始knight
变量。它似乎起了作用。谢谢大家的意见。