【发布时间】:2018-07-20 20:05:02
【问题描述】:
所以我找到了一些格式化 2048 游戏板的代码,这样当一个数字超过 1 位时它看起来不会很乱:
nlist = [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 128, 2, 2, 16, 16]
widths = [max(len(str(nlist[row * 4 + col])) for row in range(4)) + 2 for col in range(4)]
width = sum(widths) + 5
count = 0
for i in range(16):
print('|{:^{width}}'.format(nlist[i], width=widths[i % 4]), end = '')
count += 1
if count == 4:
print("|\n" + '-' * width)
count = 0
print("")
运行此代码以使事情更清晰,并更改 nlist 的值以查看格式化的工作方式。所以无论如何,在我完成游戏后,我想添加颜色以使游戏在终端中更容易理解,所以我将代码编辑为如下所示:
clist = nlist.copy()
for x in range(16):
if clist[x] == 2:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 4:
clist[x] = ' \033[1;37;105m' + str(clist[x]) + '\033[0m '
if clist[x] == 8:
clist[x] = ' \033[1;37;104m' + str(clist[x]) + '\033[0m '
if clist[x] == 16:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 32:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 64:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 128:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 256:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 512:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 1024:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 2048:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
if clist[x] == 4096:
clist[x] = ' \033[1;37;106m' + str(clist[x]) + '\033[0m '
widths = [max(len(str(nlist[row * 4 + col])) for row in range(4)) + 2 for
col in range(4)]
width = sum(widths) + 5
count = 0
for i in range(16):
print('|{:^{width}}'.format(clist[i], width=widths[i % 4]), end = '')
count += 1
if count == 4:
print("|\n" + '-' * width)
count = 0
但是现在格式变得一团糟,我的电路板又一次看起来很丑。有没有一种可能的方法来改变这个代码,使它看起来像第一个代码,除了颜色(现在几乎所有的颜色都是一样的,因为时间的缘故。我稍后会改变它)。另外,有没有更简单的方法可以在条件语句中添加颜色?
编辑:
这是没有正确格式颜色的文件的链接:2048 that works(no colors)
这是颜色格式不正确的文件的链接:2048 that does not work(colors)
我运行代码的屏幕截图:Screen shot of messed up format
【问题讨论】:
-
添加(正确的)ANSI 转义序列不应该改变可见字符的数量。因此,您的计数必须关闭。这是我第一次在 Stack Overflow 上问这个问题:您可以添加彩色文本的屏幕截图吗?
-
我会在描述的整个代码中放一个链接
-
@J.Doe,已更新,希望对您有所帮助。
标签: python python-3.x colors