我一直在从事动态井字游戏 当检查行和列时,我遇到了一个问题。
我所有桌子的拳头看起来像
size? : 4 #input
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Player 1 plays :
我正在检查X或O的列是否已满
def column_check():
col_winner = None
cx = []
co = []
for i in range(1):
for j in range(0, game_size ** 2, game_size):
if matrix[j] == player1:
cx.append(j)
elif matrix[j] == player2:
co.append(j)
if len(cx) == game_size:
col_winner = player1
elif len(co) == game_size:
col_winner = player2
return col_winner
我为我工作得很好 但是我无法为行检查设置for循环。 我尝试了此代码块;
def row_check():
row_winner = None
rx = []
ro = []
for i in range(game_size):
for j in range(i * game_size, i * game_size + game_size):
if matrix[j] == player1:
rx.append(j)
elif matrix[j] == player2:
ro.append(j)
if len(rx) == game_size:
row_winner = player1
elif len(ro) == game_size:
row_winner = player2
return row_winner
但是它检查矩阵中的所有数字。它应该逐行检查。 我该怎么办?
答案 0 :(得分:0)
我假设您已绑定到column_check()中使用的结构,并且game_zize为4时,您需要连续4个; game_size = 3时为3。 我的解决方案是这样的:
def row_check():
row_winner = ""
for i in range(game_size):
ro = []
rx = []
for j in range(i * game_size, i * game_size + game_size):
if matrix[j]==player1:
rx.append(j)
elif matrix[j] == player2:
ro.append(j)
if rx == range(i*game_size, i*game_size+game_size):
row_winner = player1
elif ro == range(i * game_size, i * game_size + game_size):
row_winner = player2
return row_winner
答案 1 :(得分:0)
我写了这样的代码块,它工作得很好。 比我想的要简单。
def row_check():
row_winner = None
for i in range(game_size):
if matrix[i * game_size:i * game_size + game_size].count(player1) == game_size:
row_winner = player1
elif matrix[i * game_size:i * game_size + game_size].count(player2) == game_size:
row_winner = player2
return row_winner