是什么原因导致我的程序在一个函数上运行了两次,即使它在运行一次之后应该退出?

2024-09-30 22:22:46 发布

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

我正在尝试制作一个石头、布、剪刀的游戏,我很难弄清楚为什么我的程序在一个函数上重复两次,而它本应该重复一次,然后由于一个while循环而重新开始

以下是导致问题的函数(过滤掉不必要的信息):

def playRps():  # Compares the choices and determines who won the game
    game = "".join([playerAction, computerAction])

    outcomes = {
        "rr": tied,
        "pp": tied,
        "ss": tied,
        "rp": playerLoss,
        "ps": playerLoss,
        "sr": playerLoss,
        "rs": playerWin,
        "pr": playerWin,
        "sp": playerWin,
    }

    if playerAction == "q":
        return False

    else:
        action = outcomes.get(game)
        if action:
            action()
        else:
            print("Invalid input!")

您可以找到整个functions.py文件here.

下面是调用函数并运行程序的main.py文件(过滤掉不必要的信息):

while True:
    if functions.playerScore != 0 or functions.computerScore != 0:
        functions.scores()

    playGame = str(input('Would you like to play "Rock, Paper, Scissors"? (Y/n): '))

    if playGame == "y":
        while True:
            functions.playerChoice()
            functions.computerChoice()
            functions.playRps()
            if not functions.playRps():
                break

    elif playGame == "n":
        print("Terminating program...")
        quit()

    else:
        print("Unknown input. Please enter a valid answer.")
        continue

您可以找到整个main.py文件here.

嗯,当您不输入q时,程序似乎会像预期的那样转到actions = outcome.get(game)中的functions.py。然后,它转到main.py文件,并在if not functions.playRps():验证结果

出于某种原因,它接着返回到functions.py,最后返回到actions = outcome.get(game),这增加了第二个点<然后它返回到main.py,然后它正好在if not functions.playRps():后面的break

当我没有输入q作为播放器响应时,它不应该重复playRps()两次,也不应该在main.py中点击break。由于while循环,它应该返回到playerChoice()中的main.py函数,以便玩家可以做出选择

除非玩家在调用playerChoice()函数时进入q,否则while中的while循环根本不应该被中断

我的问题是:

  • 为什么程序会重复playRps()函数两次,为什么调用main.py函数的while循环被中断,即使调用playerChoice()函数时播放器从未进入q

Tags: 文件函数py程序gameifmainfunctions
1条回答
网友
1楼 · 发布于 2024-09-30 22:22:46

正在第二次调用该函数,因为您在if statement中再次调用了该函数:

functions.playRps() # call 1
if not functions.playRps(): # call 2
    break

您应该为该函数的结果设置一个变量,以便可以在if statement中对其求值,而无需再次调用它:

result = functions.playRps()
if not result:
    break

相关问题 更多 >