我试图找出一个 for 循环和 if 语句,它将检查 tic tac toe 游戏是否在 python 中获胜。我需要这个,因为我有一个 connect 4 游戏并且我打算使用相同的伪代码。
这是我到目前为止所拥有的:
col_size = 3
row_size = 3
ttt = list()
for n in range(col_size):
rows = input(msg[n]+ ":")
ttt.append(rows)
print(ttt)
row_ttt= list()
for i in range(row_size):
one_row = list()
for j in range(col_size):
one_row+= ttt[i][j]
row_ttt.append(one_row)
diagonal_ttt= list()
for j in range(col_size):
one_diagonal= ""
for i in range(row_size):
one_diagonal+= ttt[i][j+1:2]
diagonal_ttt.append(one_diagonal)
print(row_ttt)
valid_symbols = ['x','X','o','O','.']
for j in range(col_size):
for i in range(row_size):
if row_ttt[i][j]== row_ttt[i:i+1][j] == row_ttt[i:i+2][j]:
#print(row_ttt[i][j]) to check the element
#print(row_ttt[i:i+1][j]) to check element
#print(row_ttt[i:i+2][j]) to check element
valid = True
print("valid board - " + ttt[i][j] + " is the winner")
break
我在这里手动写了出来,但我想要一个更短的代码:
if ttt[0][0] == ttt[1][1] == ttt[2][2]:
print("valid board " + ttt[0][0] + " is the winner")
break
if ttt[0][2] == ttt[1][1] == ttt[2][0]:
print("valid board " + ttt[2][0] + " is the winner")
break
if ttt[0][0] == ttt[0][1] == ttt[0][2]:
print("valid board " + ttt[0][0] + " is the winner")
break
if ttt[1][0] == ttt[1][1] == ttt[1][2]:
print("valid board " + ttt[0][0] + " is the winner")
break
if ttt[2][0] == ttt[2][1] == ttt[2][2]:
print("valid board " + ttt[0][0] + " is the winner")
break
if ttt[0][0] == ttt[1][1] == ttt[2][2]:
print("valid board " + ttt[0][0] + " is the winner")
break
if ttt[0][0] == ttt[1][0] == ttt[2][0]:
print("valid board " + ttt[0][0] + " is the winner")
break
if ttt[0][1] == ttt[1][1] == ttt[2][1]:
print("valid board " + ttt[0][1] + " is the winner")
break
if ttt[0][2] == ttt[1][2] == ttt[2][2]:
print("valid board " + ttt[0][2] + " is the winner")
break