使用Python类制作游戏-如何更新self init?

使用Python类制作游戏-如何更新self init?,python,Python,我正在基于python制作一个基于文本的游戏,使用类系统跟踪主要角色的变化(比如它的名字)。我正在编写游戏的主代码,它在主角色类之外,在主函数内部 我很挣扎,因为我需要将Main character类中的self.character\u名称更新为Main函数中用户的输入。我不确定如何做到这一点,我有下面写的代码-但它不是更新内的主要字符类的名称。我怎样才能重写这个 我还担心我在尝试更新宠物时会遇到这个问题。然而,我似乎没有这个问题与更新健康或XP class Main_Character():

我正在基于python制作一个基于文本的游戏,使用类系统跟踪主要角色的变化(比如它的名字)。我正在编写游戏的主代码,它在主角色类之外,在主函数内部

我很挣扎,因为我需要将Main character类中的self.character\u名称更新为Main函数中用户的输入。我不确定如何做到这一点,我有下面写的代码-但它不是更新内的主要字符类的名称。我怎样才能重写这个

我还担心我在尝试更新宠物时会遇到这个问题。然而,我似乎没有这个问题与更新健康或XP

class Main_Character():

def __init__(self):
    self.health=100
    self.exp=0    
    self.level=0
    self.character_name=""
    self.characters_known={None}
    self.pets={None}
    self.progression_tracker=0

def __str__(self):
    return "Name: "+ str(self.character_name)+"  |  "+ "Health:"+ str(self.health) + "  |  " +"XP:"+ str(self.exp) + "  |  "+ "Level:"+ str(self.level)+"  |  "+"Pets:"+str(self.pets)

def Char_Name(self,name):
    if name.isalpha()==False:
        print("You entered a name containing non-alphabetic characters, pease reenter a new name:")
        main()
    elif len(name)>=10:
        print("You entered a name containing 10 or more characters, pease reenter a new name:")
        main()
    else:
        self.character_name=name


def Char_Level_Experience(self,exp,b):
    self.exp+=exp
    b=2
    if exp<=0:
        exp=1
    ans = 1
    level=0
    while ans<exp:
        ans *= b
        level += 1
    if ans == exp:
        self.level=level
        print("You have reached level", self.level)
    else:
        level = int(log(exp, 2))
        level = min(level, exp) 
        if level>=0:
            self.level=level
        else:
            level=0


def healing(self,heal):
    if self.health+heal>=100:
        self.health=100
    else:
        self.health+=heal


def other_answers(answer):
    if answer=='quit':
        raise SystemExit
    if answer=='pets':
        print("Pets owned:", Main_Character().pets)
        user_decision=input("Would you like to continue where you left off?    Type 'yes' to continue, or 'no' to go back to main menu")
        if user_decision=='yes':
            if Main_Character().progression_tracker==0:
                main()
            elif Main_Character().progression_tracker==1:
                choice1()
        if user_decision=='no':
                main()
        else:
            other_answers(user_decision)
    if answer=='characters':
        print("Characters met:", Main_Character().characters_known)
        user_decision=input("Would you like to continue where you left off? Type 'yes' to continue, or 'no' to go back to main menu:")
        if user_decision=='yes':
            if Main_Character().progression_tracker==0:
                main()
            if Main_Character().progression_tracker==1:
                choice1()
        if user_decision=='no':
                main()
        else:
            other_answers(user_decision)

def start_check():
    print("If you understand the game, type 'go' to continue- if not, type 'more information' to receive more information about how to play the game")
    begin_game=input("")
    if begin_game=="go":
        choice1()
    if begin_game=='more information':
        print("\n","The object of the game is to gain XP [experience points] without dying")
        start_check()
    else:
        other_answers(begin_game)

def choice1():
    Main_Character().progression_tracker=1
    print("You are a knight in the Kings Guard- the King has asked to meet with you about a very special mission")
    print("What would you like to do?")
    print("  1.Go Directly to King","\n", "2. Finish your dinner")
    choice=input("1 or 2?")
    if choice=="1":
        Main_Character().Char_Level_Experience(1,2)
    elif choice=="2":
        Main_Character().Char_Level_Experience(.5,2)
    else:
        other_answers(choice)
    print(Main_Character())

def main(): 
    print("Welcome!")
    unfiltered_name=input("Please enter the name of your character:")
    Main_Character().Char_Name(unfiltered_name)
    print("Welcome,", Main_Character().character_name,"!", "Here are your current stats!")
    print(Main_Character())
    start_check()
