我正在研究一个学校项目,在python中创建Yahtzee(我对语言很新)我想知道它是否可行,如果是的话,如何在命令中出现一列文本显示每当他们决定在特定类别中得分时更新的玩家分数的行。这是我想要打印的内容:
print:('''
╔═══════════╗╔═══════════╗
║ Ones ║║ ║
╠═══════════╣╠═══════════╣
║ Twos ║║ ║
╠═══════════╣╠═══════════╣
║ Threes ║║ ║
╠═══════════╣╠═══════════╣
║ Fours ║║ ║
╠═══════════╣╠═══════════╣
║ Fives ║║ ║
╠═══════════╣╠═══════════╣
║ Sixes ║║ ║
╠═══════════╣╠═══════════╣
║ Total ║║ ║
╠═══════════╬╬═══════════╬
╠═══════════╬╬═══════════╬
║ Three of ║║ ║
║ a kind ║║ ║
╠═══════════╣╠═══════════╣
║ Four of ║║ ║
║ a kind ║║ ║
╠═══════════╣╠═══════════╣
║ Full House║║ ║
╠═══════════╣╠═══════════╣
║ Small ║║ ║
║ Straight ║║ ║
╠═══════════╣╠═══════════╣
║ Large ║║ ║
║ Straight ║║ ║
╠═══════════╣╠═══════════╣
║ Chance ║║ ║
╠═══════════╣╠═══════════╣
║ Yahtzee ║║ ║
╚═══════════╝╚═══════════╝
''')
我希望第二列可以复制并使用变量进行更新,具体取决于玩家的数量以及每个类别中的得分。任何想法都会有所帮助。
答案 0 :(得分:1)
您可以预定义框的固定长度,然后打印该值并计算带有差异的空格以保留您的结构,如下所示:
box_design_length = 10 # box design length to store character
ones = 2
twos = 55
threes = 4596
print('''
╔═══════════╗╔═══════════╗
║ Ones ║║ {0}{1}║
╠═══════════╣╠═══════════╣
║ Twos ║║ {2}{3}║
╠═══════════╣╠═══════════╣
║ Threes ║║ {4}{5}║
╚═══════════╝╚═══════════╝
'''.format(ones, ' '*(box_design_length-len(str(ones))),
twos, ' '*(box_design_length-len(str(twos))),
threes, ' '*(box_design_length-len(str(threes))),
)
)
format()
进行字符串格式化
{0}, {1}, {2}...
是format()
中传递的参数的数量,它支持2.6以上的所有python版本
输出:
╔═══════════╗╔═══════════╗
║ Ones ║║ 2 ║
╠═══════════╣╠═══════════╣
║ Twos ║║ 55 ║
╠═══════════╣╠═══════════╣
║ Threes ║║ 4596 ║
╚═══════════╝╚═══════════╝
如果您了解python formatting,可以采用更好的方式进行操作,如下所示:
from collections import OrderedDict
values = OrderedDict([('Ones', 2), ('twos', 55), ('threes', 4596)]) # store key, value in dictionary
# order dictionary is used to preserve order
def box_printer(value_set, box_design_length):
"""
print values in box
:param value_set: dictionary of key and value to print in box
:param box_design_length: length of box design
"""
count = 0 # initialize count: help to identify first loop or last loop to change box design accordingly
for key, value in value_set.items():
if count == 0: # first loop
print('╔{0}╗╔{0}╗'.format('═'*box_design_length))
count += 1
print('║ {1:^{0}}║║ {2:^{0}}║'.format(box_design_length-1, key, value))
if count >= len(value_set):
print('╚{0}╝╚{0}╝'.format('═'*box_design_length))
else:
print('╠{0}╣╠{0}╣'.format('═'*box_design_length))
box_printer(values, 11)
您将通过此代码获得您的愿望输出。
答案 1 :(得分:0)
如果您使用的是python 3.6,那么f-strings将是理想的选择。
t = 3
text = (f'''
╔═══════════╗╔═══════════╗
║ Ones ║║ {t} ║
╠═══════════╣╠═══════════╣
║ Twos ║║ ║
╠═══════════╣╠═══════════╣
''')
print(text)
使用花括号添加t变量,并在使用文本变量时进行转换。