正如你们中的一些人可能知道的那样,在几乎任何游戏中,创造或提升角色的一部分就是能力分数的提高。在这个例子中,角色有六种能力,有预先分配的分数:力量、灵巧、智慧、智慧、魅力和体质。代码的用户可以选择将1分加2分,或者两个不同的分数加一个。
我的代码运行良好,但是,我意识到它是笨重的、丑陋的,而且可能是python运行它的罪过。你能帮我简化/简化它吗?谢谢
def ability(self):
choice = raw_input("leveling up: do you want to increase 'one' score by two, or 'two' scores by one each?")
if choice == "one":
score = raw_input("which ability do you want to increase by two?")
if score == "strength":
self.strength = self.strength + 2
elif score == "dexterity":
self.dexterity = self.dexterity + 2
elif score == "intelligence":
self.intelligence = self.intelligence + 2
elif score == "wisdom":
self.wisdom = self.wisdom + 2
elif score == "charisma":
self.charisma = self.charisma + 2
else:
self.constitution = self.constitution + 2
else:
score = raw_input("which ability do you want to increase by one?")
if score == "strength":
self.strength = self.strength + 1
elif score == "dexterity":
self.dexterity = self.dexterity + 1
elif score == "intelligence":
self.intelligence = self.intelligence + 1
elif score == "wisdom":
self.wisdom = self.wisdom + 1
elif score == "charisma":
self.charisma = self.charisma + 1
else:
self.constitution = self.constitution + 1
score_two = raw_input("which second ability do you want to increase?")
if score_two == "strength":
self.strength = self.strength + 1
elif score_two == "dexterity":
self.dexterity = self.dexterity + 1
elif score_two == "intelligence":
self.intelligence = self.intelligence + 1
elif score_two == "wisdom":
self.wisdom = self.wisdom + 1
elif score_two == "charisma":
self.charisma = self.charisma + 1
else:
self.constitution = self.constitution + 1发布于 2018-06-19 20:41:27
重复的代码几乎总是更好地替换为一个函数。考虑一种用给定值改变能力的类方法。这可以通过getattr和setattr来实现(我相信这是最干净的)。调用getattr(x,'spam')将返回值x.spam,类似地,setattr(x,'spam',n)将x.spam的值设置为n。
当用户输入意想不到的内容时,再加上一条有用的消息,将产生如下代码:
def ability(self):
choice = raw_input("Leveling up: do you want to increase 'one' score by two, or 'two' scores by one each?")
while True:
if choice == "one":
stat = raw_input("Which ability do you want to increase by two?")
self.alter_stat(self, stat, 2)
break
elif choice == "two":
first_stat = raw_input("Which first ability do you want to increase by one?")
self.alter_stat(self, first_stat, 1)
second_stat = raw_input("Which second ability do you want to increase?")
self.alter_stat(self, second_stat, 1)
break
else:
print("Hmm, I don't understand. Enter 'one' or 'two' next time!")
def alter_stat(self, stat, alteration):
assert stat in ['charisma', 'constitution', 'dexterity', 'intelligence', 'strength', 'wisdom'], "That's not a valid ability!"
old_value = getattr(self, stat)
setattr(self, stat, old_value + alteration)https://codereview.stackexchange.com/questions/196847
复制相似问题