Example #1
0
class GUI(object):
    def __init__(self, world):
        self.ticks = 0
        self.world = world
        self.width = world.width
        self.height = world.height

        self.root = Tk()
        self.root.title("Mars Explorer")
        window_x, window_y = self._compute_window_coords()
        self.root.geometry('%dx%d+%d+%d' %
                           (self.width, self.height, window_x, window_y))

        self.canvas = Canvas(self.root, width=self.width, height=self.height)
        self.canvas.pack()
        self.canvas.after(1, self._tick)

    def start(self):
        self.root.mainloop()

    def _tick(self):
        # Stop if done.
        if self.world.is_done():
            return

        self.world.tick()
        self._draw()

        self.ticks += 1
        self.canvas.after(1, self._tick)

    def _draw(self):
        self.canvas.delete('all')

        self.world.draw(self.canvas)
        for entity in self.world.entities:
            entity.draw(self.canvas)

        self.canvas.create_text(self.width - 20, 10, text=str(self.ticks))
        self.canvas.create_text(self.width - 70,
                                30,
                                text='Rocks in explorers: %d' %
                                self.world.rocks_in_explorers())
        self.canvas.create_text(self.width - 70,
                                50,
                                text='Rocks delivered: %d' %
                                self.world.rocks_collected)
        self.canvas.create_text(self.width - 55,
                                70,
                                text='Total rocks: %d' % self.world.num_rocks)

    def _compute_window_coords(self):
        # http://stackoverflow.com/a/14912644/742501
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_x = screen_width / 2 - self.width / 2
        window_y = screen_height / 2 - self.height / 2
        return window_x, window_y
Example #2
0
class GUI(object):
    def __init__(self, world):
        self.ticks = 0
        self.world = world
        self.width = world.width
        self.height = world.height

        self.root = Tk()
        self.root.title("Mars Explorer")
        window_x, window_y = self._compute_window_coords()
        self.root.geometry('%dx%d+%d+%d' % (self.width, self.height,
                                            window_x, window_y))

        self.canvas = Canvas(self.root, width=self.width, height=self.height)
        self.canvas.pack()
        self.canvas.after(1, self._tick)

    def start(self):
        self.root.mainloop()

    def _tick(self):
        # Stop if done.
        if self.world.is_done():
            return

        self.world.tick()
        self._draw()

        self.ticks += 1
        self.canvas.after(1, self._tick)

    def _draw(self):
        self.canvas.delete('all')

        self.world.draw(self.canvas)
        for entity in self.world.entities:
            entity.draw(self.canvas)

        self.canvas.create_text(self.width - 20, 10, text=str(self.ticks))
        self.canvas.create_text(self.width - 70, 30,
                                text='Rocks in carriers: %d' % self.world.rocks_in_carriers())
        self.canvas.create_text(self.width - 70, 50, text='Rocks delivered: %d' % self.world.rocks_collected)
        self.canvas.create_text(self.width - 55, 70, text='Total rocks: %d' % self.world.num_rocks)

    def _compute_window_coords(self):
        # http://stackoverflow.com/a/14912644/742501
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_x = screen_width / 2 - self.width / 2
        window_y = screen_height / 2 - self.height / 2
        return window_x, window_y
Example #3
0
class Animation:
    def __init__(self):
        root = Tk()
        self.canvas = Canvas(root, height=500, width=500)
        self.canvas.pack()

        self.canvas.create_rectangle(0, 0, 500, 500, fill="#0D4566", outline="#0D4566")  # space
        self.venus = Planet(250, 150, self.canvas, "red")
        self.earth = Planet(250, 100, self.canvas, "green")
        self.sun = Planet(250, 250, self.canvas, "yellow")

        self.start = time.time()
        self.ticks = 0
        self.done = False
        self.timer()
        root.mainloop()

    def rotate_body(self, body, amount):
        theta = math.degrees(amount)

        x = body.x - 250
        y = body.y - 250

        x, y = x * math.cos(theta) - y * math.sin(theta), x * math.sin(theta) + y * math.cos(theta)

        x += 250
        y += 250

        body.move_to(x, y)

        self.canvas.update()

    def timer(self):
        if self.done:
            print "Done after %2.2f seconds!" % (time.time() - self.start)
            return
        self.rotate_body(self.earth, math.pi / 36000 * 13.0)
        self.rotate_body(self.venus, math.pi / 36000 * 8.0)

        self.ticks += 1
        if self.ticks % 2 == 0:
            self.canvas.create_line(self.earth.x, self.earth.y, self.venus.x, self.venus.y, fill="white")
        if self.ticks > 1250:
            self.done = True

        self.canvas.after(5, self.timer)
Example #4
0
class FrameTk(object):

    def __init__(self, height, width, box_size, title = "Tk", bg = None):
        self.BOX_SIZE = box_size

        self.main = Tk()
        self.main.wm_title(title)
        self.canvas = Canvas(self.main, height = height, width = width, bg = bg)
        self.canvas.pack()

    def run(self):
        self.main.mainloop()

    def repeat(self, end, timeMillis, callback):
        def _repeat(end, time, func):
            if self.sma.stop:
                return

            if end > 0:
                end -= 1
                self.repeat(end, time, func)
                func()
                self._draw()

        self.canvas.after(timeMillis, _repeat, end, timeMillis, callback)

    def after(self, timeMillis, callback):
        def _callback(time, func):
            if self.sma.stop:
                return

            self.after(time, func)
            func()
            self._draw()

        self.canvas.after(timeMillis, _callback, timeMillis, callback)

    def _draw(self):
        pass

    def drawTkImage(self, x, y, tkimage):
        self.canvas.create_image(x, y, anchor = NW, image = tkimage)

    def drawText(self, x, y, text, color = 'black', size = 8):
        self.canvas.create_text(x, y, anchor = NW, text = text, font = ('Arial', size), width = self.BOX_SIZE, fill = color)
