# L-31 MCS 260 Wed 30 Mar 2016 : arrowkeys.py
"""
Binding the arrow keys to canvas, we move a dot.
"""

from tkinter import Tk, Canvas

class KeyShow(object):
    """
    The GUI consists of a canvas and the arrow keys
    which allows the user to move a red dot.
    """
    def __init__(self, wdw, r, c):
        """
        Sets up the layout of the GUI.
        """
        wdw.title("binding arrow keys")
        self.cnv = Canvas(wdw, width=c, height=r)
        self.cnv.grid(row=0, column=0)
        self.cnv.bind("<Any-KeyPress>", self.move)
        self.rows = r
        self.cols = c
        self.pos = [self.cols/2, self.rows/2]
        self.draw_dot()

    def draw_dot(self):
        """
        Draws a dot at the location self.pos.
        """
        self.cnv.delete('dot')
        [xpd, ypd] = self.pos
        self.cnv.create_oval(xpd-6, ypd-6, xpd+6, ypd+6, \
            fill='red', tags='dot')

    def move(self, event):
        """
        Moves the dot in the direction of the arrow key.
        The canvas is organized as a torus.
        """
        if event.keysym == 'Left':
            self.pos[0] = self.pos[0] - 6
            if self.pos[0] < 0:
                self.pos[0] = self.cols - self.pos[0]
        if event.keysym == 'Right':
            self.pos[0] = self.pos[0] + 6
            if self.pos[0] > self.cols:
                self.pos[0] = self.pos[0] - self.cols
        if event.keysym == 'Up':
            self.pos[1] = self.pos[1] - 6
            if self.pos[1] < 0:
                self.pos[1] = self.rows - self.pos[1]
        if event.keysym == 'Down':
            self.pos[1] = self.pos[1] + 6
            if self.pos[1] > self.rows:
                self.pos[1] = self.pos[1] - self.rows
        self.draw_dot()

def main():
    """
    Puts up the canvas and then listens for keys.
    """
    top = Tk()
    print('press tab after clicking on window,')
    print('then use arrow keys to move red dot')
    KeyShow(top, 200, 300)
    top.mainloop()

if __name__ == "__main__":
    main()
