Quick actions

cmd+k|ctrl+k

Navigation

Languages

Test2

Snippet info

Language

Python

Visibility

public

Author

victormakwaitat

Created

2024-10-31T12:59:05.409671Z

Updated

2024-10-31T12:59:10.15319Z

#   Name: Mak Wai Tat Victor , Student No. : 13

def print_board(board):
    for row in board:
        print(" | ".join(row))
        print("-" * 9)

def check_winner(board, player):
    # Check rows, columns, and diagonals
    for i in range(3):
        if all(board[i][j] == player for j in range(3)) or \
           all(board[j][i] == player for j in range(3)):
            return True
    if all(board[i][i] == player for i in range(3)) or \
       all(board[i][2-i] == player for i in range(3)):
        return True
    return False

def is_full(board):
    return all(cell != " " for row in board for cell in row)

def play_game():
    board = [[" " for _ in range(3)] for _ in range(3)]
    current_player = "X"
    # Adjusted mapping to match the desired input-output behavior
    moves = {
        "7": (0, 0), "8": (0, 1), "9": (0, 2),
        "4": (1, 0), "5": (1, 1), "6": (1, 2),
        "1": (2, 0), "2": (2, 1), "3": (2, 2)
    }

    while True:
        print_board(board)
        if current_player == "X":
            current_player = "B"
        elif current_player == "O":
            current_player = "A"
        move = input(f"Player {current_player}, enter a number (1-9): ")
        numcheck = move.isnumeric()
        if current_player == "A":
            current_player = "O"
        elif current_player == "B":
            current_player = "X"
        if numcheck == True:
            if move in moves:
                row, col = moves[move]
            if board[row][col] == " ":
                board[row][col] = current_player
                if check_winner(board, current_player):
                    print_board(board)
                    if current_player == "X":
                        current_player = "B"
                    elif current_player == "O":
                        current_player = "A"
                    print(f"Congratulations, The winner is player {current_player} wins!")
                    break
                elif is_full(board):
                    print_board(board)
                    print("It's a tie!")
                    break
                current_player = "O" if current_player == "X" else "X"
            else:
                print("Sorry, wrong move. Try again!")
        else:
            print("Please enter a number within the range!")




if __name__ == "__main__":
    username = 'Mak Wai Tat Victor, Student No. : 13'
    print('Student Name : {}'.format(username))
    play_game()
INFO