【问题标题】:Repeating a block of "If" statement重复“If”语句块
【发布时间】:2015-02-16 15:04:13
【问题描述】:

我正在尝试制作基于文本的游戏,并且为了制作我的战斗机制,我必须重复 if 语句,直到你或怪物死去。

这里是 --
Ph 代表玩家健康,str 是玩家力量,mdam 是怪物伤害,mstr 是怪物力量,monsterh 是怪物健康,@987654327 @是你获得的攻击奖励(加上这个,有没有办法将数字四舍五入到一位或没有小数位?)谢谢! :D

if fight == "A" and ph > 0:
    damage = (str) + (random.random())
    monsterh = 6
    mstr = 0.9
    monsterh = (monsterh) - (damage)
    print(damage)
    print(damage - str)
    print('You attack the monster. You deal %s damage.' % damage ) 
    time.sleep(3)
    if monsterh > 0:
        mstr = 0.9
        mdam = (mstr) + (random.random())
        print('The monster attacks you!')
        ph = ph - mstr
        print("You get hit %s" % mdam )
    else:
        xpgain = damage + 5
        print("You won! You've gained %s XP!" % xpgain)

【问题讨论】:

  • 你想要一个while 循环。查看docs.python.org/2/tutorial/…
  • 你可以把整个事情循环起来:while i_am_not_dead and monster_is_not_dead: ...

标签: python


【解决方案1】:

对你得到的值进行四舍五入

random.random() 

你可以的

round(random.random(),1) 

四舍五入到小数点后一位,或者如果你想去掉小数点,替换

random.random() 

int(random.random())

至于重复if语句,你可以把它放到一个循环中,当一个条件满足时就会中断

while true:
    if fight == "A" and ph > 0:
        damage = (str) + (int(random.random()))
        monsterh = 6
        mstr = 0.9
        monsterh = (monsterh) - (damage)
        print(damage)
        print(damage - str)
        print('You attack the monster. You deal %s damage.' % damage ) 
        time.sleep(3)
    elif ph<=0 or fight!="A":
        print("You lose!")
        break
    if monsterh > 0:
        mstr = 0.9
        mdam = (mstr) + (int(random.random()))
        print('The monster attacks you!')
        ph = ph - mstr
        print("You get hit %s" % mdam )
    else:
        xpgain = damage + 5
        print("You won! You've gained %s XP!" % xpgain)
        break

虽然你不需要

fight!="A"
因为我认为你根本不会改变战斗的价值。

你也不必这样做

mdam = (mstr) + (int(random.random()))

你可以这样做

mdam = mstr+int(random.random())

上面的 ^ 也适用于代码中的其他地方。如果您有任何问题,请随时提出。

【讨论】:

    【解决方案2】:

    我会把你看到的战斗包装在一个 while 循环中。例如:

    while (ph > 0 or monsterh > 0)
        # combat rules
    
    # Check who died and move on from there
    if (ph > 0)
        # next thing the player does
    else
        # print "You died"
    

    关于四舍五入,有多种选择,具体取决于您想要做什么:python: getting only 1 decimal place

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 2016-08-05
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多