# L-32 MCS 260 Fri 1 Apr 2016 : movedot.py

"""
GUI for a random walk.
"""

from tkinter import Tk, Canvas, Label, Scale, Button
from tkinter import IntVar, W, E, N, S
from random import randint

class MovingDot(object):
    """
    GUI to illustrate an animation.
    """
    def __init__(self, wdw, size):
        """
        determines the layout of the GUI
        """
        wdw.title('a moving dot')
        self.dim = size
        self.cnv = Canvas(wdw, width=self.dim, \
            height=self.dim, bg='white')
        self.cnv.grid(row=0, column=0, columnspan=2)
        self.slp = Label(wdw, text="sleep time")
        self.slp.grid(row=1, column=0, columnspan=2)
        self.xpos = self.dim/2
        self.ypos = self.dim/2
        self.togo = False
        self.sleep = IntVar()
        self.step = IntVar()
        self.hsc = Scale(wdw, \
            orient='horizontal', from_=0, to=300, \
            tickinterval=50, resolution=1, \
            length=300, variable=self.sleep)
        self.hsc.grid(row=2, column=0, columnspan=2, \
            sticky=W+E+N+S)
        self.hsc.set(100)
        self.vsc = Scale(wdw, \
            orient='vertical', from_=0, to=100, \
            tickinterval=10, resolution=1, \
            length=400, variable=self.step)
        self.vsc.grid(row=0, column=2)
        self.vsc.set(10)
        self.bt0 = Button(wdw, text="start", \
            command=self.start)
        self.bt0.grid(row=3, column=0, sticky=W+E)
        self.bt1 = Button(wdw, text="stop", \
            command=self.stop)
        self.bt1.grid(row=3, column=1, sticky=W+E)

    def animate(self):
        """
        performs the animation
        """
        vxp = self.xpos
        vyp = self.ypos
        while self.togo:
            self.cnv.delete("dot")
            self.cnv.create_oval(vxp-6, vyp-6, vxp+6, vyp+6, width=1, \
                outline='black', fill='SkyBlue2', tags="dot")
            stp = self.step.get()
            vxp = vxp + randint(-stp, stp)
            vyp = vyp + randint(-stp, stp)
            if vxp >= self.dim:
                vxp = vxp - self.dim
            if vyp >= self.dim:
                vyp = vyp - self.dim
            if vxp < 0:
                vxp = vxp + self.dim
            if vyp < 0:
                vyp = vyp + self.dim
            self.cnv.after(self.sleep.get())
            self.cnv.update()

    def start(self):
        """
        starts the animation
        """
        self.togo = True
        self.animate()

    def stop(self):
        """
        stops the animation
        """
        self.togo = False

def main():
    """
    Instantiates the GUI and
    lauches the event loop.
    """
    top = Tk()
    MovingDot(top, 300)
    top.mainloop()

if __name__ == "__main__":
    main()
