我已经为游戏连接 4 制作了一个初始化的棋盘,我现在想跟踪每个回合的位置和游戏,这样如果我这样做:
b = ConnectFour()
b.play_turn(1, 3)
b.play_turn(1, 3)
b.play_turn(1, 4)
b.print_board()
该板应打印出:
-----------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
-----------------------------
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | x | | | |
| | | | x | x | | |
-----------------------------
更新:
#initializes board
class ConnectFour(object):
def __init__(self):
self.board = [[0 for i in range(7)] for j in range(8)]
def get_position(self, row, column):
""" Returns either None or an integer 1 or 2 depending
on which player is occupying the given row or column.
Row is an integer between 0 and 5 and column is an integer between 0 and 6. """
assert row >= 0 and row < 6 and column >= 0 and column < 7
return self.board[row][column]
def play_turn(self, player, column):
""" Updates the board so that player plays in the given column.
player: either 1 or 2
column: an integer between 0 and 6
"""
assert player == 1 or player == 2
assert column >= 0 and column < 7
for row in range(6):
if self.board[row][column] == None:
self.board[row][column] = player
return
def print_board(self):
print "-" * 29
print "| 0 | 1 | 2 | 3 | 4 | 5 | 6 |"
print "-" * 29
for row in range(5,-1,-1):
s = "|"
for col in range(7):
p = self.get_position(row, col)
if p == None:
s += " |"
elif p == 1:
s += " x |"
elif p == 2:
s += " o |"
else:
s += " ! |"
print s
print "-" * 29
解决:
这是当前输出:
-----------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
-----------------------------
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | | | | |
| | | | x | | | |
| | | | x | x | | |
-----------------------------