Python - 井字棋

Python - TicTacToe

在这个问题中,我必须在 python 中创建一个 TicTacToe 游戏,它将在终端中 运行 。这是一款 2 人游戏,如果任何玩家根据 TicTacToe 规则获胜,则必须打印获胜者 = 玩家 1/2。

当我在对角线上有三个 0 或 1 时,我得到了获胜者声明,但在其他两种情况下(水平和垂直)我没有获得胜利者

请帮忙找出我代码中的错误

import numpy as np

def create_board():
    return (np.array([[0, 0, 0],
                      [0, 0, 0],
                      [0, 0, 0]]))


def coordinates(board, player):
    i, j, cn = (-1, -1, 0)
    while (i > 3 or i < 0 or j < 0 or j > 3) or (board[i][j] != 0):
        if cn > 0:
            print("Wrong Input! Try Again")
        print("Player {}'s turn".format(player))
        i = int(input("x-coordinates: "))
        j = int(input("y-coordinates: "))
        i = i - 1
        j = j - 1
        cn = cn + 1
    board[i][j] = player
    return board


def row_win(board, player):
    for x in range(len(board)):
        win = True

        for y in range(len(board)):
            if board[x, y] != player:
                win = False
                continue
    return win


def col_win(board, player):
    for x in range(len(board)):
        win = True

        for y in range(len(board)):
            if board[y][x] != player:
                win = False
                continue

    return win


def diag_win(board, player):
    win = True
    y = 0
    for x in range(len(board)):
        if board[x][x] != player:
            win = False
    if win:
        return win
    win = True
    if win:
        for x in range(len(board)):
            y = len(board) - 1 - x
            if board[x][y] != player:
                win = False
    return win


def evaluate(board):
    winner = 0

    for player in [1, 2]:
        if (row_win(board, player) or
                col_win(board, player) or
                diag_win(board, player)):
            winner = player

    if np.all(board != 0) and winner == 0:
        winner = -1
    return winner


def play_game():
    board, winner, counter = create_board(), 0, 1
    print(board)
    while winner == 0:
        for player in [1, 2]:
            board = coordinates(board, player)
            print("Board after " + str(counter) + " move")
            print(board)
            counter += 1
            winner = evaluate(board)
            if winner != 0:
                break
    return winner

print("Winner is: " + str(play_game()))

假设这是董事会:

x x x 
o o x
x o o

你的 row_win 检查第一行,win 仍然是 True。 然后它继续检查第二行,win 设置为 False。在最后一行之后,该函数最终报告玩家没有赢,即使赢了。

要解决此问题,请将您的 row_wincol_win 更改为如下内容:

def row_win(board, player):
    for row in board:
        if all([cell == player for cell in row]):
            return True
    return False

如果一行中的所有单元格都等于玩家,则玩家获胜。 如果 none 行的所有单元格都等于玩家,则玩家未获胜。