这个程序本来是要转到一个函数,但却遵循try和except循环

2024-05-15 23:11:40 发布

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

我决定在python3.3中制作一个基本的游戏,其中怪物和宝藏分别在1-100之间的数字上生成,用户必须选择一个数字。然后程序会通知用户他们是否离得太近或太高,或者是否碰到了什么东西

我用一个except NameError做了一个try循环(因为我在Mac上,对于Windows来说是ValueError)。在我提出任何问题之前,我想与大家分享我目前掌握的代码:

import time, random

def generateValues():
    global treasurePos, monsterPos
    while treasurePos != monsterPos:
        treasurePos = random.randint(1, 100)
        monsterPos = random.randint(1, 100)
    print(treasurePos)
    print(monsterPos)

def mainmenu():
    time.sleep(0.5)
    print("welcome to this game, press 1 to play or 2 to quit")
    time.sleep(0.5)
    try:
        option = int(input("What would you like to do: "))
        if option == (1):
            time.sleep(0.5)
            generateValues()
        elif option == (2):
            quit()
    except NameError:
        time.sleep(0.5)
        print("please enter only 1 or 2")            



mainmenu()

如果我输入1,我最初的计划是让游戏继续并生成宝藏和怪物的位置。相反,程序所做的是循环回到:

except NameError:
        time.sleep(0.5)
        print("please enter only 1 or 2")

这进一步创建了一个无限循环“请只输入1或2”-即使我输入1

因此,我的问题是,有没有一个简单或复杂的命令可以阻止这个循环继续,并允许程序继续执行'generateValues'函数

如果您愿意分享任何帮助或见解,我将不胜感激

提前谢谢, 狮子座

编辑1:

Karen Clark指出了我的while循环,我为它编写了一个替代解决方案,如下所示:

def generateValues():
    global treasurePos, monsterPos
    treasurePos = 0
    monsterPos = 0
    treasurePos = random.randint(1, 3)
    monsterPos = random.randint(1, 5)
    if treasurePos == monsterPos:
        generateValues()
    else:
        print(treasurePos)
        print(monsterPos)

Tags: orto程序timedefsleeprandomoption
2条回答

调用generateCharPosition()时出现拼写错误。函数定义是正确的,但是调用缺少一个“i”-generateCharPosi选项

问题出在generateValues()函数中。你需要初始化TreasePos和monsterPos来工作。试试这个:

def generateValues():
    global treasurePos, monsterPos
    treasurePos = 10
    monsterPos = 1
    while treasurePos != monsterPos:
        treasurePos = random.randint(1, 100)
        monsterPos = random.randint(1, 100)
    print(treasurePos)
    print(monsterPos)

一定要给他们不同的价值观。如果不是,代码就不会进入循环

相关问题 更多 >