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

2024-09-29 19:31:31 发布

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

这里的Noob正试图让我的头脑明白我的想法。我知道这不是Python之类的。我只是想让一个基本的系统在这里工作,但这是最接近我正在尝试的功能版本。尝试了很多方法,但似乎无法正确更新options。真的希望一些反馈能为我指明正确的方向。Iv包含了整个代码,我的主要问题是battleChoice函数中带有注释部分的部分。我无法使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)

Tags: keynameinselffalsetruevaluedef
2条回答

在Player.element()中是否定义了字典“elements”(我希望应该是它)

然后,在Player.attacking()中迭代字典,然后执行以下操作:

P.beatsEnemy = True
enemy.beatsEnemy = False

此处没有任何更改,因为您没有明确说明要更改的值(它与键链接)。 此外,将值指定给键没有意义。 你最好这样做:

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

这应该行得通

发生这种情况是因为您在全局范围中声明了options,并在challenge()函数内的局部范围中重新声明了它。因此,当您在本地更新选项时,全局变量根本不会更改

您至少有以下两种选择:

1)

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>)

这样做的问题是:一旦程序启动,就会加载全局options数组,并且不会再次加载。在您对它进行第一次更改后,它的值将永远不会恢复到原来的状态,除非您显式地使它们恢复到原始状态

2)

参数化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      

在{}上:

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..
        

相关问题 更多 >

    热门问题