如何正确编码此减法循环? - 编辑:找到解决方案

时间:2018-02-06 01:47:56

标签: python-3.x

编辑:在我弄清楚之后,在原始代码下方添加了新代码。

原始问题:我是论坛的新手,并且正在深入学习python 2天。

有人能告诉我如何让这个代码循环直到兽人死了吗?

它可以减去生命值,但是在OrcnewHP< = 0之前循环战斗部分然后打印胜利文本的正确逻辑是什么?

UserHP目前没什么用处但是一旦我理解了循环,我就会让兽人攻击回来。

关于确保输入(1)被按下与任何输入的任何提示都将被理解,但不是必需的。当我跋涉阅读我的教学书时,只是把我的脑袋缠绕在语言上并尝试制作自己的东西。这个特殊的问题似乎已经陷入了困境。

# Combat Simulator

import random
import time

    print(' Welcome to combat simulator. Press any key then <enter> to begin.')
input()

print('loading...')
time.sleep(2)

UserHP=50
UserHP=int(UserHP) 
OrcHP=30
OrcHP=int(OrcHP)

print('An Orc stands before you. Press 1 to attack it.')
input()

OrcHP=str(OrcHP)
print('The Orc has ' + OrcHP + 'hit points.')
time.sleep(1)

AttackValue = random.randint(1, 10)
HitValue = AttackValue

HitValue = str(AttackValue)

print('You attack the Orc for ' + HitValue + ' hit points!')

HitValue = int(HitValue)
OrcHP=int(OrcHP)

OrcnewHP = OrcHP - HitValue

OrcnewHP = str(OrcnewHP)

print('The orc has ' + OrcnewHP + ' hit points remaning.')
time.sleep(1)

到目前为止,它给出了一个值,但我希望存储该值并重复循环,直到值达到0或更低,每次输入越来越低。

我会更多地在网上寻找答案,但我不知道要查找的内容的名称,或者我确信它很容易找到。

先谢谢,我知道有人可以在20秒内对此进行编码..

编辑:让我更具体,因为我是新来的,仍在四处寻找答案。我已经注意到每个人都希望你对你的问题有所了解,所以这里有:

在此代码中,用户按下任何内容,程序调用随机整数,然后从OrcHP中减去该整数以获取OrcnewHP。

我只能让它发生一次。我尝试过编写一段代码,但不是重复Python只是说&#34;意外的缩进。&#34;显然我很新,我不明白python接受什么作为&#34;块&#34;什么不是。我基本上试图从行#34; AttackValue = random.randint(1,10)重复到第&#34;打印(&#39;兽人有&#39; + OrcnewHP +&#39;生命点重生。&#39;)&#34;接近尾声。在此期间,如果OrcnewHP的值达到零或更低,我希望代码打印胜利文本。类似于&#34;打印(&#39; SMASH!兽人死了,干得好!&#39;)

当OrcnewHP达到零或以下值以打印胜利文本时,这是一个非常简单的循环。

再次抱歉我的小说。如果这个问题对每个人来说都太简单了,那就不要去做评论了。我最终会弄明白,但这似乎是一个提问的好地方,让人们回答自己的方便。

谢谢!

最终编辑和答案:我明白了。这是新代码,以防任何人想要知道如何使用for循环进行尝试来执行此简单循环。

# Combat Simulator

import random
import time

print(' Welcome to combat simulator. Press any key then <enter> to begin.')
input()

print('loading...')
time.sleep(2)

UserHP=50
UserHP=int(UserHP) 
OrcnewHP=30
OrcnewHP=int(OrcnewHP)
Attempt=20

print('An Orc stands before you. Press 1 to attack it.')
input()

OrcnewHP=str(OrcnewHP)
print('The Orc has ' + OrcnewHP + 'hit points.')
time.sleep(1)

for attempt in range(20):
    AttackValue = random.randint(1, 10)
    HitValue = AttackValue

    HitValue = str(AttackValue)

    print('You attack the Orc for ' + HitValue + ' hit points!')

    HitValue = int(HitValue)
    OrcnewHP=int(OrcnewHP)

    OrcnewHP = OrcnewHP - HitValue

    OrcnewHP = str(OrcnewHP)

    print('The orc has ' + OrcnewHP + ' hit points remaning.')
    time.sleep(1)

    OrcnewHP = int(OrcnewHP)

    if OrcnewHP > 0:
        print('Attack again? Press Y. ')
        input()

    if OrcnewHP <= 0:
        break

print('SMASH! Good job you destroyed the orc!')

0 个答案:

没有答案