[英]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.