无法解决我的错误。 TypeError:'int'类型的对象没有len()
问题描述:
我正在制作一个模拟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()
答
你的问题是在这条线:
cpu = random.choice(cpu)
是第一次运行时,它的工作原理,因为cpu
在你的代码的开始分配的元组。当循环再次出现时它会失败,因为你已经用单个值(一个整数)替换了元组。
我建议使用不同的变量一个值,所以行会是这样的:
cpu_choice = random.choice(cpu)
你可以选择使用random.randint(1,3)
挑选的价值,而不是与元组打扰的。
答
正如评论已经提到:
cpu = random.choice(cpu)
here you replace your list of choices by the choice (an integer). Trycpu_choice = random.choice(cpu)
and replace the followingcpu
-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
cpu = random。选择(cpu)''在这里你可以用选项(一个整数)替换你的选择列表。尝试'cpu_choice = random.choice(cpu)'并替换下面的'cpu'-名称。 :) – MSeifert
'cpu = random.choice(cpu)'正在用一个选项替换你的元组'1,2,3''。通过循环第二次,你会得到你报告的错误。一个好的调试技术是在发出错误的行之前加上'print'语句来检查你的变量是否包含你期望的内容。 –
感谢MSeifert的帮助,并感谢Paul Hankin的建议。这解决了我的问题。做得好! – jrod