如何从Python中函数所在的行继续编写代码?

2024-09-27 23:15:47 发布

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

我的文本游戏中有一个nameType()函数,它被使用了两次:

  1. 创建一个stats类(或者其他什么),这样程序就可以保存它们,并且
  2. 游戏中的一个函数,用于改变某些变量

以下是此帖子针对的当前代码(可能会发生更改):

def TitleScreen():
blankHuge()
anar()
print('The Game of Hierarchy and Anarchy\nBy Roach\nText Edition\n▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬\nType "new" to start a new game.\nTo load a game, type "load".\nTo exit, type "exit".')
StartGame = input()
if StartGame == 'new':
    print('► Crew Member: Hello, fine man. I can see you are on an adventure to the land of Salbury.\nBefore you disembark the boat, please enter your name.')
    for filename in file:
        os.unlink(filename)
    nameType()
    global PlayerIG                   
    PlayerIG = Player(CharName)
    print('► Crew Member: Thanks for travelling with us, and have a great time,',PlayerIG.name,'.')
    saveGame()
    MainMenu()
# more stuff that aren't related down here...

以下是nameType()函数:

def nameType():
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()

        if confirmName == 'yes': # If this is true, then jump to next codeline from where the nameType() func was placed...
            pause() # Doesn't work

        if confirmName == 'no':
            nameType()
        else:
            print('► Invalid Input!')
            nameType()

下面是一个函数,它应该从原来的位置继续代码,但它不起作用:

def pause():
pause = input('► Press Enter to continue.')
if pause != '':
    pause()

有没有办法继续我的代码

示例(很可能行不通):

def TitleScreen():
    ...
    nameType() # Someway, jump to next line after code in nameType() has been executed...
    global PlayerIG
    PlayerIG = Player(CharName) 
    ...
    saveGame()
    MainMenu() 

def management():
    ...
    opt = input()
    if opt = 'name':
        nameType() # Someway, jump to next line after code in nameType() has been executed...
        PlayerIG.nameWait = 12
        PlayerIG.heat = 0
    ...

注意:我知道这将如何工作,但我不确定它是否能工作。它是:

# outside of nameType()
if confirmName == 'yes':
    ...

Tags: to函数代码nameyouinputifdef
1条回答
网友
1楼 · 发布于 2024-09-27 23:15:47

我的想法奏效了,在nameType()函数之外使用if确实有效。我使用了global(我知道这是个糟糕的编码,但不管怎样),现在这个函数可以工作了

def nameType():
global confirmName
global CharName
print('▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬')
CharName = input()
if CharName != '':
    if len(CharName) > 20:
        print('► The name is too long!')
        nameType()
    else:
        print('► Are you sure this is what you want as a name?\nIf so, type "yes".\nOtherwise, type "no".')
        confirmName = input()
# Items down here for the confirmName input removed

# This is the system for the 'jump':
if confirmName == 'blah1':
    # add stuff here...    
    if confirmName == 'no':
        # add stuff here...
    else:
        # add stuff here...

相关问题 更多 >

    热门问题