# Allison Obourn
# CSC 110, Spring 2018
# Lecture 32

# reads mountain elevation data in a file
# where elevation is represesnted by numbers
# the first line is the northern most data
# the second, just south of that, etc
# Outputs a black and white elevation map of the
# data and draws a red spot on the heighest point.

from DrawingPanel import *
import random

def main():
    data = read_data()
    peak = find_peak(data)
    path_list = path(data, peak)
    draw(data, peak, path_list)

# takes a list of lists as a parameter
# returns the x, y location as a tuple of the location
# in the list of lists that contains the heighest number
def find_peak(data):
    max_x = 0
    max_y = 0
    for i in range(len(data)):
        for j in range(len(data[i])):
            current_x = j
            current_y = i
            if data[current_y][current_x] > data[max_y][max_x]:
                max_x = current_x
                max_y = current_y
    return (max_x, max_y)


def path(data, peak):
    path_list = []
    x = peak[0]
    y = peak[1]
    while x < len(data[0]) - 1:
        current = data[y][x]
        front = data[y][x + 1]
        top = data[y - 1][x + 1]
        bottom = data[y + 1][x + 1]
        front_diff = abs(current - front)
        top_diff = abs(current  - top)
        bottom_diff = abs(current - bottom)
        if front_diff <= top_diff and front_diff <= bottom_diff:
            x = x + 1
        elif top_diff < bottom_diff:
            x = x + 1
            y = y - 1
        elif bottom_diff < top_diff:
            x = x + 1
            y = y + 1
        else:
            r = random.randint(0, 1)
            if r == 0:
                x = x + 1
                y = y - 1
            else:
                x = x + 1
                y = y + 1
        path_list.append((x, y))
    return path_list
    

# takes a list of lists and a tuple as a parameter
# draws each number in the list of lists as a one pixel
# dot on a DrawingPanel using its value for the rgb color values
# draws a red dot at the location of the passed in x, y tuple
def draw(data, peak, path_list):
    panel = DrawingPanel(len(data[0]), len(data))
    for i in range(len(data)):
        for j in range(len(data[i])):
            n = data[i][j]
            hue = (n, n, n)
            panel.fill_rect(j, i, 1, 1, hue)

    panel.fill_oval(peak[0], peak[1], 6, 6, "red")

    for i in range(len(path_list)):
        x = path_list[i][0]
        y = path_list[i][1]
        panel.fill_oval(x,y, 4, 4, "yellow")


# reads data from a file into a list of lists.
# converts all data to integers
# returns this list of lists
def read_data():
    file = open("mountains.dat")
    data = file.readlines()
    for i in range(len(data)):
        data[i] = data[i].split()
        for j in range(len(data[i])):
            data[i][j] = int(data[i][j])
    return data

main()
