我正在制作一个模拟Roshambo(岩石,纸张,剪刀)的游戏。 一切都很好,除非你赢了一场比赛,我得到一个错误。这是我的代码。
###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()
答案 0 :(得分:3)
您的问题就在这一行:
cpu = random.choice(cpu)
第一次运行时,它的工作原理是因为cpu
在代码的开头被赋予了一个元组。然而,当循环再次出现时,它会失败,因为您已经用单个值(整数)替换了元组。
我建议为一个值使用不同的变量,因此该行将类似于:
cpu_choice = random.choice(cpu)
您也可以使用random.randint(1,3)
来选择值,而不必担心元组。
答案 1 :(得分:1)
正如评论中已经提到的那样:
cpu = random.choice(cpu)
在这里您可以通过选择(整数)替换您的选择列表。尝试cpu_choice = random.choice(cpu)
并替换以下cpu
- 姓名。
但你也可以做更多的事情来缩短它:
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