"""Tony's Exit. Python 3."""

MAP = [
    "S..#..",
    "##.#..",
    "...T..",
    ".####.",
    ".....E",
]

DIRECTIONS = {
    "N": (0, -1),
    "E": (1, 0),
    "S": (0, 1),
    "W": (-1, 0),
}


def check_route(route):
    x = 0
    y = 0
    found_tony = False

    for step in route:
        if step not in DIRECTIONS:
            return "Use only N, E, S and W."

        dx, dy = DIRECTIONS[step]
        new_x = x + dx
        new_y = y + dy

        if new_y < 0 or new_y >= len(MAP):
            return "You reached the map edge."
        if new_x < 0 or new_x >= len(MAP[new_y]):
            return "You reached the map edge."
        if MAP[new_y][new_x] == "#":
            return "A wall blocks that route."

        x = new_x
        y = new_y
        if MAP[y][x] == "T":
            found_tony = True

    if found_tony and MAP[y][x] == "E":
        return "Tony is safe. You reached the exit!"
    return "Find Tony, then finish at E."


def play():
    print("TONY'S EXIT")
    print("S=start T=Tony E=exit #=wall .=floor")
    for row in MAP:
        print(row)
    print("Plan a route with N E S W. q quits.")

    while True:
        route = input("Route: ").upper()
        route = route.replace(" ", "")
        if route == "Q":
            print("Your next attempt can wait.")
            return
        result = check_route(route)
        print(result)
        if result.startswith("Tony is safe"):
            return


if __name__ == "__main__":
    play()
