首页 > 解决方案 > 在 Mastermind 游戏中重复功能的问题

问题描述

我正在设计一个用 python 玩的策划游戏。但是当我尝试设置一个函数以在尝试不完全正确时重复自身时遇到一些问题。

我的代码分为两部分。对于第一部分,它要求用户输入正确的号码,然后第二个用户尝试输入他的尝试号码。代码的第二部分将他的尝试分解为数字列表,并计算正确整数的数量和正确位置的整数数量,然后如果答案不完全正确,程序会要求用户进行第二次输入。

def getnumber():
predestine = input("Please input your test number")
a = str(predestine)
attempt()

def attempt():
  attempt = input("Attempt:")
  b = str(attempt)
  correctrecord = []
  sequencerecord = []
  for i in b:
      if i in a:
          correctrecord.append(1)
  for i in range(0,4):
      if b[i] == a[i]:
        s  equencerecord.append(1)

  correctlength = len(correctrecord)
  sequencelength = len(sequencerecord)

  print(f"You have made {correctlength} correct attempts, and of these {sequencelength} are of correct positions")

  if sequencelength == 4:
      print("You have won, the game is ended")
  else:
      return attempt()

问题在于最后一个代码:返回尝试()。似乎无法使用“str object not callable”错误重复该函数。

标签: python

解决方案


您的代码中的问题在于变量阴影。

您的重复函数位于名为 的变量中attempt,即全局变量。然后,在attempt函数内部定义一个attempt字符串变量,该变量是该函数的本地变量,因此暂时隐藏了attempt保存该函数的全局变量。

因此,调用attempt()失败,因为您实际上是在尝试调用字符串。

解决方案是重命名本地字符串变量attempt以不影响全局变量:

def attempt():
    attempt_ = input("Attempt:")
    b = str(attempt_)
    correctrecord = []
    sequencerecord = []
    for i in b:
        if i in a:
            correctrecord.append(1)
    for i in range(0,4):
        if b[i] == a[i]:
            sequencerecord.append(1)

    correctlength = len(correctrecord)
    sequencelength = len(sequencerecord)

    print(f"You have made {correctlength} correct attempts, and of these {sequencelength} are of correct positions")

    if sequencelength == 4:
        print("You have won, the game is ended")
    else:
        return attempt()

推荐阅读