猜测游戏中输入多个相同数字;循环停止工作?

时间:2015-10-17 10:32:53

标签: python list loops random input

我一直在制作一个4号猜谜游戏来学习符合三个标准的python:

  • 重玩
  • 告诉玩家猜测正确答案需要多少次尝试
  • 告诉玩家许多数字如何正确引导玩家正确回答

我认为我符合标准,但游戏中发生了这个非常奇怪的错误。如果您尝试使用反复试验来猜测数字;游戏中断并且没有检测到你的答案是对的。如果答案是“[1,2,3,4]”并且您试图通过'[1,1,1,1]'然后'[1,2,2,2,]'并最终得到答案得到'[1,2,3,4]';该程序会说4个号码匹配,但它不会让你赢得游戏,只是要求你再次玩。这个错误真的让我感到害怕,我希望阅读的人能理解我想说的话。

对于长长的代码块感到抱歉,但问题可能在这里的任何地方,但老实说我看不到它;我会尽可能地注释,使它看起来不那么令人困惑。我只是......为什么会发生这种情况!?

def compareLists(a, b): # to compare the guessed numbers and random numbers
    return list(set(a) & set(b))
rNums = random.sample(range(10), 4) # random list of numbers
def start():
    count = 0 # count for number of tries
    global rNums
    gNums = [] # guessed numbers
    print(rNums) # cheating to save time
    flag = True # to stop the guessing loop

    while flag:
        print("Get ready to guess 4 numbers!")
        for i in range(0, 4): # asks the player 4 times to input a number
            x = int(input("Guess: "))
            gNums.append(x) # puts numbers in guessed numbers

        comparison = len(compareLists(rNums, gNums)) # storing the length of the list of similar numbers
        isCorrect = gNums == rNums # to check if lists are the same
        print("You guessed: ", gNums) # telling player what they have guessed

        if isCorrect: # if the lists are the same

            if count > 1:
                print("You win!! It only took you %d tries!" %count) # telling the player how many tries it took
            else: #congratulating the player on a flawless guess
                print("I CAN'T BELIEVE WHAT I'M SEEING!!!")
                print("YOU GOT IT IN ONE GO!!")
            count += 1 # increment count
            rNums = random.sample(range(10), 4) # generate new numbers
            gNums.clear()
            pAgain = input("Play again?")
            if pAgain.lower() in ('y', 'yes'): # replaying the game
                continue
            elif pAgain.lower() in ('n', 'no'):
                flag = False
            else:
                print("Incorrect syntax!")

        else:
            print("You guessed " + str(comparison) + " numbers right, keep guessing!") # tells the player how many numbers are similar so the player can get a more educated guess
            gNums.clear() # empties guessed numbers
            count += 1 # increment count
            print("Number of tries so far: %d" %count) # showing player number of tries so far

1 个答案:

答案 0 :(得分:1)

检查这两个列表是否相同的比较是不起作用的:

isCorrect = gNums == rNums # to check if lists are the same

以上代码检查两个列表是否相同,但元素的顺序必须相同。

对于您的测试,您只需检查匹配的数字(忽略顺序)是否等于数字列表的长度:

isCorrect = comparison == len(gNums) # to check if lists are the same

有关比较列表而不考虑订单的详细信息,请参阅此answer

另外,在与1进行比较之前,你应该增加你的计数,否则你的程序会说当你实际拿两个时你只需要一次。