2014-04-10 67 views
0

打破我想提出一个代码来模拟一个骰子和做其他的东西,但有一个while循环未被打破,我不知道为什么。While循环不是在逻辑的情况下

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的值增加。 如何解决这个问题的任何帮助,将不胜感激。 在此先感谢

+0

另外,我运行2.7.6。我不知道这是否重要 –

+0

在您的打印声明中添加'no'并显示输出 – mackworth

回答

2

nostr,而不是intxint。在Python2,int s的总是比较小于str S:

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

的解决方案是将strno转换成int

no = int(no) 

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

注意在Python3中,比较intstr引发了一个TypeError,这会使很多程序员从这个陷阱中解脱出来。

+0

哇。我不敢相信我是那么愚蠢。谢谢,我一直在想这个问题我们现在大概一个小时了--_- –

+1

@ user3337069如果它解决了您的问题,您应该将其标记为可接受的解决方案 –

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()