我是新手,我不知道如何检查某人是否赢得了我的井字棋游戏。有些代码是西班牙语的,如果你需要的话我可以翻译。
import random
Tablero = [[" ", "|", " ", "|", " "], ["^", "^", "^", "^", "^"], [" ", "|", " ", "|", " "],
["^", "^", "^", "^", "^"], [" ", "|", " ", "|", " "]]
turnoAI = False
Relacion_Columnas = {1:-1, 2:0, 3:1}
Finish = False
Count = 0
def DibujarTablero():
for i in range(len(Tablero)):
for j in range(len(Tablero[i])):
print(Tablero[i][j], end="")
else:
print("")
def TurnoJugador():
turnoAI = False
columna = int(input("Elige la columna: "))
fila = int(input("Elige la fila: "))
DibujarCasilla(columna, fila, "X", turnoAI)
def TurnoAI():
turnoAI = True
print("Turno de la IA")
fila = random.randint(1, 3)
columna = random.randint(1, 3)
DibujarCasilla(columna, fila, "O", turnoAI)
def DibujarCasilla(columna, fila, char, turnoAI):
if 0 < columna < 4 and 0 < fila < 4:
columna_real = columna + Relacion_Columnas[columna]
fila_real = fila + Relacion_Columnas[fila]
else:
print("Casilla no disponible, escoge otra")
TurnoJugador()
if Tablero[fila_real][columna_real] == " ":
Tablero[fila_real][columna_real] = char
DibujarTablero()
Finish = CheckWin(columna_real, fila_real)
else:
if turnoAI:
TurnoAI()
else:
print("Casilla no disponible, escoge otra")
TurnoJugador()
def CheckWin(columna, fila):
for i in range(0, 5, 2):
try:
if str(Tablero[columna +i][fila]) == str(Tablero[columna - 2 + i][fila]) and str(Tablero[columna - 2 + i][fila]) == str(Tablero[columna - 4 + i][fila]):
print(i)
print(fila)
print("Finish")
return True
except:
continue
DibujarTablero()
while not Finish:
TurnoJugador()
TurnoAI()
“完成”在不应该打印的时候被打印,而在应该打印的时候却没有打印。我不知道如何以更好的方式做到这一点。
您的
CheckWin
函数存在几个问题:
说实话,你自己也可以发现这一点。一个像样的调试器可以帮助您在单步执行代码、设置断点和检查变量时发现此类错误。
一个不相关的错误是您设置
finish
的方式。这是一个全局名称,因此您应该在函数中声明您将使用该全局名称:
global finish
我没有检查更多,因为这些问题只是意味着你必须完全重写
CheckWin
函数。建议:不要试图找到相对于最后一步的获胜线。相反,只需检查所有 6 条可能的线(3 条水平线、3 条垂直线、2 条对角线)。
这里是一个答案,其中包含用于检查 3x3 棋盘中获胜者的代码。