我刚刚完成了本文的练习,并想知道是否可以使用相同的技术(词典,if语句等)更有效地完成此操作。这似乎是低效的代码。
挑战如下: 为角色扮演游戏编写角色创建程序。玩家应该获得30分的积分,花费在四个属性上:力量,健康,智慧和敏捷。玩家应该能够在任何属性上花费游泳池中的积分,并且还应该能够从属性中获取积分并将它们放回池中。
答案 0 :(得分:3)
你可以轻松改进的一件事是第一个'if's:
系列if pts2 == "1":
skills["Strength"] += pts
points -= pts
...
使用字典skills_dict = {"1": "Strength", "2": "Health", ... }
即可:
skills[skills_dict[pts2]] += pts
points -= pts
第二组'if's
相同答案 1 :(得分:0)
嗯,你的代码看起来不那么优雅的一种方式是有很多非常相似的序列,特别是:
if rmv2 == "3":
if rmv < skills["Dextarity"]:
skills["Dextarity"] -= rmv
points += rmv
else:
print("No")
唯一不同的是输入是什么,修改了什么属性,以及是否要添加或删除值。如果您找到了将其转换为可重用组件的方法,您可以使代码看起来更好一点,就像使用函数一样。
答案 2 :(得分:0)
一些意见:
points=int(30)
30已经是一个int。改为
points=30
另外
while player != "e":
可能应该是:
while selection != "exit"
我将这个程序拆分成大量小函数,并为角色创建一个类来存储技能和剩余点。
答案 3 :(得分:0)
我认为你正在寻找这样的东西。第5章没有解释函数,所以我没有包含任何函数。
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
print("Good-Bye.")
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
input("\n\nPress the enter key to exit.")