[英]matching chips in Connect Four Printing the match function (python)
我有一個適當運行的Connect Four程序,但我想將match_in_direction()方法打印到屏幕上...我的代碼如下
class ConnectFour(object):
這初始化了董事會:
def __init__(self):
self.board = [[None for i in range(7)] for j in range(8)]
這得到了每個游戲點的位置:
def get_position(self, row, column):
assert row >= 0 and row < 6 and column >= 0 and column < 7
return self.board[row][column]
這應該檢查所播放的籌碼是否匹配:
def match_in_direction(self, row, column, step_row, step_col):
assert row >= 0 and row < 6 and column >= 0 and column < 7
assert step_row != 0 or step_col != 0 # (0,0) gives an infinite loop
match = 1
while True:
nrow = row + step_row
ncolumn = column + step_col
if nrow >=0 and nrow <6 and ncolumn >=0 and ncolumn <7:
if self.board[row][column] == self.board[nrow][ncolumn]:
match == match+1
row = nrow
column = ncolumn
else:
return match
else:
return match
print match
這將是基於用戶輸入的游戲
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 xrange(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:
# This is impossible if the code is correct, should never occur.
s += " ! |"
print s
print "-" * 29
我的用法:
b = ConnectFour()
b.play_turn(1, 3)
b.play_turn(1, 3)
b.play_turn(1, 4)
b.match_in_direction(0,3,0,2)
b.print_board()
我當前的輸出給我的位置很好...但是它不打印match_in_direction(0,3,0,2)應該是2因為這是多少芯片匹配....任何幫助將是很大的贊賞。
從match_in_direction快速瀏覽一下,看起來你match == match+1
而不是match = match + 1
(或“更好”但match += 1
)
將此添加到您的測試代碼:
f = b.match_in_direction(0,3,0,2)
print(m)
因為返回語句,你不需要在match_in_direction函數中使用“print match”,並且print board不使用(缺少更好的單詞)方向函數中的匹配,因此你必須單獨打印出來。
你的match_in_direction函數的格式有點令人困惑,但我認為這是因為這里的拼寫錯誤:
if self.board[row][column] == self.board[nrow][ncolumn]:
match == match+1
它應該是
match += 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.