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

2024-09-27 23:24:32 发布

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

我做了一个4位数的猜谜游戏来学习python,它符合三个条件:

  • 可重播
  • 告诉玩家猜出正确答案需要多少次
  • 告诉玩家多少个数字是正确的引导玩家正确的答案

我以为我符合标准,但是游戏中出现了一个奇怪的错误。如果你试着用试错法来猜数字,游戏就会中断,而且不会检测到你的答案是正确的。如果答案是“[1,2,3,4]”并且你试图通过做“[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

Tags: oftheto答案inifcountrandom
1条回答
网友
1楼 · 发布于 2024-09-27 23:24:32

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

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

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

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

^{pr2}$

有关不按顺序比较列表的详细信息,请参阅answer。在

另外,在与1进行比较之前,您应该增加计数,否则程序会说您只进行了一次,而实际上只进行了两次。在

相关问题 更多 >

    热门问题