2016-03-03 80 views
-1

遊戲的規則是你已經有3堆棍子。第一堆有3個,第二個有5個,最後一個有7個。兩名球員輪流移除每個球杆上的杆,但球杆必須超過一個,並且少於杆上的杆數。誰挑選最後一根棍子將贏得比賽。python的nim遊戲?

問題:第一次採摘沒問題,木棒按照預期的方式被切斷,但第二次又回到初始狀態。

def bill_board(): 
    player=1 
    pile_1='*'*3 
    pile_2='*'*5 
    pile_3='*'*7 
    player=1 
    print('Player ',player,"'s Turn",sep='') 
    print('1: ',pile_1) 
    print('2: ',pile_2) 
    print('3: ',pile_3) 

def pile_input(): 
    while True:  
     while True: 
      pile=int(input('pile? ')) 
      if pile in range(1,4): 
       break 
      print('illegal choose: only 1-3') 

     if pile==1: 
      while True: 
       stick=int(input('Sticks? ')) 
       pile_1='*'*3 
       pile_2='*'*5 
       pile_3='*'*7 
       length_1=len(pile_1) 
       if stick>0 and stick<=length_1: 
        break 
        print('bad choose') 
      length_1=len(pile_1)  
      pile_1=length_1-stick 
      pile_1='*'*pile_1 
      print('1: ',pile_1)`enter code here` 
      print('2: ',pile_2) 
      print('3: ',pile_3) 

     elif pile==2: 
      while True: 
       stick=int(input('Sticks? ')) 
       pile_1='*'*3 
       pile_2='*'*5 
       pile_3='*'*7 
       length_2=len(pile_2) 
       if stick>0 and stick<=length_2: 
        break 
        print('bad choose') 
      length_2=len(pile_2) 
      pile_2=length_2-stick 
      pile_2='*'*pile_2 
      print('1: ',pile_1) 
      print('2: ',pile_2) 
      print('3: ',pile_3) 

     else: 
      while True: 
       stick=int(input('Sticks? ')) 
       pile_1='*'*3 
       pile_2='*'*5 
       pile_3='*'*7 
       length_3=len(pile_3) 
       if stick>0 and stick<=length_3: 
        break 
        print('bad choose') 
      length_3=len(pile_3) 
      pile_3=length_3-stick 
      pile_3='*'*pile_3 
      print('1: ',pile_1) 
      print('2: ',pile_2) 
      print('3: ',pile_3) 


def game(): 
    print('Welcome to NIM!!!') 
    print() 
    bill_board() 
    pile_input() 
game()`enter code here` 

回答

0

有一大堆的在你的代碼,你要重新初始化的變量要存儲的棍棒地方:

  pile_1='*'*3 
      pile_2='*'*5 
      pile_3='*'*7 

每次運行這些線路時,樁會重置爲初始狀態。如果您想要保持所做更改的效果,則只需更改一次該值,然後在繼續執行其餘代碼時繼續使用修改後的值。 (請注意,使用整數列表而不是數字變量跟蹤三個堆棧的長度可能會更容易,您可以遍歷該列表以生成字符串*當你要輸出它們時需要)。