这利用了Windows控制台中的OEM代码页为控制字符打印一些可见字符.卡片适合cp437和cp850是chr(3)-chr(6). Python 3(3.6之前)不会打印一个黑色钻石的Unicode字符,但它是你为U 0004获得的:
>>> print('\N{BLACK DIAMOND SUIT}')
Traceback (most recent call last):
File "", line 1, in
File "C:\Python33\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2666' in position 0: character maps to
>>> print(chr(4))
♦
因此:
#!python3
#coding: utf8
class Card:
def __init__(self,value,suit):
self.value = value
self.suit = suit # 1,2,3,4 = ♥♦♣♠
def print(self):
print("┌───────┐")
print("| {:<2} |".format(self.value))
print("| |")
print("| {} |".format(chr(self.suit+2)))
print("| |")
print("| {:>2} |".format(self.value))
print("└───────┘")
输出:
>>> x=Card('K',4)
>>> x.print()
┌───────┐
| K |
| |
| ♠ |
| |
| K |
└───────┘
>>> x=Card(10,3)
>>> x.print()
┌───────┐
| 10 |
| |
| ♣ |
| |
| 10 |
└───────┘
Python 3.6更新
Python 3.6使用Windows Unicode API来打印,所以现在不需要控制字符,可以使用新的格式字符串:
#!python3.6
#coding: utf8
class Card:
def __init__(self,value,suit):
self.value = value
self.suit = '♥♦♣♠'[suit-1] # 1,2,3,4 = ♥♦♣♠
def print(self):
print('┌───────┐')
print(f'| {self.value:<2} |')
print('| |')
print(f'| {self.suit} |')
print('| |')
print(f'| {self.value:>2} |')
print('└───────┘')
输出:
>>> x=Card('10',3)
>>> x.print()
┌───────┐
| 10 |
| |
| ♣ |
| |
| 10 |
└───────┘
这篇博客探讨了如何在Python中利用控制字符和Unicode打印卡片图案,特别是在Windows控制台环境下。文章通过示例展示了在不同Python版本中如何处理字符编码问题,包括在Python3.6之前的版本中使用OEM代码页和控制字符,以及3.6之后版本中使用Unicode API的改进。同时,还提供了一个用于打印扑克牌卡牌的类,展示了如何在代码中实现卡片的可视化。
1万+

被折叠的 条评论
为什么被折叠?



