好的,所以这就是我正在努力的乐趣和实践!
我正在为井字游戏或跳棋制作游戏板,我希望它在侧面编号,但我不能找到一些好的代码。我使用尽可能少的代码,因为我希望有人可以帮我解决这个小问题。
正在使用Python 2.7.8
Num = 1
def P1():
print(" ---" * game)
def P2():
if game >= 2:
Num+ 1
print(str(Num) + "| " * (game + 1))
game = int(raw_input("Game board size: "))
for i in range(game):
P1()
P2()
P1()
我希望摆脱这种情况如下所示。
1 2 3
--- --- ---
1| | | |
--- --- ---
--- --- ---
2| | | |
--- --- ---
--- --- ---
3| | | |
--- --- ---
我的代码结果如下:
Game board size: 3
--- --- ---
1| | | |
--- --- ---
--- --- ---
1| | | |
--- --- ---
--- --- ---
1| | | |
--- --- ---
答案 0 :(得分:3)
不包括顶部数字条
def P1():
print(" " + (" ---" * game))
def P2():
print(str(i+1) + ("| " * (game + 1)))
game = 3
P1()
for i in range(game):
P2()
P1()
答案 1 :(得分:2)
您使用刚刚需要的代码将您当前正在打印的行号传递给P2()
方法并且需要在顶部打印一行数字。这应该工作。
def P0(num):
for i in range(num-1):
print " " + str(i+1),
print(" " + str(num))
def P1():
print(" ---" * game)
def P2(i):
print(str(i+1) + "| " * (game + 1))
game = int(input("Game board size: "))
P0(game)
for i in range(game):
P1()
P2(i)
P1()
答案 2 :(得分:2)
我会把它留在这里,就像我的一些旧剧本中所见。
请注意,这远非完美;它会例如如果大小超过9则中断,因为它变为2个字符宽作为字符串然后...
from __future__ import print_function
def draw_board(size, state):
print(' |' + '|'.join(' {} '.format(x) for x in range(1, size + 1)) + '|')
for y in range(1, size + 1):
print('-+' + '---+' * size)
print('{}|'.format(y), end='')
for x in range(1, size + 1):
marker = ' '
if state[x - 1][y - 1] is not None:
marker = state[x - 1][y - 1]
print(' {} |'.format(marker), end='')
print()
print('-+' + '---+' * size)
print()
def put(x, y, marker, state):
if state[x][y] is None:
state[x][y] = marker
else:
raise Exception('Place already occupied.')
def check_winner(state):
pass
if __name__ == '__main__':
size = 3
state = [[None] * size for _ in range(size)]
draw_board(size, state)
put(1, 1, 'x', state)
draw_board(size, state)
put(0, 1, 'o', state)
draw_board(size, state)
此脚本如果按原样运行,将产生以下输出:
| 1 | 2 | 3 |
-+---+---+---+
1| | | |
-+---+---+---+
2| | | |
-+---+---+---+
3| | | |
-+---+---+---+
| 1 | 2 | 3 |
-+---+---+---+
1| | | |
-+---+---+---+
2| | x | |
-+---+---+---+
3| | | |
-+---+---+---+
| 1 | 2 | 3 |
-+---+---+---+
1| | | |
-+---+---+---+
2| o | x | |
-+---+---+---+
3| | | |
-+---+---+---+
其余部分留给你,OP;)