2016-04-29 41 views
0

我正在製作一個模擬Roshambo(岩石,紙,剪刀)的遊戲。 一切都很好,除非你贏了一場比賽,我得到一個錯誤。這是我的代碼。無法解決我的錯誤。 TypeError:'int'類型的對象沒有len()

###import the random module 
import random 
import time 
##my function 
def RockPaperScissors(): 
    print("This is Roshambo Simulator 2016 copyright © Jared is Cool") 
    time.sleep(2.5) 
    print("Your score is on the left, and the computers is on the right.") 
    time.sleep(1.25) 
    score = [0,0] 
    print(score) 
    cpu = 1, 2, 3 
### game loop! you choose your weapon 
    while True: 
     while True: 
      choice = input("Rock(1), Paper(2), or Scissors(3)?") 
      if choice == "1": 
       whichOne = 1 
       break 
      elif choice == "2": 
       whichOne = 2 
       break 
      elif choice == "3": 
       whichOne = 3 
       break 

##who wins the roshambo 
     cpu = random.choice(cpu) 
     if whichOne == cpu: 
      print("stale!") 
      print(score) 
     elif (whichOne == 3 and cpu == 2) or (whichOne == 2 and cpu == 1) or (whichOne == 1 and cpu == 3): 
      print("win!") 
      score[0] = score[0] + 1 
      print(score) 
     else: 
      print("lose") 
      print(score) 
      score[1] = score[1] + 1 

RockPaperScissors() 

這是我不斷收到的錯誤。

Traceback (most recent call last): 
    File "python", line 41, in <module> 
    File "python", line 28, in RockPaperScissors 
TypeError: object of type 'int' has no len() 
+2

cpu = random。選擇(cpu)''在這裏你可以用選項(一個整數)替換你的選擇列表。嘗試'cpu_choice = random.choice(cpu)'並替換下面的'cpu'-名稱。 :) – MSeifert

+2

'cpu = random.choice(cpu)'正在用一個選項替換你的元組'1,2,3''。通過循環第二次,你會得到你報告的錯誤。一個好的調試技術是在發出錯誤的行之前加上'print'語句來檢查你的變量是否包含你期望的內容。 –

+0

感謝MSeifert的幫助,並感謝Paul Hankin的建議。這解決了我的問題。做得好! – jrod

回答

3

你的問題是在這條線:

cpu = random.choice(cpu) 

是第一次運行時,它的工作原理,因爲cpu在你的代碼的開始分配的元組。當循環再次出現時它會失敗,因爲你已經用單個值(一個整數)替換了元組。

我建議使用不同的變量一個值,所以行會是這樣的:

cpu_choice = random.choice(cpu) 

你可以選擇使用random.randint(1,3)挑選的價值,而不是與元組打擾的。

1

正如評論已經提到:

cpu = random.choice(cpu) here you replace your list of choices by the choice (an integer). Try cpu_choice = random.choice(cpu) and replace the following cpu -names.

但你也可以做一些更多的東西把它縮短:

玩家選擇:

while True: 
    choice = input("Rock(1), Paper(2), or Scissors(3)?") 
    if choice in ["1", "2", "3"]: 
     whichOne = int(choice) 
     break 

電腦的選擇:

cpu_choice = random.choice(cpu) 

if whichOne == cpu_choice: 
    print("stale!") 

elif (whichOne, cpu_choice) in [(3, 2), (2, 1), (1, 3)]: 
    print("win!") 
    score[0] = score[0] + 1 

else: 
    print("lose") 
    score[1] = score[1] + 1 

print(score) # Call it after the if, elif, else 
相關問題