Example #5
0
    yp = 0.7 * h - 0.7 * h * y / 100.0
    canvas.coords(ship, w / 4, yp)

    if y >= 0.0:
        canvas.after(1, tick)


root = Tk()
canvas = Canvas(root, width=w, height=h, bg='black')
canvas.pack()

img1 = Image.open('earthrise.jpg').resize((w, h))
pmg1 = ImageTk.PhotoImage(img1)
canvas.create_image(w / 2, h / 2, image=pmg1)

img2 = Image.open('eagle.jpg').resize((200, 200))
pmg2 = ImageTk.PhotoImage(img2)
ship = canvas.create_image(w / 4, 0, image=pmg2)

canvas.create_rectangle(w / 4 - 150,
                        int(0.5 + 0.7 * h) + 100,
                        w / 4 + 150,
                        int(0.5 + 0.7 * h) + 125,
                        outline='green',
                        fill='green')

print t, y, vy

canvas.after(1000, tick)
root.mainloop()
Example #6
0
class PhyUI():

    def callback_switcher(self):
        """ Callback function for switching status between 
            'freezed' and 'on going'. """

        play_ref = self.button_play
        if not self.locked :
            play_ref.config(text = "Play")
            self.locked = True
        else:
            play_ref.config(text = "Freeze")
            self.locked = False

    def keyevent_up_press(self, event):
        """ Callback for pressing up key. """
        self.mouse_lock = True
        self.selected_user_accel_factor[0] = 1

    def keyevent_up_release(self, event):
        """ Callback for releasing up key. """
        self.mouse_lock = False
        self.selected_user_accel_factor[0] = 0

    def keyevent_down_press(self, event):
        """ Callback for pressing down key. """
        self.mouse_lock = True
        self.selected_user_accel_factor[1] = 1

    def keyevent_down_release(self, event):
        """ Callback for releasing down key. """
        self.mouse_lock = False
        self.selected_user_accel_factor[1] = 0

    def keyevent_left_press(self, event):
        """ Callback for pressing left key. """
        self.mouse_lock = True
        self.selected_user_accel_factor[2] = 1

    def keyevent_left_release(self, event):
        """ Callback for releasing left key. """
        self.mouse_lock = False
        self.selected_user_accel_factor[2] = 0

    def keyevent_right_press(self, event):
        """ Callback for pressing right key """
        self.mouse_lock = True
        self.selected_user_accel_factor[3] = 1

    def keyevent_right_release(self, event):
        """ Callback for releasing right key """
        self.mouse_lock = False
        self.selected_user_accel_factor[3] = 0

    def __init__(self, root_handle, canvas_width, canvas_height):
        """ Setup the whole application."""

        self.locked = True  # True for freeze.
        self.mouse_lock = False # True for locking the mouse behavior.
        self.selected = None # What ball is selected now?
        self.selected_user_accel_factor = [0, 0, 0, 0] # Acceleration from user's keypress event
        self.selected_user_accel_val = [Vect2D(0, 15), 
                                        Vect2D(0, -5),
                                        Vect2D(-5, 0), 
                                        Vect2D(5, 0)] 

        self.circles = [] # Reference to all the balls.

        # Initialize the main variables for the application

        self.frm_main = Frame(root_handle)
        self.frm_side_top = LabelFrame(root_handle, 
                                        text = "Realtime Parameters:")
        self.frm_side_bot = Frame(root_handle)

        # Setup the frames

        self.canv_width = canvas_width
        self.canv_height = canvas_height
        self.canvas_base = Vect2D(0, self.canv_height)
        self.canvas = Canvas(
                self.frm_main, 
                width = self.canv_width, height = self.canv_height, 
                bg = "#cccccc")
        # Setup the canvas

        self.canvas.bind_all("<KeyPress-w>", self.keyevent_up_press)
        self.canvas.bind_all("<KeyRelease-w>", self.keyevent_up_release)
        self.canvas.bind_all("<KeyPress-a>", self.keyevent_left_press)
        self.canvas.bind_all("<KeyRelease-a>", self.keyevent_left_release)
        self.canvas.bind_all("<KeyPress-d>", self.keyevent_right_press)
        self.canvas.bind_all("<KeyRelease-d>", self.keyevent_right_release)
        self.canvas.bind_all("<KeyPress-s>", self.keyevent_down_press)
        self.canvas.bind_all("<KeyRelease-s>", self.keyevent_down_release)

        # Setup all keys
 
        self.button_play = Button(self.frm_side_bot, 
                                    text = "Play", 
                                    command = self.callback_switcher)
        self.button_add = Button(self.frm_side_bot, 
                                    text = "Exit", 
                                    command = root_handle.quit)

        # Setup all the buttons

        side_names = ["Mass", "Positioin", "Velocity", "Acceleration"]
        self.side_label = []
        self.side_entry = []
        for name in side_names:
            self.side_label.append(Label(self.frm_side_top, text = name + ":"))
            self.side_entry.append(Label(self.frm_side_top, width = 20))

        # Setup information area located on the sidebar

        self.frm_main.grid(row = 0, column = 0, rowspan = 2)
        self.frm_side_top.grid(row = 0, column = 1, sticky = "S")
        self.frm_side_bot.grid(row = 1, column = 1, sticky = "S")
        self.canvas.grid(row = 0, column = 0, columnspan = 2)
        self.button_play.grid(row = 1, column = 0, sticky = "E")
        self.button_add.grid(row = 1, column = 1, sticky = "W")
        for i in xrange(len(self.side_label)):
            self.side_label[i].grid(row = i, column = 0)
            self.side_entry[i].grid(row = i, column = 1)

        # Build up the layout

    def set_viewport(self, math_bl, math_tr):
        """ 
            Set the translation rate.
            You should call this before calling trans or rev_trans.
        """

        self.scale_factor = Vect2D(
                self.canv_width / float(math_tr.x - math_bl.x),
                -self.canv_height / float(math_tr.y - math_bl.y))

        self.math_base = math_bl

    def trans(self, pos):
        """ Translation (from math coord to canvas coord)."""

        return (pos - self.math_base).scale(self.scale_factor) + \
            self.canvas_base

    def rev_trans(self, pos):
        """ Reverse translation (from canvas coord to math coord)."""

        return (pos - self.canvas_base).rev_scale(self.scale_factor) + \
            self.math_base

    def canvas_refresh(self, id, vertexes):
        """ Refresh the canvas """
        self.canvas.coords(id, vertexes)

    def update_side_bot(self):
        """ Update the information posted on the side bar."""
        if self.selected: 
            self.side_entry[0].config(text = str(self.selected.mass))
            self.side_entry[1].config(text = self.selected.shift.get_str())
            self.side_entry[2].config(text = self.selected.velo.get_str())
            self.side_entry[3].config(text = self.selected.accel.get_str())
        else:
            for i in xrange(4):
                self.side_entry[i].config(text = "")


    def create_circle(self, vertexes):
        """ Create a circle graphically and return the id of the object. """

        return self.canvas.create_oval(
                vertexes,
                fill="white"
                )

    def create_line(self, vertexes):
        """ Create a line graphically and return the id of the object."""
        return self.canvas.create_line(vertexes)

    def register_trigger(self, obj, real_interval, math_interval):
        """ Call this for hooking any simulated objects."""
        self.canvas.after(
                real_interval, obj.refresh, real_interval, math_interval)