class主字符()
定义初始化(自):
自我健康=100
self.exp=0
self.level=0
self.character_name=“”
self.characters_known={None}
self.pets={None}
self.progression\u tracker=0
定义(自我):
返回“Name:”+str(self.character_Name)+“|”+“Health:”+str(self.Health)+“|”+“XP:”+str(self.exp)+“|”+“Level:”+str(self.Level)+“|”+“Pets:+str
def Char_名称(自我,名称):
如果name.isalpha()==False:
打印(“您输入了一个包含非字母字符的名称,请重新输入一个新名称:”)
main()
elif len(名称)>=10:
打印(“您输入的名称包含10个或更多字符,请重新输入新名称:”)
main()
其他:
self.character\u name=名称
def字符级别经验(自我、经验、b):
self.exp+=exp
b=2
如果exp=100:
自我健康=100
其他:
自我健康+=治愈
def其他_答案(答案):
如果答案==“退出”:
升起系统出口
如果答案==“宠物”:
打印(“宠物所有:”,主字符()
user_decision=input(“您想继续您离开的地方吗?键入“是”继续,或键入“否”返回主菜单”)
如果用户_决策==‘是’:
如果Main_Character().progression_tracker==0:
main()
elif Main_Character().progression_tracker==1:
选择1()
如果用户_决策==‘否’:
main()
其他:
其他答案(用户决定)
如果答案=='characters':
打印(“遇到的字符:”,主字符()。已知字符)
user_decision=input(“您想继续您离开的地方吗?键入‘是’继续,或键入‘否’返回主菜单:”)
如果用户_决策==‘是’:
如果Main_Character().progression_tracker==0:
main()
如果Main_Character().progression_tracker==1:
选择1()
如果用户_决策==‘否’:
main()
其他:
其他答案(用户决定)
def start_check():
打印(“如果您了解游戏,请键入“go”继续,如果不了解,请键入“more information”以接收有关如何玩游戏的更多信息”)
开始游戏=输入(“”)
如果开始游戏==“开始”:
选择1()
如果开始游戏==‘更多信息’:
打印(“\n”,“游戏的目标是在不死亡的情况下获得XP[经验点]”)
开始检查()
其他:
其他答案(开始游戏)
def choice1():
主字符()
打印(“你是国王卫队中的一名骑士-国王要求与你会面,商讨一项非常特殊的任务”)
打印(“您想做什么?”)
打印(“1.直接去找国王”,“2.吃完你的晚餐”)
选择=输入(“1或2?”)
如果选项==“1”:
主要字符().字符级别经验(1,2)
elif选项==“2”:
主要字符()
其他:
其他答案(选择)
打印(主字符()
def main():
打印(“欢迎!”)
unfiltered_name=input(“请输入您的角色名称:”)
Main_Character().Char_Name(未筛选的_Name)
打印(“欢迎”,主要字符()
打印(主字符()
开始检查()

您还不太了解类和实例是如何工作的

当您需要一个新角色时,调用类就是您要做的事情。每次调用
Main\u Character()
,都会得到一个全新的实例,其默认值在
\uuuu init\uuuu
中设置。如果你的每个朋友都有自己的角色,那么你会给每个朋友都打一次电话。然后,您需要将这些实例中的每一个都保存在一个变量中,以便每次都可以再次引用它们

例如:

my_character = Main_Character()
unfiltered_name=input("Please enter the name of your character:")
my_character.Char_Name(unfiltered_name)
print("Welcome,", my_character.character_name,"!", "Here are your current stats!")
print(my_character)
每次调用
Main\u character
时都会创建一个新字符。相反,您应该调用它一次:

the_character = Main_Character()
...
the_character.name = "..."

这不仅仅是一个问题。他试图从类方法内部调用main()。隐藏递归;))但是,我理解,当我这样做时,更新的名称将只在主函数内部工作,而不是在角色可能做出的每个选择的所有函数中工作。是。你需要传递这个变量。或者,您可能需要重新考虑程序的结构,并将函数转换为类本身的方法;然后所有的东西都放在一个地方,这就是封装的要点。一般来说,尽量减少代码示例。对于Python,在发布时仔细检查缩进(在这个问题中,它显然是错误的)。此外,确保行短(少于80个字符)并遵循标准样式(最后一行是“加号”)