这利用了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 |
└───────┘