【问题标题】:Why is my code not printing an output of the dice diagram?为什么我的代码没有打印骰子图的输出?
【发布时间】:2022-08-18 15:25:34
【问题描述】:

在我的代码中,我已经插入了骰子的 ASCII 图。函数的第一部分,我创建了一个函数来生成 1-6 的随机数来刺激掷骰子。在我卡住的代码的第二部分,我应该根据我得到的骰子打印出骰子的图表,它必须水平打印而不是垂直打印。但是,当我尝试使用我创建的 for second for 循环打印图表时,它不起作用并且没有打印出来。output that i received 下面是我收到的指令。

import random


def roll_dice(num_of_dice=1):
    \"\"\"
    Rolls dice based on num_of_dice passed as an argument.

    Arguments:
      - num_of_dice: Integer for amount of dice to roll

    Returns the following tuple: (rolls, display_string)
      - rolls: A list of each roll result as an int
      - display_string: A string combining the dice art for all rolls into one string
    \"\"\"
    die_art = {
        1: [\"┌─────────┐\", \"│         │\", \"│    ●    │\", \"│         │\", \"└─────────┘\"],
        2: [\"┌─────────┐\", \"│  ●      │\", \"│         │\", \"│      ●  │\", \"└─────────┘\"],
        3: [\"┌─────────┐\", \"│  ●      │\", \"│    ●    │\", \"│      ●  │\", \"└─────────┘\"],
        4: [\"┌─────────┐\", \"│  ●   ●  │\", \"│         │\", \"│  ●   ●  │\", \"└─────────┘\"],
        5: [\"┌─────────┐\", \"│  ●   ●  │\", \"│    ●    │\", \"│  ●   ●  │\", \"└─────────┘\"],
        6: [\"┌─────────┐\", \"│  ●   ●  │\", \"│  ●   ●  │\", \"│  ●   ●  │\", \"└─────────┘\"]
    }

    rolls = []

    for i in range(num_of_dice):
        r = random.randint(1, 6)
        rolls.append(r)

    display_string = \"\"

    for roll in rolls:
        for line in die_art[roll]:
            if die_art[roll] == rolls:
                display_string.append(die_art[line])

    return(rolls, display_string)

result = roll_dice()
print(result[0])
print(result[1])
  • 欢迎来到堆栈溢出。请包括实际输出和预期输出。简要浏览一下您的代码后,为什么die_art[roll] == rolls 会是真的。您正在将字符串 (die_art[roll] 与列表 (rolls) 进行比较。
  • 嗨,谢谢!我已经包含了一个示例输出,但现在不包含实际输出。谢谢提醒
  • 我明白了,我试图将模具艺术的每一行添加到 display_string 变量中,但写错了。谢谢指出

标签: python random


【解决方案1】:

几个问题,主要是不确定你想用if die_art[roll] == rolls:实现什么...

这就是你想要的:

display_string = []

for roll in rolls:
    for line in die_art[roll]:
        display_string.append(line) # line is already what you want to print
display_string = "\n".join(display_string) # add new line breaks between lines

编辑:水平打印骰子:

display = []
for roll in rolls:
    display.append(die_art[roll])
display_string = '\n'.join((' '.join(line) for line in zip(*display)))

这只是取第一行并在它们之间用空格缝合它们,然后为每个模具重复第二、第三等行。最后像以前一样添加换行符。

【讨论】:

  • 天哪,就是这样! tysm 但是在尝试了代码之后,我意识到它垂直打印骰子图。有什么办法可以让它水平打印吗?
  • 当然,请参阅编辑。
  • tysm 的帮助。
猜你喜欢
  • 2021-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2013-08-20
  • 1970-01-01
相关资源
最近更新 更多