简体   繁体   English

动态更新其他字典函数中的字典值

[英]Dynamically update dictionary values in functions from other dictionaries

Noob here trying to wrap my head around this idea I had.菜鸟在这里试图围绕我的这个想法。 I know it's not pythonic or anything.我知道这不是 pythonic 或任何东西。 Just trying to get a basic system working here but this is the closest to a functioning version of what I'm trying to do.只是试图让一个基本系统在这里工作,但这是最接近我正在尝试做的功能版本。 Tried a bunch of things and can't seem to get the options to update properly.尝试了很多东西,但似乎无法正确更新options Really hope some feedback can point me in the right direction.真的希望一些反馈可以为我指明正确的方向。 Iv included the entire code, the part with the commented section in the challenge() function by battleChoice is my main issue. Iv 包含了整个代码, challenge() battleChoice中的注释部分是我的主要问题。 I can't get the options dictionary values to change to call different functions based on the current page.我无法更改options字典值以根据当前页面调用不同的函数。

import random



class Player:

    def __init__(self, name, element, attack, defence, hp, mp, alive=True, beatsEnemy=False):
        self.name = name
        self.element = element
        self.attack = attack
        self.defence = defence
        self.hp = hp
        self.mp = mp
        self.alive = alive
        self.beatsEnemy = beatsEnemy

    def get_name(self):
        return self.name


    def element():
        print()
        print(f'Hi {P.name}, your current element is {P.element}.')
        print()
        print("What would you like to change it to?")
        print()
        for key, value in elements.items():
                print(f"{key}) {value}")

        eleInp = input("---> ")
        if eleInp in elements.keys():
            P.element = elements[eleInp]
            print(f'You have successfully changed your element to {P.element}.')

        else:
            print("Invalid")

    def spells():
        playerSpells = {}
        for key, value in elements.items():
            if P.element in elements.values():
                playerSpells = P.element.spells
                pass
            else:
                pass


    def playerInput(self):
        running = True

        while running:    

            inp = input("---> ")
            if inp in options.keys():
                options[inp]()
                for key, value in options.items():
                    print(f"{key}) {value.__name__.capitalize()}")

            else:
                print("Invalid")


    def attacking():
        enemy = random.choice(basicEnemies)
        for keys, values in elementalStrengths.items():

                    if P.element in keys and enemy.element in values:
                        print("You have the elemental advantage!")
                        P.beatsEnemy = True
                        enemy.beatsEnemy = False

                    elif enemy.element in keys and P.element in values:
                        print("Enemy has the Elemental Advantage")

                        enemy.beatsEnemy = True
                        P.beatsEnemy = False


                    else:
                        Player.beatsEnemy = False
                        enemy.beatsPlayer = False



        battling = True
        while battling:



                if P.hp <= 0 or enemy.hp <= 0:
                    print("Battle ended.")
                    battling = False
                    if P.hp <= 0:
                        print("You died!")
                        P.alive = False
                    else:
                        print(f'{enemy.name} has died!')


                elif P.hp > 0 and enemy.hp > 0:
                    print(f'{enemy.name} - {enemy.hp} HP ')
                    print()
                    print(f'{P.name} - {P.hp} HP')
                    myDamage = enemy.defence - P.attack
                    enemyDamage = P.defence - enemy.attack
                    P.hp += enemyDamage
                    enemy.hp += myDamage
                    print(enemyDamage)
                    print(myDamage)
                    print(P.hp)
                    print(enemy.hp)







class SpellBook():
    pass





class StoryLine:

    def __init__(self, name, pageNumber, currentOptions, description, info):
        self.name = name
        self.pageNumber = pageNumber
        self.currentOptions = currentOptions
        self.description = description
        self.info = info


    def print_to_screen(self):
        print(self.name)
        print(f'Page Number: {self.pageNumber}')
        for key, value in options.items():
            print(f"{key}) {value.__name__.capitalize()}")
        print(self.description)
        print(self.info)



    def change_options(self):
        for key, value in options.items():
            print(f"{key}) {value.__name__.capitalize()}")



def challenge():                                    
    print("Challenge")
    print("You wish to battle?")
    battleChoice = {'1': "yes", '2':"no"}
    options = battleChoice
    Player.playerInput(battleChoice)
    #battleChoice = int(input("""1) Yes, 2) No
#---->"""))
    #if battleChoice == 1:
        #print("Commence Battle!!!")
        #Player.playerInput(battleOptions)
        #Player.attacking()


    #elif battleChoice == 2:
        #battle = False
        #print("You cowardly ran away...")
    #else:
        #print("----> ")


