2014-04-10 66 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()