【问题标题】:Is there a cleaner way to write this code? D&D dice roller有没有更简洁的方法来编写这段代码? DnD骰子滚轮
【发布时间】:2019-06-12 19:17:22
【问题描述】:

我觉得它的代码非常直接且易于阅读,但我想知道是否有一种简单或更有效的方法来编写它。 这是我第一个项目的开始。

import random

command = "".lower()

def dice():
    while True:
        dice_entry = input(":> ").lower().strip()
        if dice_entry == "help":
            print("""
Valid commands include:
Coin, d4, d6, d8, d10, d12 or d20
in order to roll the corresponding dice
or flip a coin.

Type Quit to close program.""")

        elif dice_entry == "coin":
            print("".join(random.choices(['Heads', 'Tails'])))

        elif dice_entry == "d4":
            print(random.randint(1, 4))

        elif dice_entry == "d6":
            print(random.randint(1, 6))

        elif dice_entry == "d8":
            print(random.randint(1, 8))

        elif dice_entry == "d10":
            print(random.randint(1, 10))

        elif dice_entry == "d12":
            print(random.randint(1, 12))

        elif dice_entry == "d20":
            print(random.randint(1, 20))

        elif dice_entry == "quit":
            break
        else:
            print("Invalid command. Type \"Help\" for list of valid commands.")

【问题讨论】:

  • 您可以阅读该消息,检查是否符合您的格式“dXX”。如果是,删除 'd' 并将 remining 文本转换为 int,然后调用 'random.randint(1,xx)'。

标签: python python-3.x


【解决方案1】:

当然有:

变量命名:你的变量 dice_entry 有一个坏名字。您还可以投掷硬币、退出或键入与骰子无关的帮助。

使用random.choices :您可以改用random.choice 并避免使用"".join

WET : 一些代码被重复多次,你可以使用一个函数。

无用代码:命令变量的意义何在?特别是 "".lower() 的意义何在?为什么不只是""

import random

def throw_dice(nb_faces):
    return random.randint(1, nb_faces)

def throw_coin():
    return random.choice(['Heads', 'Tails'])

def main():
    while True:
        entry = input(":> ").lower().strip()

        if entry == "help":
            print("""
Valid commands include:
Coin, d4, d6, d8, d10, d12 or d20
in order to roll the corresponding dice
or flip a coin.

Type Quit to close program.""")

        elif entry == "coin":
            print(throw_coin())

        elif entry in ["d4", "d6", "d8", "d10", "d12", "d20"]:
            nb_faces = int(entry[1:])
            print(throw_dice(nb_faces))

        elif entry == "quit":
            break

        else:
            print('Invalid command. Type "Help" for list of valid commands.')

【讨论】:

    【解决方案2】:

    一种选择是使用寻址字典:

    import random
    
    def dice():
        help_message = (
            "Valid commands include:\n"
            "Coin, d4, d6, d8, d10, d12 or d20 in order to roll the corresponding dice or flip a coin.\n"
            "Type Quit to close program.\n"
        )
        commands_dict = {
            "help": lambda: help_message,
            "coin": lambda: random.choice(("Heads", "Tails")),
            "d4"  : lambda: random.randint(1,  4),
            "d8"  : lambda: random.randint(1,  8),
            "d10" : lambda: random.randint(1, 10),
            "d12" : lambda: random.randint(1, 12),
            "d20" : lambda: random.randint(1, 20)
        }
        default = lambda: "Invalid command. Type \"Help\" for list of valid commands."
        while True:
            dice_entry = input(":> ").lower().strip()
            if dice_entry == "quit":
                break
            print(commands_dict.get(dice_entry, default)())
    

    这里有live example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多