# Gulp Catch, part 1: a game is a loop
#
# Flip walks along the top. A pancake flies from wall to wall.
# Nobody can play yet: Gulp comes in part 2.
#
# To run: open this file in IDLE and press F5.
# Closing the window stops the loop with a red message.
# Part 4 shows how a game closes its window properly.
#
# Everything after a # is a note for people. Python skips it.

from tkinter import Tk, Canvas
import time

width = 480
height = 640


class Flip:
    def __init__(self, canvas):
        self.canvas = canvas
        self.x = 120
        self.speed = 2
        x = self.x
        self.parts = [
            canvas.create_line(x, 58, x, 40, width=3, fill="gray30"),
            canvas.create_oval(x - 6, 32, x + 6, 44, fill="orange red", outline=""),
            canvas.create_rectangle(x - 22, 58, x + 22, 90, fill="light sea green",
                                    outline="dark slate gray", width=2),
            canvas.create_oval(x - 13, 68, x - 5, 76, fill="black"),
            canvas.create_oval(x + 5, 68, x + 13, 76, fill="black"),
            canvas.create_rectangle(x - 28, 92, x + 28, 140, fill="light sea green",
                                    outline="dark slate gray", width=2),
            canvas.create_line(x + 28, 108, x + 50, 108, width=4, fill="gray30"),
            canvas.create_oval(x + 46, 100, x + 86, 114, fill="gray20", outline=""),
        ]

    def step(self):
        # Flip walks along the top and turns around at the walls.
        self.x = self.x + self.speed
        for part in self.parts:
            self.canvas.move(part, self.speed, 0)
        if self.x <= 40 or self.x >= width - 90:
            self.speed = -self.speed


class Pancake:
    def __init__(self, canvas, x, y):
        self.canvas = canvas
        self.x = x
        self.y = y
        self.speed_x = 5
        self.shape = canvas.create_oval(x - 20, y - 7, x + 20, y + 7,
                                        fill="goldenrod", outline="dark goldenrod", width=2)

    def step(self):
        # Bounce off the side walls: the same speed, the other way.
        if self.x + self.speed_x < 20 or self.x + self.speed_x > width - 20:
            self.speed_x = -self.speed_x
        self.x = self.x + self.speed_x
        self.canvas.move(self.shape, self.speed_x, 0)


class Game:
    def __init__(self):
        self.window = Tk()
        self.window.title("Gulp Catch")
        self.canvas = Canvas(self.window, width=width, height=height, bg="powder blue")
        self.canvas.pack()
        self.flip = Flip(self.canvas)
        self.pancake = Pancake(self.canvas, 240, 300)

    def step(self):
        self.flip.step()
        self.pancake.step()

    def run(self):
        # The game is this loop: move everything a little, show it, wait, again.
        while True:
            self.step()
            self.window.update()
            time.sleep(0.02)


game = Game()
game.run()
