繁体   English   中英

如何并排放置两个或多个 ASCII 图像?

[英]How do I place two or more ASCII images side by side?

我想建立一系列的纸牌游戏。 这个想法是将卡片的 ASCII 图像放入字典值中,以便在需要时调用。 但是,无论我使用哪种方法,我都无法弄清楚如何让卡片并排打印。

我尝试使用for循环、 join和修改print函数来解决这个问题。 每次输出产生:

.-------.
|A      |
|       |
|   ♣   |
|       |
|      A|
`-------´

.-------.
|2      |
|       |
|   ♦   |
|       |
|      2|
`-------´

代替:

.-------.  .-------.
|A      |  |2      |
|       |  |       |
|   ♣   |  |   ♦   |
|       |  |       |
|      A|  |      2|
`-------´  `-------´

我认为问题与光标停留在图像底部而不是返回图像顶部有关。 我花了几个小时寻找这方面的信息,但没有产生任何结果。

以下是字典中的两个示例变量:

ace = r'''
.-------.
|A      |
|       |
|   ♣   |
|       |
|      A|
`-------´
'''

two = r'''
.-------.
|2      |
|       |
|   ♦   |
|       |
|      2|
`-------´
'''
cards = {"Ace":ace, "Two":two}

# modify the print
print(f'{cards["Ace"]} {cards["Two"]}', end=' ')

# using join
space = " "
deck = space.join(cards.values())
print(deck)

# placing the dictionary entries into a list
cards2 = [cards["Ace"], cards["Two"]]
for item in cards2:
    print (item)

您可以将两张卡片的行zip()放在一起,并在每行上打印每张卡片中的一张:

ace = r'''\
.-------.
|A      |
|       |
|   ♣   |
|       |
|      A|
`-------´
'''

two = r'''\
.-------.
|2      |
|   ♦   |
|       |
|   ♦   |
|      2|
`-------´
'''

spacer = ' ' * 5  # Space between cards.
for a, b in zip(ace.splitlines(), two.splitlines()):
    print(f'{a}{spacer}{b}')

输出:

.-------.     .-------.
|A      |     |2      |
|       |     |   ♦   |
|   ♣   |     |       |
|       |     |   ♦   |
|      A|     |      2|
`-------´     `-------´

更新:

这是两张或更多卡的通用版本:

ace = r'''\
.-------.
|A      |
|       |
|   ♣   |
|       |
|      A|
`-------´
'''

two = r'''\
.-------.
|2      |
|   ♦   |
|       |
|   ♦   |
|      2|
`-------´
'''

three = r'''\
.-------.
|3      |
|   ♥   |
|   ♥   |
|   ♥   |
|      3|
`-------´
r'''

spacing = ' ' * 5  # Between cards.
cards = ace, two, three

for pieces in zip(*(card.splitlines() for card in cards)):
    print(spacing.join(pieces))

输出:

.-------.     .-------.     .-------.
|A      |     |2      |     |3      |
|       |     |   ♦   |     |   ♥   |
|   ♣   |     |       |     |   ♥   |
|       |     |   ♦   |     |   ♥   |
|      A|     |      2|     |      3|
`-------´     `-------´     `-------´

如果要对齐它们,则必须按文本行而不是按卡片打印(因此,检索代表每张卡片的第一行文本,打印第一行,依此类推)。

下面的代码就是一个例子,假设所有卡片都由相同数量的文本行表示:

def print_cards(card_dict, sep="\t"):
    card_lines = [card.split("\n") for card in card_dict.values()]
    for line_num in range(len(lines[0])):
        for card_line in lines: 
            print(card_line[line_num], end="")
            print(sep, end="")
        print()

结果如预期:

>>> print_cards(cards)  
.-------.   .-------.   
|A      |   |2      |   
|       |   |       |   
|   ♣   |   |   ♦   |   
|       |   |       |   
|      A|   |      2|   
`-------´   `-------´   

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM