gpt4 book ai didi

python - 访问外部函数中创建的参数和变量 (Python)

转载 作者:行者123 更新时间:2023-12-01 09:03:30 25 4
gpt4 key购买 nike

import time


def classBase(class_name, class_health, class_damage, class_hit_chance):
print("You are a " + class_name + "!")

def enemyBase(enemy_name, enemy_health, enemy_damage, enemy_hit_chance, enemy_alive):
time.sleep(2)
print("Out of nowhere, a " + enemy_name + " appears!")
enemy_total_health = enemy_health



print("Welcome to Blades of Goblonia!")
user_name = input("What is your name?")
type(user_name)
print("Hello, " + user_name + "!")
user_class_choice = input("""What class would you like to be?
A) Warrior
B) Hunter
C) Wizard""")
if user_class_choice == "A" :
user_class = classBase("Warrior", 50, 7, 95)
elif user_class_choice == "B" :
user_class = classBase("Hunter", 40, 10, 85)
elif user_class_choice == "C" :
user_class = classBase("Wizard", 35, 12, 80)

enemyBase("Goblin", 30, 10 , 60, True)

time.sleep(1)

user_action_choice = input("""Would you like to
A) Hit
B) Run
C) Heal""")

if user_action_choice == "A" :
print("Hit")
elif user_action_choice == "B" :
print("Run")
elif user_action_choice == "C" :
print("Heal")

在我的游戏代码中,我试图访问并改变敌人基地的健康状况,因为它在我重新创建它时发生了变化。为了创建伤害效果,我需要更改enemy_total_health的值,但我无法引用该变量。我该如何编写代码才能访问局部变量和参数?谢谢:)

最佳答案

出于您的目的,您应该将 Enemy 创建为一个类,并为 goblin 创建一个 Enemy 类的实例,以便将敌人作为对象的所有属性进行跟踪:

class Enemy:
def __init__(self, name, health, damage, hit_chance, alive):
self.name = name
self.health = health
self.total_health = health
self.damage = damage
self.hit_chance = hit_chance
self.alive = alive
print("Out of nowhere, a " + name + " appears!")

goblin = Enemy("Goblin", 30, 10, 60, True)
print('%s has a total health of %d' % (goblin.name, goblin.total_health))

关于python - 访问外部函数中创建的参数和变量 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52267267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com