繁体   English   中英

如何在python上将变量限制为零

[英]how to limit a variable to zero on python

我已经开始在 python 上制作一个新游戏并拥有它,所以如果玩家 1 或玩家 2 的健康状况为零或更低,代码结束,但我不想显示玩家的健康状况,例如,-12 最后。 这是代码:

player1 = 50
player2 = 50
while player1 >= 0 or player2 >= 0:
    import random

    slash = random.randint(5, 9)
    stab = random.randint(1, 15)
    swing = random.randint(15, 20)
    heal = random.randint(10, 15)
    a = [slash, stab, swing]
    ai = random.choice(a)
    hit1 = input("Press 1 2 3 or 4")
    if hit1 == "1":
        print("You dealt " + str(slash))
        player2 = player2 - slash
        print("Player 2 now has " + str(player2))
    if hit1 == "2":
        print("You dealt " + str(stab))
        player2 = player2 - stab
        print("Player 2 now has " + str(player2))
    if hit1 == "3":
        print("You dealt " + str(swing))
        player2 = player2 - swing
        print("Player 2 now has " + str(player2))
    if hit1 == "4":
        print("You healed by " + str(heal))
        player2 = player1 + heal
        print("Player 1 now has " + str(player1))
    hit2 = print("player 2 has dealt " + str(ai))
    player1 = player1 - ai
    print("player1 is now on " +str(player1))

你可以在python中使用max函数。

对于您的相关线路:

 player2 = max(player2 - slash, 0)

 player2 = max(player2 - stab, 0)

 player2 = max(player2 - swing, 0)

 player1 = max(player1 - ai, 0)

此外,您需要更改 while 条件:

while player1 > 0 or player2 > 0:

编辑

player1 = 50
player2 = 50
while player1 > 0 and player2 > 0:
    import random

    slash = random.randint(5, 9)
    stab = random.randint(1, 15)
    swing = random.randint(15, 20)
    heal = random.randint(10, 15)

    hit_number_to_hit_type = {'1': slash,
                              '2': stab,
                              '3': swing}
    a = [slash, stab, swing]
    ai = random.choice(a)
    hit1 = input("Press 1 2 3 or 4\n")
    if "1" <= hit1 <= "3":
        hit = hit_number_to_hit_type[hit1]
        print("You dealt " + str(hit))
        player2 = max(player2 - hit, 0)
        print("Player 2 now has " + str(player2))
    if hit1 == "4":
        print("You healed by " + str(heal))
        player1 += heal
        print("Player 1 now has " + str(player1))
    hit2 = print("player 2 has dealt " + str(ai))
    player1 = max(player1 - ai, 0)
    print("player1 is now on " + str(player1))
if str(player) < 0 {
   print("player1 is now on 0 health")
}

和/或

if str(player) > 5 {
   print("player1 is now on 5 health")
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM