您好我需要画一个动态宽度和高度的游戏板:
格式:
---- ---- ----
| 01 | 02 | 03 |
---- ---- ----
| 04 | 05 | 06 |
---- ---- ----
| 07 | 08 | 09 |
---- ---- ----
Enter width and height (min = 2x2, max 6x8):
这就是我现在所拥有的:
def board_draw(height, width):
for x in range(height):
print(" --- " * width)
print("| |" * width)
print(" --- " * width)
heightinp= int(input("Enter the height of the board: "))
widthinp= int(input("Enter the width of the board: "))
board_draw(heightinp,widthinp)
有人可以帮我打印数字,但我无法让它工作......
答案 0 :(得分:4)
str.format()
是将数字插入这些字符串的不错选择。
str.join()
是加入很多字符串的不错选择。在您的情况下,我将在.join()
。
def board_draw(height, width):
for x in range(height):
print(" ---- " * width)
print("|" +
"|".join(' {:02d} '.format(x * width + y + 1)
for y in range(width)) +
"|")
print(" ---- " * width)
结果:
$ python3 x.py
Enter the height of the board: 3
Enter the width of the board: 4
---- ---- ---- ----
| 01 | 02 | 03 | 04 |
---- ---- ---- ----
| 05 | 06 | 07 | 08 |
---- ---- ---- ----
| 09 | 10 | 11 | 12 |
---- ---- ---- ----
只是为了好玩,这里有一个使用Unicode盒子绘图字符。 (注意:这是Python3语法)。
def board_draw(height, width):
top = "┌" + "┬".join(["─"*6]*width) + "┐\n"
bottom = "└" + "┴".join(["─"*6]*width) + "┘"
middle = "├" + "┼".join(["─"*6]*width) + "┤\n"
print(top +
middle.join(
"│" +
"│".join(' {:02d} '.format(x * width + y + 1)
for y in range(width)) +
"│\n"
for x in range(height)) +
bottom)
结果:
$ python3 x.py
Enter the height of the board: 4
Enter the width of the board: 3
┌──────┬──────┬──────┐
│ 01 │ 02 │ 03 │
├──────┼──────┼──────┤
│ 04 │ 05 │ 06 │
├──────┼──────┼──────┤
│ 07 │ 08 │ 09 │
├──────┼──────┼──────┤
│ 10 │ 11 │ 12 │
└──────┴──────┴──────┘
答案 1 :(得分:0)
打印数字会使您的网格变得更加复杂。您必须重写整个电路板绘图功能。
您基本上想要做的是:
这是您想要的一种可能的实现方式:
def board_draw(height, width):
square = 0
print(" --- " * width)
for x in range(height):
line = "| "
for i in range(0, width):
line += format(square, '02d') + " | "
square += 1
print(line)
print(" --- " * width)
heightinp= int(input("Enter the height of the board: "))
widthinp= int(input("Enter the width of the board: "))
board_draw(heightinp,widthinp)