gpt4 book ai didi

python - 尝试通过将行添加到单个多行字符串中来逐行打印显示

转载 作者:太空宇宙 更新时间:2023-11-03 17:48:17 25 4
gpt4 key购买 nike

我正在尝试打印一系列骰子,显示如下:

   ___     ___     ___     ___     ___
|* | |* | |* *| |* | | |
| | | * | |* *| | * | | * |
| *| | *| |* *| | *| | |
^^^ ^^^ ^^^ ^^^ ^^^

这些骰子应该代表我“掷骰子”时产生的数字。我创建了一个 Die 类和一个 Hand 类,它们在下面生成。

import random

class Die():

def __init__(self):
self.value = random.randint(1,6)

def roll(self):
self.value = random.randint(1,6)

'''def __str__(self):
return str(self.value)'''
<小时/>
import Die


class Hand:
def __init__(self):
self.L=[]
for i in range(5):
self.L.append(Die.Die()) #makes the number of dice



def __str__(self):
"""converts hand to a string for printing"""
return "{0},{1},{2},{3},{4}".format(self.L[0], self.L[1], self.L[2], self.L[3], self.L[4])

def roll(self, keep):
for i in range(5):
if i+1 not in keep:
self.L[i].roll()

上面给出的代码将在主文件进入时生成一个数字列表

h = hand.Hand()
h.roll() #this rolls the hand again
print(h)

有什么想法可以让我的结果以提供的显示样式打印吗?有人建议最好的方法是打印三行来构建所有 5 个骰子。最近的建议是“你必须逐行构建骰子的整个显示,然后将行添加在一起在单个多行字符串中。”我只是不确定如何执行它。

最佳答案

这是一种方法:

DIE_PARTS = [
['___'] * 6,
[' ', '* ', '* ', '* *', '* *', '* *'],
[' * ', ' ', ' * ', ' ', ' * ', '* *'],
[' ', ' *', ' *', '* *', '* *', '* *'],
['^^^'] * 6,
]

DIE_SPACING = ' ' * 3


def print_hand(dies):
# Build line parts
lines = [[],[],[],[],[]]
for i,line in enumerate(lines):
for d in dies:
if i in [1,2,3]: edge = '|'
else: edge = ' '
part = ''
part += edge # Leading edge of die
part += DIE_PARTS[i][d-1] # "pips"
part += edge # Trailing edge of die
line.append(part)

# Join lines
lines = [DIE_SPACING.join(l) for l in lines]

# Print lines
for l in lines: print(l)


print_hand([1,2,3,4,5,6])

输出:

 ___     ___     ___     ___     ___     ___ |   |   |*  |   |*  |   |* *|   |* *|   |* *|| * |   |   |   | * |   |   |   | * |   |* *||   |   |  *|   |  *|   |* *|   |* *|   |* *| ^^^     ^^^     ^^^     ^^^     ^^^     ^^^ 

If it's not clear, you're building each line of the 5 line output, line by line, then die for die.

So it goes something like

line 1 - die 1, line 1 - die 2, line 1 - die 3, ... 
line 2 - die 1, line 2 - die 2, line 2 - die 3, ...
...
line 5 - die 1, line 5 - die 2, line 5 - die 3, ...

然后它使用 DIE_SPACING 作为分隔符连接行列表的各个部分。

我将把它集成到你的其余代码中,由你决定。

关于python - 尝试通过将行添加到单个多行字符串中来逐行打印显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452281/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com