python-3.x - 如何重构此 Python 代码以使其更具可读性和紧凑性?
问题描述
我编写了一个函数来处理选择和使用项目以在文本冒险中恢复玩家的健康。缩小以下代码的最佳方法是什么?任何反馈或建设性的批评将不胜感激。
提前致谢。
另外,我真的很难理解面向对象的编程。有没有人推荐一本关于 OOP 主题的书(最好用 Python 例子来教)?
def use_item(action):
print("What item do you want to use? Type the name of the item.")
print("Inventory:")
for items in player_inventory:
print(items)
action = input("> ")
if action == "fruit":
if action == "fruit" and "Fruit" not in player_inventory:
print("You don't have any fruit.")
print("Enter 'u' again if you want to select something else.")
elif action == "fruit" and "Fruit" in player_inventory:
print("You ate some fruit. You are refreshed.")
player_inventory.remove("Fruit")
player_health += 25
if player_health > 100:
player_health = 100
print("You have",player_health,"health.")
else:
print("Invalid choice! Try again.")
elif action == "bread":
if action == "bread" and "Bread" not in player_inventory:
print("You don't have any bread.")
print("Enter 'u' again if you want to select something else.")
elif action == "bread" and "Bread" in player_inventory:
print("You ate some bread. You are refreshed.")
player_inventory.remove("Bread")
player_health += 50
if player_health > 100:
player_health = 100
print("You have",player_health,"health.")
else:
print("Invalid choice! Try again.")
elif action == "meat":
if action == "meat" and "Meat" not in player_inventory:
print("You don't have any meat.")
print("Enter 'u' again if you want to select something else.")
elif action == "meat" and "Meat" in player_inventory:
print("You ate some meat. You are refreshed.")
player_inventory.remove("Meat")
player_health += 75
if player_health > 100:
player_health = 100
print("You have",player_health,"health.")
else:
print("Invalid choice! Try again.")
elif action == "elixir":
if action == "elixir" and "Elixir" not in player_inventory:
print("You don't have any elixir.")
print("Enter 'u' again if you want to select something else.")
elif action == "elixir" and "elixir" in player_inventory:
print("You ate drank an elixir. You are fully healed.")
player_inventory.remove("Elixir")
player_health += 100
if player_health > 100:
player_health = 100
rint("You have",player_health,"health.")
else:
print("Invalid choice! Try again.")
else:
print("Invalid choice! Try again.")
解决方案
您可以创建一个只有 if/elif/else 逻辑的函数,并且每个逻辑都有自己的函数。真的很好的解释 https://realpython.com/python3-object-orientated-programming/
推荐阅读
- python - 从用户那里获取+推特最新推文的问题
- flutter - AnimatedContainer Rotation 提供了不需要的旋转
- python - 为什么 python 客户端没有收到 SSE 事件?
- node.js - 如何在 Eclipse(Windows 操作系统)中设置 Node.js 版本
- php - Zend 框架 3 在 Factory 中检查 Auth 令牌并返回 json
- xml - 比较 2 个参数值
- excel - 如何获取表中值的计数/频率?
- objective-c - SKStore审查控制器与 Xcode 11
- google-places-api - 如何让服务器端调用 Google Places API 工作?
- python - 使用 users.info 时有没有办法忽略机器人用户?