无法修复我的错误。类型错误:int类型的对象没有长度()。

2024-04-25 07:25:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个游戏来模拟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()

这是我一直得到的错误。在

^{pr2}$

Tags: orandtheimporttimeisrandomcpu
2条回答

正如评论中已经提到的:

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

计算机选择:

^{pr2}$

你的问题在这一行:

cpu = random.choice(cpu)

第一次运行时,它是有效的,因为cpu在代码的开头被分配了一个元组。但是,当循环再次出现时,它将失败,因为您已经用单个值(整数)替换了元组。在

我建议对一个值使用不同的变量,因此该行应该类似于:

^{pr2}$

您也可以使用random.randint(1,3)来选择值,而不必为元组操心。在

相关问题 更多 >