制作一个小rpg,但是如果不调用整个函数,就无法将一个函数中的变量值传递给另一个函数

2024-06-28 15:39:56 发布

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

我基本上是想从函数“gym”到函数“local_badass”得到一个变量(strength0、strength1、strength2,取决于用户选择)。如果我尝试用return捕捉它,它将调用整个函数,从而返回游戏中的一步

只是想知道是否有办法根据用户的选择获取变量及其值,这样我就可以在未来的游戏级别中使用变量(strength0、strength1和strength2),从而影响用户在游戏中的表现,例如,如果strength<;2不能打败龙

def start():
    print("Hi there, you are sitting in your room.")
    print("A voice inside your head says let's go and have some fun.")
    print("You have two options.")
    print("1. Go to the gym.")
    print("2. Go elsewhere.")
    choice = input(">   ")

    if choice == "1":
        gym(list(range(3)))
    elif choice == "2":
        elsewhere()

def bedroom():
    print("You are back in your bedroom after the gym.")
    print("You have one option: ")
    print("1. Go elsewhere.")
    choice = input(">   ")

    if choice == "1":
        start()

def gym(strength):
    print("You arrive at the gym, your muscles are aching for some action.")
    print("Do you wish to go hard or take it easy, or not bother at all?")
    print("0. Enough of this, let's go home.")
    print("1. Go soft, I don't want to risk injury.")
    print("2. Go hard, I was born for this.")
    choice_gym = input(">   ")

    if choice_gym == "0":
        print("You are tired just walking to the gym and decide to go home.")
        global strength0
        strength0 = strength.pop(0)
        print(f"Strength is: {strength0}")
        bedroom()


    elif choice_gym == "1":
        print("You take it easy, but make some gains.")
        global strength1
        strength1 = strength.pop(1)
        print("Strength is now: ", strength1)
        bedroom()


    elif choice_gym == "2":
        print("You go hard, dripping sweat and testosterone everywhere.")
        print("Boy do you feel strong.")
        strength2 = strength.pop(2)
        print("Strength is now: ", strength2)
        bedroom()


    else:
        print("Invalid selection, please try again.")
        gym(list(range(3)))

def dead():
    print("Your are dead. Bad luck.")
    exit(0)

def elsewhere():

    print("You leave your house, a slight breeze ruffles your hair as you look around.\nYou pull a map out of your pocket and see 3 things you can do.")
    print("1. Challenge the local badass.")
    print("2. Challenge the UFC champion.")
    print("3. Defeat the dragon.")
    choice = input(">   ")

    if choice == "1":
        print("You have chosen the local badass.")
        print("Seeking out local badass...")
        local_badass()

def local_badass():
    if strength1 > 0 or strength2 > 0:
        print("You whooped his ass.")
    else:
        print("You got your ass kicked.")



start()

Tags: theyouyourlocaldefarestrengthgym
1条回答
网友
1楼 · 发布于 2024-06-28 15:39:56

一个简单的方法是建立一个球员统计数据的全球列表。这似乎是你已经在用strength做的事情

也许可以上一节课把他们都关在里面:

class Player:
    def __init__( self ):
        self.strength1  = 10
        self.strength2  = 10
        self.luck       = 7.3
        self.muchness   = 12

您需要创建Player实例

player_stats = Player()

但是,您可以在函数中访问它:

def local_badass():
    global player_stats
    if player_stats.strength1 > 0 or player_stats.strength2 > 0:
        print("You whooped his ass.")
    else:
        print("You got your ass kicked.")

不过,全局变量通常是不受欢迎的。因此,如果您愿意,可以将玩家的统计信息传递给每个函数,但在这种情况下,这似乎有点毫无意义

如果我可以提供一些建议。。。可能值得创建一个getUserInput()函数,该函数可以接受范围选项,并处理所有错误输入、错误、退出等。这比每次调用input()并分别重复检查要好

比如:

def getUserInput( prompt, min_input, max_input ):
    """ Get a valid number from the user that's between min & max.
        If the user inputs "quit", exit the program.
        Keep prompting until a valid option is entered.              """
    result = None
    while ( result == None ):                    # Asking until we get valid input
        choice = input( prompt )
        choice = choice.trim().lower()
        if ( choice == 'quit' or choice == 'exit' ):
            print( "\nbye..." )
            sys.exit( 0 )
        else:
            try:
                number = int( choice )           # Did the user enter a valid number?
            except:
                pass  
            # Did we get valid input?
            if ( number >= min_input and number <= max_input ):                   
                # Correct input, set the result 
                result = str( number )           # Convert result back to string
            else:
                # The input was invalid, loop around again
                print( "Valid input is a number %d → %d, or \"quit\"\n" % ( min_input, max_input ) )
    return result

相关问题 更多 >