如果有人在这段代码中添加多样性将会很有帮助。(我是编码之旅的初学者,以Python作为我的起点)

问题描述 投票:0回答:1
creatures = \["\\U0001F47D", "\\U0001F9DF", "\\U0001F9DD"\]
creaname = \["alien", "zombie", "elf"\]
creapoints = \[5, 10, 15\]

print("Creatures to kill -\> ")
for crea, name in zip(creatures, creaname):
    print(f"-{crea} ({name})")

kill_one_name = input("Kill one of them | \\U0001F47D \\U0001F9DF \\U0001F9DD | : ").lower()
if kill_one_name in creaname:
    index = creaname.index(kill_one_name)
#print(index)
    print(f"Earned +{creapoints\[index\]} points for killing {creaname\[index\]}")
else:
    print("Invalid creature choice")

如果有人帮助我了解一些关于如何为其添加多样性的语法以及一些改进的想法,以使其更加优化和快速。

python optimization
1个回答
0
投票

将逻辑封装在函数中:将代码组织成函数可以使其更加模块化且更易于理解。每个函数可以处理特定的任务。 处理错误和异常:改进输入验证以优雅地管理意外输入。 扩展功能:添加多次尝试、评分系统或更多生物等功能。 字典的使用:这可以简化生物、它们的名称和点的管理方式,从而更容易维护和扩展。 以下是您如何结合这些建议重写代码:

def initialize_game():
    creatures = {
        "alien": {"emoji": "\U0001F47D", "points": 5},
        "zombie": {"emoji": "\U0001F9DF", "points": 10},
        "elf": {"emoji": "\U0001F9DD", "points": 15}
    }
    return creatures

def display_creatures(creatures):
    print("Creatures to kill ->")
    for name, details in creatures.items():
        print(f"- {details['emoji']} ({name})")

def kill_creature(creatures):
    attempt_limit = 3
    for attempt in range(attempt_limit):
        user_input = input("Kill one of them (alien, zombie, elf): ").lower()
        if user_input in creatures:
            print(f"Earned +{creatures[user_input]['points']} points for killing {user_input}")
            return
        else:
            print("Invalid creature choice. Please try again.")
            if attempt < attempt_limit - 1:
                continue
            else:
                print("Sorry, no more attempts left.")
                break

def main():
    creatures = initialize_game()
    display_creatures(creatures)
    kill_creature(creatures)

if __name__ == "__main__":
    main()

解释

模块化功能:游戏的每个部分(初始化、显示生物、处理生物杀死过程)都封装在其函数中,使代码更干净、更易于管理。

数据字典:使用字典可以轻松存储和检索每个生物的所有相关信息,从而简化游戏的扩展。

错误处理和限制:游戏现在包含一个简单的错误处理机制,允许用户多次尝试做出有效选择。 这个修订版本不仅使代码更有组织性和健壮性,而且还为未来的扩展做好了结构准备,例如添加新生物或更复杂的游戏逻辑。

© www.soinside.com 2019 - 2024. All rights reserved.