注意:我没有找你重新制作我的代码,我正在寻找有助于我改进此代码的网站的提示和链接。如果您想修复代码,我也会接受您的回答。
我试图理解class
是如何运作的,但是,我真的很难这样做。我创建了一个名为class
的{{1}},其中包含给定用户的所有统计信息。用户的所有统计信息均为Stat
。每个name, level, totexp and role
有3个统计信息(它应该有三个,但我的代码搞砸了),role
。这是主要代码(不工作):
health, attack, and defense
在主代码之后,class Stat():
def __init__(self, name, level, totexp, role, health, attack, defense):
self.name = Name
self.level = 1
self.totexp = 0
self.role = Role
self.health = health
self.attack = attack
self.defense = defense
self.exp = 0
def choose_name():
while(True):
Name = input("What is your Dicer's name?:\n").title()
if(any(Bad_Words in Name.lower() for Bad_Words in [])):
print("That's an inappropriate name! Try again")
elif(len(Name) < 3):
print("That name is too short! Try again.")
elif(len(Name) > 16):
print("That name is too long! Try again.")
else:
break
def choose_role():
Roles = {
'mage':lambda:Role(100, 40, 10), #(Health, Attack, Defense)
'warrior':lambda:Role(100, 30, 20),
'gunner':lambda:Role(100, 20, 30),
'archer':lambda:Role(100, 10, 40)
}
while(True):
Role = input("What role do you want to be?\nChoices:\n1. Mage\n"
"2. Warrior\n3. Gunner\n4. Archer\n").title()
if(Role.lower() in (Roles)):
return
else:
print("That's not a role! Try again.")
self = choose_name()
self = choose_role()
(在标题中)或结果代码应Results
相应于实例的顺序print
。结果代码如下:
Stats
当我运行代码时出现错误:
print("Here is your Dicer's information:\nDicer's name: {0}\n"
"Level: {1}\nExperience: {2}\nRole: {3}\nRole Stats:\n"
"Health: {4}\nAttack: {5}\nDefense: {6}".format(self.name, self.level,
self.totexp, self.role,
self.health, self.attack,
self.defense))
我想我已经知道为什么会这样,但我不知道如何解决它。你能帮助我开始我的代码和修复方法。这是我想要的结果(对于这个例子,Name = Bob和Role = Gunner):
Traceback (most recent call last):
File "python", line 37, in <module>
AttributeError: 'NoneType' object has no attribute 'name'
答案 0 :(得分:2)
我有点犹豫要发布这个因为代码是一个巨大的混乱。但是你说你不想重写你只是想看看你的代码是固定的,所以这里修复了。我评论了我改变的一切
#renamed stat to player, the point of the object shouldn't be to hold just the stats, should hold all information
#pertaining to the player / dicer
class Dicer():
#levelm, totalexp, health removed from constructor
def __init__(self, name, role, health, attack, defense):
self.name = name #changed Name to name
self.level = 1
self.totexp = 0
self.role = role #changed Role to role
self.health = health
self.attack = attack
self.defense = defense
self.exp = 0
#instance function to print the stats of the dicer
def print_info(self):
print(
"Here is your Dicer's information:\nDicer's name: {0}\nLevel: {1}\nExperience: {2}\nRole:"\
" {3}\nRole Stats:\nHealth: {4}\nAttack: {5}\nDefense: {6}".format(self.name, self.level, self.totexp, self.role, self.health, self.attack, self.defense)
)
def choose_name():
while(True):
Name = input("What is your Dicer's name?:\n").title()
if(any(Bad_Words in Name.lower() for Bad_Words in [])):
print("That's an inappropriate name! Try again")
elif(len(Name) < 3):
print("That name is too short! Try again.")
elif(len(Name) > 16):
print("That name is too long! Try again.")
else:
#you have to return the name so you can use it later
return Name
def choose_role():
#removed all the lambdas here
Roles = {
'mage': (100, 40, 10), #(Health, Attack, Defense)
'warrior': (100, 30, 20),
'gunner': (100, 20, 30),
'archer': (100, 10, 40)
}
while(True):
Role = input("What role do you want to be?\nChoices:\n1. Mage\n2. Warrior\n3. Gunner\n4. Archer\n").title()
if(Role.lower() in (Roles)):
#don't just return None, return the name of the role and it's 3-tuple stats
#returning the role and it's stats from a function is not the best way to do this
return Role, Roles[Role.lower()]
else:
print("That's not a role! Try again.")
dicer_name = choose_name()
dicer_role_name, dicer_role_stats = choose_role()
#create a dicer using the stats returned from chose_role() function
mainDicer = Dicer(dicer_name, dicer_role_name, dicer_role_stats[0], dicer_role_stats[1], dicer_role_stats[2])
mainDicer.print_info()
如果从头开始编写,我将如何做到这一点
class Dicer():
def __init__(self, name, role, statTuple):
self.name = name
self.level = 1
self.xp = 0
self.health = statTuple[0]
self.attack = statTuple[1]
self.defense = statTuple[2]
def print_stats(self):
print("Name", self.name)
print("Level", self.level)
print("XP", self.xp)
print("Health", self.health)
print("Attack", self.attack)
print("Defense", self.defense)
roles = {
#health, attack defense
"mage" : (100, 40, 10),
"warrior" : (100, 30, 20),
"gunner" : (100, 20, 30),
"archer" : (100, 10, 40)
}
name = input("What is your name ")
dicer_role_choice = None
while dicer_role_choice not in roles.keys():
print("Please select a dicer:")
#prints each role on a new line, showing all the possible choices
print("\n".join(roles.keys()))
dicer_role_choice = input()
mainDicer = Dicer(name, dicer_role_choice, roles[dicer_role_choice])
mainDicer.print_stats()
答案 1 :(得分:0)
我在这里修改了我的代码:
代码提供者:Bradley Elko
更新1 [51行]
更新2 [97行]
更新3 [127行]
更新4 [148行]
class Char():
def __init__(self):
self.name = ""
self.role = ""
self.health = 0
self.health_now = 0
self.health_gained = 0
self.attack = 0
self.defense = 0
self.glob()
self.add_name()
self.add_role()
self.print_info()
self.menu()
def glob(self):
global Level, TotXp, Xp, Info, Points
Level = 1
Points = 15
TotXp = 0
Xp = 0
Info = "Not Filled In Yet"
def print_info(self):
print("\nYour Character's Stats:")
print("Your character's name is: {0}".format(self.name))
print("Your character is level: {0}".format(Level))
print("You have {0} Level Points\n".format(Points))
print("Your Role Stats:")
print("Your character's role is: {0}\nYour character's health is: {1}\nYour character's attack is: {2}\nYour character's defense is: {3}".format(self.role, self.health, self.attack, self.defense))
print("\nIntroduction To Game:\n{0}".format(Info))
def add_name(self):
while(True):
Name = input("What's your character's name?\n")
if(len(Name) < 3):
print("That name is too short!")
elif(len(Name) > 20):
print("That name is too long!")
elif(any(bad_word in Name.lower() for bad_word in ['fuck'])):
print("That name is inappropriate!")
else:
self.name += Name
break
def add_role(self):
global Role
Roles = {
"Marksman": (100, 50, 30),
"Melee":(100, 40, 40),
"Mage":(100, 30, 50)
}
while(True):
Role = input("\nWhat's your characters role?\nChoices:\n1. Marksman\n2. Melee\n3. Mage\n").title()
if(Role not in ['Marksman', 'Melee', 'Mage']):
print("That's not a role!")
else:
self.role += Role
self.health += Roles[Role][0]
self.health_now += Roles[Role][0]
self.attack += Roles[Role][1]
self.defense += Roles[Role][2]
break
def menu(self):
global Choice
print("\nMenu\nWelcome to the menu! Here is where you will be staying in between fights, regaining health, and using the shop.\n")
while(True):
Choice = input("Where do you want to go?\n1. Shop\n2. Fight\n3. Sleep\n4. Role Stats\n5. Char Stats\n").lower()
if(Choice == "shop"):
return self.shop()
elif(Choice == "fight"):
print("Needing updating!")
break
elif(Choice == "sleep"):
self.sleeping()
break
elif(Choice == "role stats"):
return self.role_stats()
elif(Choice == "char stats"):
return self.char_stats()
else:
print("That's not an option!")
def menu_two(self):
global Choice
print("\nMenu\nWelcome back to the menu!")
while(True):
Choice = input("Where do you want to go next?\n1. Shop\n2. Fight\n3. Sleep\n4. Role Stats\n5. Char Stats\n").lower()
if(Choice == "shop"):
return self.shop()
elif(Choice == "fight"):
print("Needing updating!")
break
elif(Choice == "sleep"):
self.sleeping()
break
elif(Choice == "role stats"):
return self.role_stats()
elif(Choice == "char stats"):
return self.char_stats()
else:
print("That's not an option!")
def role_stats(self):
global Choice
if(Choice == "role stats"):
print("\nRole Stats:\nRole: {0}\nHealth: {1}\nAttack: {2}\nDefense: {3}\n".format(self.role, self.health, self.attack, self.defense))
return self.menu_two()
def shop(self):
while(True):
Buy = input("\nWelcome to the shop! Here is were you spend your level points. What do you want to purchase?\nChoices:\n1. Abilities\n2. Weapons\n3. Stat Points\n4. Nothing\n").lower()
if(Buy == "abilities"):
print("\nYou selected 'Abilities'.")
break
elif(Buy == "weapon"):
print("\nYou selected 'Weapons'.")
break
elif(Buy == "stat points"):
print("\nYou selected 'Stat Points'.")
break
elif(Buy == "nothing"):
print("\nReturning to menu...")
return self.menu_two()
else:
print("\nThat is not an option!")
def char_stats(self):
global Choice
if(Choice == "char stats"):
print("\nYour Character's Stats:")
print("Username: {0}".format(self.name))
print("Level: {0}".format(Level))
print("Level Points: {0}".format(Points))
return self.menu_two()
def sleeping(self):
global Choice
import time
if(Choice == "sleep" and self.health_now >= self.health):
print("\nYour health is full and so you don't need to sleep. Returning to menu.")
return self.menu_two()
elif(Choice =="sleep" and self.health_now < self.health):
print("\nYou are sleeping to regain health. This doubles your characters health regeneration! Please wait patently as your character sleeps to regain health faster.")
for i in range(1, 1801):
time.sleep(1)
if(i in [60,120,180,240,300,360,420,480,540,600,660,720,780,840,900,960,1020,1080,1140,1200,1260,1320,1380,1440,1500,1560,1620,1680,1740,1800]):
self.health_gained += 10
self.health_now += 10
if(self.health_now < self.health):
print("\nYou're still healing. You've regained %d health!\nCurrent health:\nHealth: %d/%d" % (self.health_gained, self.health_now, self.health))
else:
print("\nYou're done healing! You've regained %d health!\nCurrent health:\nHealth: %d/%d" % (self.health_gained - (self.health_now - self.health), self.health, self.health))
print("\nYou woke up from your healing nap. Returning to menu.")
return self.menu_two()
self.health_gained -= 10
MyChar = Char()
更新1日期[2016年10月6日]
更新2日期[2016年10月6日]
更新3日期[2016年11月6日]
更新4日期[2016年6月14日]