def stats():
    print("_Player Stats_")
    print()
    print(f'Element - {P.element}')
    print(f'Attack - {P.attack}')
    print(f'Defence - {P.defence}')
    print(f'Health - {P.hp}')
    print(f'Mana - {P.mp}')
    print()



def menu():
    print("Menu Page ")
    print()

    print("Menu Options ")
    print()


def exits():
    print("Thanks for playing!!! :) ")

    exit()








options = {'1': challenge, '2': stats, '3': menu, '4': Player.element, '5': exits}

battleOptions = {'1': Player.attacking, '2': "defend", '3': stats, '4': "items", '5': "run"}

elementalStrengths = {"Fire":["Earth", "Lightning"], "Earth":["Water", "Wind"], "Water":["Fire", "Wind"], "Wind":["Fire", "Lightning"], "Lightning":["Earth", "Water"]}



P = Player("Random", "Lightning", 15, 10, 100, 100, True)
E1 = Player("Slime", "Water", 15, 10, 20, 20, True)
E2 = Player("Ember", "Fire", 15, 10, 20, 20, True)
E3 = Player("Wisp", "Wind", 15, 10, 20, 20, True)
E4 = Player("Rots", "Earth", 15, 10, 20, 20, True)
E5 = Player("Spark", "Lightning", 15, 10, 20, 20, True)

E6 = Player("Armored Slime", "Water", 25, 25, 250, 250, True)


basicEnemies = [E1, E2, E3, E4, E5]

intEnemies =[]

advEnemies  = []




elements = { '1': "Fire", '2': "Water", '3': "Earth", '4': "Air", '5': "Lightning"}



intro = StoryLine("Introduction ", 1, (options), "This is the introduction page. ", "Introduces the game.")
intro2 = StoryLine("Introduction Two", 2, (battleOptions), "This is the second introduction page. ", "Introduces the game again.")





print("welcome player... ")
print(P.get_name())
intro.print_to_screen()
Player.playerInput(options)

This happens because you've declared options in a global scope and re-declaring it in a local scope inside the challenge() function.发生这种情况是因为您在全局scope 中声明了options ,并在challenge() function 内的本地scope 中重新声明了它。 So when you update options locally, the global variable is not changed at all.因此,当您在本地更新选项时,全局变量根本不会更改。

You have at least these two options:您至少有以下两个选择:

1) 1)

State to challenge() that options is a reference to a global value and do the update: State challenge() options是对全局值的引用并进行更新:

def challenge(): 
    # This call makes the magic happen  
    global options   
                           
    print("Challenge")
    print("You wish to battle?")
    battleChoice = {'1': "yes", '2':"no"}

    # Now options is globally updated
    options = battleChoice
    Player.playerInput(<it looks like this function is not suppose to receive any arguments>)

The problem with this is: your global options array is loaded as soon as the program starts, and it will not be loaded again.这样做的问题是:您的全局options数组会在程序启动后立即加载,并且不会再次加载。 After the first change you make to it, it's values will never go back to what they were unless you explicitly make them go back to the original.在您对其进行第一次更改后,它的值将永远不会 go 恢复到原来的值,除非您明确地将它们 go 恢复为原始值。

2) 2)

Parameterize Player.playerInput() to receive an options array and do what is supposed to, instead of retrieving it from the global context (I'm sure that this is a better solution in your case).参数化Player.playerInput()以接收options数组并执行应做的操作,而不是从全局上下文中检索它(我确信在您的情况下这是一个更好的解决方案)。

    # Player's class
  
    def player_input(self, options):
        # Now your options are locally defined and will not be retrieved from the global context
        ... # Do what it was doing before      

And on challenge() :challenge()上:

def challenge():                                    
    print("Challenge")
    choice = input("You wish to battle?")
    if choice.lower() in ["yes", "y"]:
        Player.playerInput(battleOptions)
  
    elif choice.lower() in ["no", "n"]:
        battle = False
        print("You cowardly ran away...")

    else:
        # Default behavior..
        

In Player.element() is dictionary 'elements' (I hope it should be it) defined?在 Player.element() 中是否定义了字典“元素”(我希望它应该是它)?

Then, in Player.attacking() you iterate through the dictionary and you're doing next:然后,在 Player.attacking() 中,您遍历字典,然后您将执行以下操作:

P.beatsEnemy = True
enemy.beatsEnemy = False

nothing changes here, cause you didn't say explicitly what value(it's linked with the key)you want to change.这里没有任何变化,因为您没有明确说明要更改的值(它与键相关联)。 Also, assigning a value to a key has no sense.此外,为键赋值是没有意义的。 You'd be better do this:你最好这样做:

for key in dictionary.keys():
    if key == 'the condition you need':  # change it according to your needs
        dictionary[key] = 'the value you need'  # same, as above

that should work那应该工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM