我在python中有此代码,该代码通过输入(r)而不是水平地垂直打印每个骰子。有人知道如何编辑此代码以水平打印3个骰子吗?
import random
x = "r"
while x == "r":
no = random.randint(1,6)
if no == 1:
print("[-----]")
print("[ ]")
print("[ 0 ]")
print("[ ]")
print("[-----]")
if no == 2:
print("[-----]")
print("[ 0 ]")
print("[ ]")
print("[ 0 ]")
print("[-----]")
if no == 3:
print("[-----]")
print("[ ]")
print("[0 0 0]")
print("[ ]")
print("[-----]")
if no == 4:
print("[-----]")
print("[0 0]")
print("[ ]")
print("[0 0]")
print("[-----]")
if no == 5:
print("[-----]")
print("[0 0]")
print("[ 0 ]")
print("[0 0]")
print("[-----]")
if no == 6:
print("[-----]")
print("[0 0 0]")
print("[ ]")
print("[0 0 0]")
print("[-----]")
x=input("press r to roll again or e to exit:")
print("\n")
答案 0 :(得分:2)
您可以使用列表存储骰子字符串。追加到每个骰子骰子的字符串上。
这将为每卷连续打印骰子:
import random
def drawdice(nums):
rows = [] # all dice
for no in nums:
if no == 1:
rows.append(
"[-----]"
"[ ]"
"[ 0 ]"
"[ ]"
"[-----]")
if no == 2:
rows.append(
"[-----]"
"[ 0 ]"
"[ ]"
"[ 0 ]"
"[-----]")
if no == 3:
rows.append(
"[-----]"
"[ ]"
"[0 0 0]"
"[ ]"
"[-----]")
if no == 4:
rows.append(
"[-----]"
"[0 0]"
"[ ]"
"[0 0]"
"[-----]")
if no == 5:
rows.append(
"[-----]"
"[0 0]"
"[ 0 ]"
"[0 0]"
"[-----]")
if no == 6:
rows.append(
"[-----]"
"[0 0 0]"
"[ ]"
"[0 0 0]"
"[-----]")
for rx in range(5): # each row in dice
for ry in rows:
print(ry[rx*7:(rx+1)*7], end=' ') # each dice
print() # next row
print()
x = 'r'
while x != 'e':
rolls = [random.randint(1,6) for n in range(3)] # 3 dice
drawdice(rolls)
print("")
x=input("press enter to roll again or e to exit: ")
print("")
输出
[-----] [-----] [-----]
[ ] [0 0] [ ]
[ 0 ] [ 0 ] [0 0 0]
[ ] [0 0] [ ]
[-----] [-----] [-----]
press enter to roll again or e to exit:
[-----] [-----] [-----]
[ ] [ 0 ] [ ]
[0 0 0] [ ] [0 0 0]
[ ] [ 0 ] [ ]
[-----] [-----] [-----]
press enter to roll again or e to exit:
[-----] [-----] [-----]
[0 0 0] [0 0] [0 0]
[ ] [ ] [ ]
[0 0 0] [0 0] [0 0]
[-----] [-----] [-----]
为完整起见,您还可以将骰子字符串包装在列表中以进行显示
def drawdice(nums):
dice = [
["[-----]","[-----]","[-----]","[-----]","[-----]","[-----]"],
["[ ]","[ 0 ]","[ ]","[0 0]","[0 0]","[0 0 0]"],
["[ 0 ]","[ ]","[0 0 0]","[ ]","[ 0 ]","[ ]"],
["[ ]","[ 0 ]","[ ]","[0 0]","[0 0]","[0 0 0]"],
["[-----]","[-----]","[-----]","[-----]","[-----]","[-----]"]
]
for rx in dice: # each row in dice
for no in nums:
print(rx[no-1], end=' ')
print()
输出相同