虽然循环不在逻辑环境下破坏

时间:2014-04-10 23:39:25

标签: python debugging loops while-loop

我正在制作一个模拟骰子和做其他东西的代码,但是有一个不会破坏的循环,我不知道为什么。

import random
import math

#infinite loop
while True:
    while True:
        a = 0
        #input amount of dice
        att_die = raw_input('Attacking dice: ')
        def_die = raw_input('Defending dice: ')

        #att
        #if NaN
        if str(att_die).isdigit() == False:
            print('NaN')
        #if not NaN
        else:
            a += 1

        #def
            #if NaN
        if str(def_die).isdigit() == False:
            print('NaN')
        #if not NaN
        else:
            a +=1

        if a == 2:
            break

    if att_die >= def_die:
        no = def_die
    else:
        no = att_die

    print (no)

    x = 0
    while x <= no:
        att_loss = 0
        def_loss = 0

        roll_att = random.randint(1,6)
        roll_def = random.randint(1,6)

        if roll_att <= roll_def:
            att_loss += 1
        elif roll_att == roll_def:
            att_loss += 1
        else:
            def_loss += 1

        x += 1
        print(x)
   print('Att: -' + str(att_loss) + '\nDef: -' + str(def_loss)) 

一切正常,直到最后一个while循环,它只是连续输出x增加的值。 任何有关如何解决这个问题的帮助将不胜感激。 提前致谢

2 个答案:

答案 0 :(得分:2)

nostr,而不是intxint。在Python2中,int s总是小于str s:

In [187]: 9999 < '1'
Out[187]: True

解决方案是将str no转换为int

no = int(no)

In [188]: 9999 < int('1')
Out[188]: False

请注意,在Python3中,将intstr进行比较会引发TypeError,这将使许多程序员免于此陷阱。

答案 1 :(得分:0)

这是重构版本:

import random
import math

DIE_SIDES = 6
WINNING_ATTACK_ODDS = 0.5 * (DIE_SIDES - 1) / DIE_SIDES

def get_int(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError:
            pass

def attack():
    """
    Does the attacker win?
    """
    return random.random() < WINNING_ATTACK_ODDS

def main():
    while True:
        att_die = get_int("Attacking dice: ")
        def_die = get_int("Defending dice: ")

        rolls = min(att_die, def_die)
        def_loss = sum(attack() for _ in range(rolls))
        att_loss = rolls - def_loss

        print("Att: -{}\nDef: -{}".format(att_loss, def_loss))

if __name__=="__main__":
    main()