我得到了一个 2D 元组,它应该被视为 Connect4 游戏。 Mt 代码应该检测到第一个元组中对角有 4 个 X,第二个元组中水平有 4 个 O。我已经能够找到水平和垂直的 4 对,但我的代码无法检测对角线的。我需要知道我做错了什么
这是我的代码:
def check_winner(tuples):
result = None
#check for row win
for row in range(0,6):
for col in range(0,4):
if tuples[row][col] == tuples[row][col+1] == tuples[row][col+2] == tuples[row][col+3]=="O":
result = tuples[row][col];
elif tuples[row][col] == tuples[row][col+1] == tuples[row][col+2] == tuples[row][col+3]=="X":
result = tuples[row][col];
#check for column win
for col in range(0,7):
for row in range(0,3):
if tuples[row][col] == tuples[row+1][col] == tuples[row+2][col] == tuples[row+3][col]=="O":
result = tuples[row][col];
elif tuples[row][col] == tuples[row+1][col] == tuples[row+2][col] == tuples[row+3][col]=="X":
result = tuples[row][col];
#checks for diagonal win
for x in range(0,3):
for y in range(0,4):
if tuples[x][y] == tuples[x+1][y+1] == tuples[x+2][y+2] == tuples[x+3][y+3]=="O":
result = tuples[x][y];
if tuples[x][y] == tuples[x+1][y+1] == tuples[x+2][y+2] == tuples[x+3][y+3]=="X":
result = tuples[x][y];
return result
您的代码检查三个不同方向的胜利:水平、垂直和下降对角线 (
\
)。但也有上升的对角线需要检查(/
)。示例中的第二个输入在上升对角线上获胜,因此您的函数不会检测到它。
因此将此块添加到您的函数中:
# ascending diagonal check
for x in range(0,3):
for y in range(3,7): # allow for subtracting from y
if tuples[x][y] == tuples[x+1][y-1] == tuples[x+2][y-2] == tuples[x+3][y-3]=="O":
result = tuples[x][y];
if tuples[x][y] == tuples[x+1][y-1] == tuples[x+2][y-2] == tuples[x+3][y-3]=="X":
result = tuples[x][y];
您的函数一旦分配给 result
就可以
退出。当你已经找到胜利时,继续寻找胜利是没有任何好处的。
您的代码中有很多重复。例如,可以避免
=="O"
和=="X"
之间的区别。当找到 4 个相同的值时,无论是“O”、“X”还是 tuples[x][y]
,就得到 None
。如果是None
继续。如果没有,请退货。
但是您甚至可以参数化搜索方向并确定给定方向的起始单元格坐标范围。
例如:
def first_true(iterable, default=False, pred=None): # a recipe from the docs on itertools
return next(filter(pred, iterable), default)
def who_wins_at(tuples, row, col, dy, dx):
if (tuples[row][col] == tuples[row+dy][col+dx]
== tuples[row+dy*2][col+dx*2]
== tuples[row+dy*3][col+dx*3]):
return tuples[row][col]
def who_wins_direction(tuples, dy, dx):
return first_true(
who_wins_at(tuples, row, col, dy, dx)
for row in range([3, 0, 0][dy + 1], [6, 6, 3][dy + 1])
for col in range([3, 0, 0][dx + 1], [7, 7, 4][dx + 1])
)
def check_winner(tuples):
return first_true(
who_wins_direction(tuples, dy, dx)
for (dy, dx) in ((0, 1), (1, 0), (1, 1), (1, -1))
)