Рубрики
Без рубрики

Крестики-нолики

## 3 пользователь-перемещение по одной и той же строке или столбцу ## 3 пользовательских перемещений на диагонали (I) Def Проверьте _… Теги с Python.

## 3 user-moves on either the same row or column
## 3 user-moves on the diagonal (i == j)

def check_winner(moves):
    rows = {}
    cols = {}
    same_diagonal_count = 0

    is_winner = False

    # Elements of rows
    for move in moves:
        i, j = move
        if i in rows:
            rows[i] += 1
        else:
            rows[i] = 1

        if j in cols:
            cols[j] +=1
        else:
            cols[j] = 1

        if i == j:
            same_diagonal_count +=1


    if (same_diagonal_count >= 3):
        return True

    for col in cols:
        if cols[col] >= 3:
            return True

    for row in rows:
        if rows[row] >= 3:
            return True


    return is_winner


# Check move validity
def is_valid_move(mat,move):
    i,j = move
    return mat[i][j] == 'O'


def tictact_toe():
    mat = [
        ['O','O','O'],
        ['O','O','O'],
        ['O','O','O']
    ]

    total_moves  = len(mat) ** 2
    user_moves = {}

    while total_moves:
        user = input('Enter username: ')
        moves = input("Enter comma separated point (x, y)")

        i, j = moves.split(',')
        i = int(i)
        j = int(j)

        # Check if the move is not occupied
        if is_valid_move(mat,[i,j]):
            if user in user_moves:
                user_moves[f"{user}"].append([i,j])
            else:
                print(user_moves)
                user_moves[user] = [[i,j]]

            mat[i][i] = user
            total_moves -= 1
            # Check winner
            winner = check_winner(user_moves[user])

        else:
            print(f"Sory {user}, someone has played in this position. try again")



        if(winner):
            return f"Congratulations {user}, you are the winner" 

    print(mat)

Оригинал: “https://dev.to/mwibutsa/tic-tac-toe-27ce”