Example #7
0
class Game:
    def __init__(self):
        self.root = Tk()
        self.frame1 = None
        self.frame2 = None
        self.w = None
        self.scoreC = None
        self.score = 0
        self.hor = True
        self.upid = self.downid = self.rightid = self.leftid = 0
        self.head = -1
        self.time = 700

    def home(self):
        self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black")
        self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25)
        self.root.wm_minsize(width=750, height=666)
        self.root.configure(bg="black")
        self.frame1.pack_propagate(0)
        self.frame1.update()
        self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
        logo = PhotoImage(file="Game_Logo.gif")
        starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(40))
        startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(60))
        starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(75))
        self.frame2.pack_propagate(0)
        exp = """        This is a game in which
        the arrow keys are used
        to move the snake around
        and to get points"""
        exf = Font(family="comic sans MS", size=20)
        Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right")
        Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left")
        starte.grid(row=0, columnspan=2)
        startm.grid(row=0, columnspan=2, column=4, padx=18)
        starth.grid(row=0, columnspan=2, column=8)
        head = Font(family="comic sans MS", size=30)
        self.H=Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10)
        self.H.pack()
        self.frame2.pack(expand=True)
        self.frame1.pack(expand=True)
        self.root.mainloop()

    def callgame(self, time):
        self.time = time
        self.game()

    def calldown(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.down(0)

    def callup(self, key):
        if self.hor:
            self.w.after_cancel(self.leftid)
            self.w.after_cancel(self.rightid)
            self.up(0)

    def callright(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.right(0)

    def callleft(self, key):
        if not self.hor:
            self.w.after_cancel(self.upid)
            self.w.after_cancel(self.downid)
            self.left(0)

    def game(self):
        self.score = 0
        self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey",
                        highlightthickness=10)
        self.frame1.destroy()
        self.frame2.destroy()
        self.root.configure(width=1000, padx=10)
        self.root.pack_propagate(0)
        self.w.configure(background="black")
        self.w.pack(side="left")
        self.w.create_line(300, 250, 450, 250, width=10, fill="teal")
        self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                            font=Font(family="comic sans MS", size=25))
        self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white")
        self.scoreC.pack(side="top")
        self.root.bind("<Up>", self.callup)
        self.root.bind("<Down>", self.calldown)
        self.root.bind("<Right>", self.callright)
        self.root.bind("<Left>", self.callleft)
        self.createFood()
        self.right(0)

    def down(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.downid = self.w.after(self.time, self.down, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def up(self, i):
        crd = self.w.coords(1)
        if len(crd)>0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.upid = self.w.after(self.time, self.up, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def right(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.rightid = self.w.after(self.time, self.right, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def left(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.leftid = self.w.after(self.time, self.left, i)
            else:

                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25,
                                font=Font(family="comic sans MS", size=15),
                                command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def createFood(self):
        # self.w.delete(self.food) #deleting old food.
        crd = self.w.coords(1)
        ext = []
        for i in crd:
            ext.append(i)
            for j in range(-50, 50):
                ext.append(i + j)
        randx = random.randrange(20, 730)
        randy = random.randrange(20, 480)
        while randx not in ext and randy not in ext:
            randx = random.randrange(20, 730)
            randy = random.randrange(20, 480)
        self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow")

    def checkEaten(self):
        headcoords = self.w.coords(self.head)
        foodcoords = self.w.coords(self.food)
        # self.w.delete(self.food)
        flag = False
        # print(headcoords[-4])
        # print(foodcoords[-4])
        # print(foodcoords[-2])
        if int(headcoords[-4]) in range(int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int(
                headcoords[-3]) in range(int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)):
            flag = True
        if flag:
            self.grow()
            self.score += 10
            self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35,
                                  font=Font(family="comic sans MS", size=25))
            self.w.delete(self.food)
            self.createFood()

    def grow(self):
        crd = self.w.coords(1)
        if crd[0] != crd[2]:  # horizontal condition
            if crd[0] < crd[2]:
                crd[0] -= 20
            else:
                crd[0] += 20
            self.w.coords(1, *crd)
        else:
            if crd[3] < crd[1]:
                crd[1] += 20
            else:
                crd[1] -= 20
            self.w.coords(1, *crd)

    def end(self):
        crd = self.w.coords(1)
        h = self.w.coords(self.head)
        a = 0
        while a < len(crd) - 2:
            if crd[a] == crd[a + 2]:
                if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or (
                        h[0] == crd[a]  and crd[a + 1] > h[1] > crd[a + 3]):
                    return True
            else:
                if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]):
                    return True
            a += 2
        if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0<h[1]<500):
            return True
        return False


    def callhome(self):
        self.w.destroy()
        self.start.destroy()
        self.H.destroy()
        self.scoreC.destroy()
        self.home()
class FullScreenWindow:

    def __init__(self, label_timeout, max_elements):
        self.count = 0
        self.colors_count = 0
        self.tk = Tk()
        self.max_elements = max_elements
        self.frame = Frame(self.tk)
        self.frame.bind("<Key>", self.key_press)
        self.frame.focus_set()
        self.state = False
        self.tk.attributes("-fullscreen", True)
        self.label_timeout = label_timeout

        self.screen_width = self.tk.winfo_screenwidth()
        self.screen_height = self.tk.winfo_screenheight()
        screen_resolution = str(self.screen_width) + 'x' + str(self.screen_height)
        self.tk.geometry(screen_resolution)
        self.canvas = Canvas(self.frame, height=self.screen_height, width=self.screen_width)
        self.canvas.pack(fill=BOTH)

        self.frame.pack()
        self.objects = deque()

    def key_press(self, key):
        self.draw_triangle()

    def draw_triangle(self):
        x1 = random.uniform(0, 1) * self.screen_width
        y1 = random.uniform(0, 1) * self.screen_height

        x2 = random.uniform(0, 1) * self.screen_width
        y2 = random.uniform(0, 1) * self.screen_height

        x3 = random.uniform(0, 1) * self.screen_width
        y3 = random.uniform(0, 1) * self.screen_height

        x4 = random.uniform(0, 1) * self.screen_width
        y4 = random.uniform(0, 1) * self.screen_height

        x5 = random.uniform(0, 1) * self.screen_width
        y5 = random.uniform(0, 1) * self.screen_height

        colors = ['black', 'red', 'green', 'blue', 'cyan', 'yellow', 'magenta']
        if self.colors_count % 7 == 0:
            self.colors_count = 0

        if self.count == 0:
            o = self.canvas.create_line(x1, y1, x2, y2, x3, y3, x1, y1)
            self.count = 1
        elif self.count == 1:
            o = self.canvas.create_rectangle(x1, y1, x2, y2, fill=colors[self.colors_count])
            self.colors_count += 1
            self.count = 2
        elif self.count == 2:
            o = self.canvas.create_oval(x1, y1, x2, y2, fill=colors[self.colors_count])
            self.colors_count += 1
            self.count = 3
        elif self.count == 3:
            o = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, fill=colors[self.colors_count])
            self.colors_count += 1
            self.count = 0
        if len(self.objects) >= self.max_elements:
            obj_to_remove = self.objects.pop()
            self.canvas.delete(obj_to_remove)
        self.objects.appendleft(o)
        self.canvas.after(self.label_timeout,self.canvas.delete, o)
        self.frame.pack(fill=BOTH, expand=1)
Example #9
0
class Photobooth:
    def __init__(self, root):
        self.root = root
        self.previewing = False
        self.camera = picamera.PiCamera()

        ## the canvas will display the images
        self.canv = Canvas(root, width=WIDTH, height=HEIGHT)
        self.canv.bind("<Button-1>", self.takePicture)
        self.canv.pack()


    def start(self):
        # Show a psuedo preview while the preview isn't going
        if not self.previewing:
            self.previewImage()
        # need to sleep instead
        self.canv.after(100, self.start)

    def previewImage(self):
        self.camera.capture(RAW_FILENAME, resize=(WIDTH, HEIGHT))
        image = Image.open(RAW_FILENAME)
        self.displayImage(image)


    def displayImage(self, im=None):
        '''
        display image im in GUI window
        '''
        #x,y = im.size
        #x = int(x / SCALE)
        #y = int(y / SCALE)

        #im = im.resize((x,y));
        #image_tk = ImageTk.PhotoImage(im)

        ## delete all canvas elements with "image" in the tag
        if im is None:
            return

        self.canv.delete("image")
        self.canv.create_image([WIDTH / 2, HEIGHT / 2],
                         image=im,
                         tags="image")


    def takePicture(self, event):
        self.previewing = True
        self.camera.start_preview()
        #camera.preview_alpha = 230
        self.camera.preview_window = (0, 0, WIDTH, HEIGHT)
        self.camera.preview_fullscreen = False

        self.countdown()
        self.camera.capture(RAW_FILENAME, resize=(WIDTH, HEIGHT))
        snapshot = Image.open(RAW_FILENAME)

        # Show it for a few seconds, then delete it
        self.camera.stop_preview()
        self.displayImage(snapshot)
        time.sleep(10)
        self.camera.remove_overlay(o)

        self.previewing = False
        return snapshot


    def countdown(self, countdown1=5):
        for i in range(countdown1):
            self.camera.annotate_text = str(countdown1 - i)
            #self.canv.delete("text")
            #self.canv.update()
            #self.canv.create_text(WIDTH/2 - 50, 300, text=str(countdown1 - i), font=font, tags="text")
            #self.canv.update()
            time.sleep(1)
Example #10
0
class Game:
    def __init__(self):
        self.root = Tk()
        self.frame1 = None
        self.frame2 = None
        self.w = None
        self.scoreC = None
        self.score = 0
        self.hor = True
        self.upid = self.downid = self.rightid = self.leftid = 0
        self.head = -1
        self.time = 700

    def home(self):
        self.frame1 = Frame(self.root,
                            width=750,
                            height=350,
                            padx=250,
                            bg="black")
        self.frame2 = Frame(self.root,
                            height=250,
                            width=750,
                            bg="black",
                            padx=25)
        self.root.wm_minsize(width=750, height=666)
        self.root.configure(bg="black")
        self.frame1.pack_propagate(0)
        self.frame1.update()
        self.frame1.configure(pady=self.frame1.cget("height") / 2.5)
        logo = PhotoImage(file="logo.gif")
        starth = Button(self.frame1,
                        text="Hard",
                        bg="orange",
                        padx=25,
                        pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(40))
        startm = Button(self.frame1,
                        text="Medium",
                        bg="teal",
                        padx=25,
                        pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(60))
        starte = Button(self.frame1,
                        text="Easy",
                        bg="orange",
                        padx=25,
                        pady=5,
                        font=Font(family="comic sans MS", size=10),
                        command=lambda: self.callgame(75))
        self.frame2.pack_propagate(0)
        exp = """        This is a game in which
        the arrow keys are used
        to move the snake around
        and to get points"""
        exf = Font(family="comic sans MS", size=20)
        Label(self.frame2, image=logo, bg="black", text=exp,
              padx=10).pack(side="right")
        Label(self.frame2,
              fg="white",
              bg="black",
              text=exp,
              justify="left",
              font=exf).pack(side="left")
        starte.grid(row=0, columnspan=2)
        startm.grid(row=0, columnspan=2, column=4, padx=18)
        starth.grid(row=0, columnspan=2, column=8)
        head = Font(family="comic sans MS", size=30)
        self.H = Label(self.root,
                       text="SNAKES",
                       font=head,
                       fg="orange",
                       bg="black",
                       pady=10)
        self.H.pack()
        self.frame2.pack(expand=True)
        self.frame1.pack(expand=True)
        self.root.mainloop()

    def callgame(self, time):
        self.time = time
        self.game()

    def do_after_cancel(self, a, b):
        if a != 0:
            self.w.after_cancel(a)
        if b != 0:
            self.w.after_cancel(b)

    def calldown(self, key):
        if self.hor:
            self.do_after_cancel(self.leftid, self.rightid)
            self.down(0)

    def callup(self, key):
        if self.hor:
            self.do_after_cancel(self.leftid, self.rightid)
            self.up(0)

    def callright(self, key):
        if not self.hor:
            self.do_after_cancel(self.upid, self.downid)
            self.right(0)

    def callleft(self, key):
        if not self.hor:
            self.do_after_cancel(self.upid, self.downid)
            self.left(0)

    def game(self):
        self.score = 0
        self.w = Canvas(self.root,
                        width=750,
                        height=500,
                        relief="flat",
                        highlightbackground="grey",
                        highlightthickness=10)
        self.frame1.destroy()
        self.frame2.destroy()
        self.root.configure(width=1000, padx=10)
        self.root.pack_propagate(0)
        self.w.configure(background="black")
        self.w.pack(side="left")
        self.w.create_line(300, 250, 450, 250, width=10, fill="teal")
        self.scoreC = Label(self.root,
                            text="Score\n" + str(self.score),
                            bg="black",
                            fg="teal",
                            padx=25,
                            pady=35,
                            font=Font(family="comic sans MS", size=25))
        self.head = self.w.create_line(450,
                                       250,
                                       455,
                                       250,
                                       width=10,
                                       fill="white")
        self.scoreC.pack(side="top")
        self.root.bind("<Up>", self.callup)
        self.root.bind("<Down>", self.calldown)
        self.root.bind("<Right>", self.callright)
        self.root.bind("<Left>", self.callleft)
        self.createFood()
        self.right(0)

    def down(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2],
                                           crd[-1] + 5,
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.downid = self.w.after(self.time, self.down, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def up(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-1] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-3] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2],
                                           crd[-1] - 5,
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = False
            if not end:
                self.upid = self.w.after(self.time, self.up, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def right(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] += 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] -= 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2] + 5,
                                           crd[-1],
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.rightid = self.w.after(self.time, self.right, i)
            else:
                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def left(self, i):
        crd = self.w.coords(1)
        if len(crd) > 0:
            if crd[0] == crd[2]:
                if crd[1] > crd[3]:
                    # print("inside if1")
                    crd[1] -= 10
                if crd[1] < crd[3]:
                    # print("inside if2")
                    crd[1] += 10
            else:
                if crd[0] > crd[2]:
                    crd[0] -= 10
                if crd[0] < crd[2]:
                    crd[0] += 10

            crd[-2] -= 10

            if i == 0:
                crd.append(crd[-2])
                crd.append(crd[-2])
                crd[-4] += 10
            if crd[0] == crd[2] and crd[1] == crd[3]:
                crd = crd[2:]
            self.w.coords(1, *crd)
            self.w.delete(self.head)
            self.head = self.w.create_line(crd[-2],
                                           crd[-1],
                                           crd[-2] - 5,
                                           crd[-1],
                                           width=10,
                                           fill="orange")
            end = self.end()
            self.checkEaten()
            i += 1
            self.hor = True
            if not end:
                self.leftid = self.w.after(self.time, self.left, i)
            else:

                self.w.delete(1)
                self.w.delete(self.head)
                self.w.delete(self.food)
                self.start = Button(self.root,
                                    text="Start",
                                    bg="orange",
                                    padx=25,
                                    pady=25,
                                    font=Font(family="comic sans MS", size=15),
                                    command=lambda: self.callhome())
                self.start.pack(side="bottom")

    def createFood(self):
        # self.w.delete(self.food) #deleting old food.
        crd = self.w.coords(1)
        ext = []
        for i in crd:
            ext.append(i)
            for j in range(-50, 50):
                ext.append(i + j)
        randx = random.randrange(20, 730)
        randy = random.randrange(20, 480)
        while randx not in ext and randy not in ext:
            randx = random.randrange(20, 730)
            randy = random.randrange(20, 480)
        self.food = self.w.create_line(randx,
                                       randy,
                                       randx + 12,
                                       randy,
                                       width=10,
                                       fill="yellow")

    def checkEaten(self):
        headcoords = self.w.coords(self.head)
        foodcoords = self.w.coords(self.food)
        # self.w.delete(self.food)
        flag = False
        # print(headcoords[-4])
        # print(foodcoords[-4])
        # print(foodcoords[-2])
        if int(headcoords[-4]) in range(
                int(foodcoords[-4]) - 7,
                int(foodcoords[-2]) + 7) and int(headcoords[-3]) in range(
                    int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)):
            flag = True
        if flag:
            self.grow()
            self.score += 10
            self.scoreC.configure(text="Score\n" + str(self.score),
                                  bg="black",
                                  fg="teal",
                                  padx=25,
                                  pady=35,
                                  font=Font(family="comic sans MS", size=25))
            self.w.delete(self.food)
            self.createFood()

    def grow(self):
        crd = self.w.coords(1)
        if crd[0] != crd[2]:  # horizontal condition
            if crd[0] < crd[2]:
                crd[0] -= 20
            else:
                crd[0] += 20
            self.w.coords(1, *crd)
        else:
            if crd[3] < crd[1]:
                crd[1] += 20
            else:
                crd[1] -= 20
            self.w.coords(1, *crd)

    def end(self):
        crd = self.w.coords(1)
        h = self.w.coords(self.head)
        a = 0
        while a < len(crd) - 2:
            if crd[a] == crd[a + 2]:
                if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or (
                        h[0] == crd[a] and crd[a + 1] > h[1] > crd[a + 3]):
                    return True
            else:
                if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (
                        h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]):
                    return True
            a += 2
        if (h[0] == 0
                and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (
                    h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760
                                                        and 0 < h[1] < 500):
            return True
        return False

    def callhome(self):
        self.w.destroy()
        self.start.destroy()
        self.H.destroy()
        self.scoreC.destroy()
        self.home()
Example #11
0
class Simulation(object):

    # Constructor
    # @param duration  Duration (in seconds) of the Simulation
    # @param dt        Time step
    # @param height    Height of the window
    # @param width     Width of the window
    # @param env_file  Path to the file containing Environment data
    def __init__(self, duration, dt, height, width, env_file):
        self._duration = duration
        self._dt = dt
        
        # Create the Canvas onto which everything will be rendered
        self._root = Tk()
        self._canvas = Canvas(
                          self._root,
                          width=width,
                          height=height)
        self._canvas.grid(column=0, row=0, sticky=(N, W, E, S))

        # Set the title, and make the Window un-sizable
        self._parent = self._root
        self._parent.title("Awesome Robot Simulation")
        self._parent.resizable(0, 0)

        # Determine the window position (centered nicely)
        self.center_window(height, width)
        
        # Read in the environment data
        self._env = Environment()
        self._env.set_dimensions(height, width)
        if env_file:
            self._env.read_env(env_file)

    # Center the window on the screen
    # @param wh Height of the window to center
    # @param ww Width of the window to center
    def center_window(self, wh, ww):
        sw = self._parent.winfo_screenwidth()
        sh = self._parent.winfo_screenheight()
        x, y = (sw - ww) / 2, (sh - wh) / 2

        self._parent.geometry('%dx%d+%d+%d' % (ww, wh, x ,y))

    # Start the event loop
    def start_event_loop(self):
        self.timer_triggered()
        self._parent.mainloop()

    # When the timer goes off, update and redraw everything and reset the timer
    def timer_triggered(self):
        self.update()
        self.redraw()
        self._canvas.after(self._dt, self.timer_triggered)

    # Update the simulation for the latest time step
    def update(self):
        sleep(0.05)   # sleep so the animation doesn't finish too quickly
        self._duration -= self._dt;
        if not self._duration > 0:
            raw_input("Press <Enter> to stop the simulation...")

            # Print the results
            print
            for robot in self._env.robots():
                M, N = robot.slam().M(), robot.slam().N()
                for i in range(N):
                        computed_landmark_pos = np.matrix([0.0, 0.0]).T
                        for k in range(M):
                            computed_landmark_pos += robot.slam().particles()[k].features()[i][0]
                        computed_landmark_pos /= M
                        computed_landmark_x = computed_landmark_pos.item(0)
                        computed_landmark_y = computed_landmark_pos.item(1)

                        (actual_landmark_x, actual_landmark_y) = self._env.landmarks()[i].pos()
                        print "Landmark %d => actual: (%f, %f), computed: (%f, %f)" % \
                              (i, actual_landmark_x, actual_landmark_y, computed_landmark_x, computed_landmark_y)

                print

                # TODO --- maybe just take the particle with the highest weight (maybe top 2 or 3)? [same for landmarks]
                actual_robot_x, actual_robot_y, actual_robot_theta = robot.pose()
                computed_robot_x, computed_robot_y, computed_robot_theta = (0.0, 0.0, 0.0)
                for k in range(M):
                    (p_x, p_y, p_theta) = robot.slam().particles()[k].pose()
                    computed_robot_x += p_x
                    computed_robot_y += p_y
                    computed_robot_theta += p_theta
                print "Robot pose => actual: (%f, %f, %f), computed: (%f, %f, %f)" % \
                      (actual_robot_x, actual_robot_y, actual_robot_theta,
                       computed_robot_x / M, computed_robot_y / M, computed_robot_theta / M)

            exit()

        # Update all of the robots
        updated_robots = []
        for robot in self._env.robots():
            updated_robots.append(robot.update(self._dt))
        self._env._robots = updated_robots

    # Redraw the canvas
    def redraw(self):
        self._canvas.delete(ALL)
        for wall in self._env.walls():
            wall.draw(self._canvas)
        for landmark in self._env.landmarks():
            landmark.draw(self._canvas)
        for robot in self._env.robots():
            robot.draw(self._canvas)

    # Start the simulation
    def start(self):
        self.start_event_loop()
class App:
    def __init__(self, master, height, width):
        from Tkinter import Label, Entry, Canvas, Button
    
        Label(master, text="Initial conditions:").grid(row=0, column=0, columnspan=2)
        Label(master, text="q").grid(row=1, column=0)
        Label(master, text="p").grid(row=2, column=0)
        Label(master, text="t").grid(row=3, column=0)
        Label(master, text="v").grid(row=4, column=0)
        Label(master, text="b").grid(row=5, column=0)
        Label(master, text="l").grid(row=6, column=0)
        Label(master, text="g").grid(row=7, column=0)
        Button(master, text="Reset", command=self.resetInitialConditions).grid(row=8, column=0, columnspan=2)

        self.q = Entry(master)
        self.p = Entry(master)
        self.t = Entry(master)
        self.v = Entry(master)
        self.b = Entry(master)
        self.l = Entry(master)
        self.g = Entry(master)

        self.q.grid(row=1, column=1)
        self.p.grid(row=2, column=1)
        self.t.grid(row=3, column=1)
        self.v.grid(row=4, column=1)
        self.b.grid(row=5, column=1)
        self.l.grid(row=6, column=1)
        self.g.grid(row=7, column=1)

        self.canv = Canvas(master, height=height, width=width)
        self.canv.grid(row=0, column=2, rowspan=8)

        self.pendulum = DrivenPendulum()

        self.q.insert(0, 2.)
        self.p.insert(0, 0.)
        self.t.insert(0, 0.)
        self.v.insert(0, 2.)
        self.b.insert(0, 1.)
        self.l.insert(0, 1.5)
        self.g.insert(0, -10.)

        self.rad = 8
        self.scaleFactor = 50
        self.shiftPosition = array([width//2, height//2])

        self.axes = self.canv.create_line(tuple(self.shiftPosition) + tuple(self.shiftPosition) + tuple(self.shiftPosition))
        self.bob1 = self.canv.create_oval(self.getOvalCoords(self.shiftPosition), fill="blue")
        self.bob2 = self.canv.create_oval(self.getOvalCoords(self.shiftPosition), fill="red")

        self.resetInitialConditions()
        self.updatePendulum()

    def getOvalCoords(self, position):
        return (position[0]-self.rad, position[1]-self.rad, position[0]+self.rad, position[1]+self.rad)

    def updatePendulum(self):

        pos1 = (self.scaleFactor*self.pendulum.getInnerPosition()*array([1, -1])).astype(int) + self.shiftPosition
        pos2 = (self.scaleFactor*self.pendulum.getOuterPosition()*array([1, -1])).astype(int) + self.shiftPosition

        self.canv.coords(self.axes, tuple(self.shiftPosition) + tuple(pos1) + tuple(pos2))
        self.canv.coords(self.bob1, self.getOvalCoords(pos1))
        self.canv.coords(self.bob2, self.getOvalCoords(pos2))

        print self.pendulum.getPhaseSpacePoint()

        self.pendulum.evolve(0.05)
        self.canv.after(20, self.updatePendulum)

    def resetInitialConditions(self):
        self.pendulum.setInitialConditions(
                float(self.q.get()),
                float(self.t.get()),
                float(self.v.get()),
                float(self.p.get()),
                float(self.b.get()),
                float(self.l.get()),
                float(self.g.get()),
                )
Example #13
0
class Stage(AnimationController, LeapListener):
    #objects that will have physics applied to them
    world_objects = {}
    #place holder for the mouse x and y coordinates
    mouse_x, mouse_y = 0, 0 
    
    hands = []
    
    def mouseMoved(self, e):
        """
        Event handler for moving the mouse on the canvas
        This will set the mouse_x and mouse_y to the current mouse
        coordinates
        """        
        self.mouse_x, self.mouse_y = int(e.x), int(e.y)
        
    
    def startFiringWeapon(self, e):
        """
        Creates a new bullet at the tip of the cannon head once 
        every 30 milliseconds until the Stage.weapon_firing bool
        is false. At which time the thread will break out of its loop and die
        """
        def keepFiring():
            if Cannon.weapon_firing == True:  
                sound = self.bullet_snd.play()                
                Bullet(
                    position = self.world_objects["cannon"].cannon_head,
                    stage = self,                    
                    velocity = (-60, self.world_objects["cannon"].cannon_angle),
                )
                self.can.after(50, func=keepFiring)
        Cannon.weapon_firing = True
        keepFiring()

    def stopFiringWeapon(self, e):
        """
        Stops your gun from firing when you release the mouse button
        """        
        Cannon.weapon_firing = False
            
            
    def __init__(self, root, snack): 
        self.snack = snack
        
        self.click_loop = snack.Sound()
        self.click_loop.load('test2_sounds/185768__jobro__click-loop.wav')        
                    
        self.bullet_snd = snack.Sound()
        self.bullet_snd.load('test2_sounds/gun.wav')        

        #set resolution to screen width
        self.width = root.winfo_screenwidth()
        self.height = root.winfo_screenheight()
        root.wm_attributes('-fullscreen', 1)
        #create a canvas to draw on
        self.can = Canvas(root, cursor='none', width=self.width, height=self.height, background="black")
        self.can.pack()
        
        def playMusic():            
            self.click_loop.play()
            info = self.click_loop.length(units="SECONDS")
            self.can.after(int(info) * 1000, playMusic)
        #playMusic()
        
        #bind canvas events
        self.can.bind("<Motion>", self.mouseMoved)
        
        
        #create a cannon
        c = Cannon(self)
        self.world_objects["cannon"] = c
        
        root.bind("a", c.moveLeft)
        root.bind("d", c.moveRight)
        
        def exit(e):
            pid = os.getpid()
            os.kill(pid, 9)
        
        root.bind("<Escape>", exit)
        self.can.bind("<ButtonPress-1>", self.startFiringWeapon)
        self.can.bind("<ButtonRelease-1>", self.stopFiringWeapon)
        
        #create the ground
        self.world_objects["ground"] = Ground(self)
        self.world_objects["stats"] = Stats(self)
        self.world_objects["cube"] = Cube(self)
        self.world_objects["crosshair"] = Crosshair(self)
        
        LeapListener.__init__(self)
        self.leap_controller = Leap.Controller()
        self.leap_controller.add_listener(self)
        
        
        #create my draw loop
        self.drawLoop()
        
        
        
        
        
        
        
        
        
        
        
        
        
        
Example #14
0
class Simulator(object):
    def __init__(self):
        tk=Tk()
        tk.title = "T da B's Gravity Simulator"
        self.width = 1900
        self.height = 1000

        self.canvas=Canvas(tk, width=self.width, height=self.height, bg='black')
        self.masses = list()
        self.new_masses = list()
        for _ in range(20):
            size = randint(3, 7)
            m = MassiveObject(
                size * 10**16,
                size,
                randint(100, self.width - 100),
                randint(100, self.height - 100),
                randint(-15, 15),
                randint(-15, 15),
                random_color()
                )
            m.canvas_id = self.canvas.create_oval(m.x - m.radius,
                                               m.y - m.radius,
                                               m.x + m.radius,
                                               m.y + m.radius,
                                               outline=m.color,
                                               fill=m.color)
            self.masses.append(m)
        self.canvas.pack()

        self.draw()
        tk.mainloop()

    def draw(self):
        """
        Main loop
        """
        for m in self.masses:
            #if m.is_deleted is True:
            #    self.masses.remove(m)
            #    continue
            for m2 in self.masses:
                if m2 == m:
                    continue
                else:
                    self.update(m, m2)
            #m.draw_accel_vector()
            #m.draw_vel_vector()
        self.masses += self.new_masses
        self.new_masses = list()
        self.canvas.after(10, self.draw)

    def update(self, m1, m2):
        """
        Update MassiveObject m1 with respect to m2
        """
        #if ( distance(m1, m2) < m1.radius + m2.radius ):
        #    logger.info("%s and %s collided!" % (m1.color, m2.color))
        #    self.canvas.delete(m1.canvas_id, m2.canvas_id)

        #    text = self.canvas.create_text((m1.x + m2.x) / 2,
        #                                 (m1.y + m2.y) / 2,
        #                                 text="COLLISION!",
        #                                 fill='red')
        #    self.canvas.after(1000, self.canvas.delete, text)
        #    m1.is_deleted = True
        #    m2.is_deleted = True
        if ( distance(m1, m2) < m1.radius + m2.radius ):
            self.canvas.delete(m1.canvas_id, m2.canvas_id)

            '''
            text = self.canvas.create_text((m1.x + m2.x) / 2,
                                         (m1.y + m2.y) / 2,
                                         text="COLLISION!",
                                         fill='red')
            self.canvas.after(1000, self.canvas.delete, text)
            '''

            self.masses.remove(m1)
            self.masses.remove(m2)
            mid_x = (m1.x + m2.x) / 2
            mid_y = (m1.y + m2.y) / 2
            c1 = m1.mass / (m1.mass + m2.mass)
            c2 = m2.mass / (m1.mass + m2.mass)
            v_x = c1 * m1.v_x + c2 * m2.v_x
            v_y = c1 * m1.v_y + c2 * m2.v_y

            new_m = MassiveObject(
                m1.mass + m2.mass,
                m1.radius + m2.radius,
                mid_x,
                mid_y,
                v_x,
                v_y,
                avg_color(m1.color, m2.color)
                )
            new_m.canvas_id = self.canvas.create_oval(new_m.x - new_m.radius,
                                                   new_m.y - new_m.radius,
                                                   new_m.x + new_m.radius,
                                                   new_m.y + new_m.radius,
                                                   outline=new_m.color,
                                                   fill=new_m.color)
            self.new_masses.append(new_m)
            return

        old_x = m1.x
        old_y = m1.y
        g_x, g_y = grav_force(m1, m2)
        m1.a_x = g_x / m1.mass
        m1.a_y = g_y / m1.mass
        m1.t += m1.timestep
        m1.x += m1.timestep * (m1.v_x + .5*(m1.timestep * m1.a_x))
        m1.y += m1.timestep * (m1.v_y + .5*(m1.timestep * m1.a_y))
        g_x, g_y = grav_force(m1, m2)
        new_a_x, new_a_y = g_x / m1.mass, g_y / m1.mass
        m1.v_x += m1.timestep * .5 * (m1.a_x + new_a_x)
        m1.v_y += m1.timestep * .5 * (m1.a_y + new_a_y)

        self.canvas.move(m1.canvas_id, m1.x - old_x, m1.y - old_y)
        logger.info("Updated %s from (%s, %s) to (%s, %s)" % (m1.color, old_x, old_y, m1.x, m1.y))

    def draw_accel_vector(self):
        m = mag(self.x, self.y, self.x + self.a_x, self.y + self.a_y)
        if m > 1:
            line = self.canvas.create_line(self.x,
                                           self.y,
                                           self.x + self.a_x,
                                           self.y + self.a_y,
                                           fill='yellow',
                                           arrow='last')

            text = self.canvas.create_text(self.x + 1.2 * self.a_x,
                                           self.y + 1.2 * self.a_y,
                                           text=str(int(m)),
                                           fill='yellow')
            self.canvas.after(int(self.timestep * 1000), self.canvas.delete, line, text)

    def draw_vel_vector(self):
        m = mag(self.x, self.y, self.x + self.v_x, self.y + self.v_y)
        if m > 1:
            line = self.canvas.create_line(self.x,
                                           self.y,
                                           self.x + self.v_x,
                                           self.y + self.v_y,
                                           fill='red',
                                           arrow='last')

            text = self.canvas.create_text(self.x + 1.2 * self.v_x,
                                           self.y + 1.2 * self.v_y,
                                           text=str(int(m)),
                                           fill='red')
            self.canvas.after(int(self.timestep * 1000), self.canvas.delete, line, text)