示例#1
0
 def draw_flood(self, canvas: Canvas, step_time_ms: int):
     scale = canvas.winfo_width() / (self.size * 2 + 1)
     flood_step = self.flood.step()
     rgb = self.to_rgba(flood_step["position"])
     color = "#" + \
             str(hex(int(rgb[0] * 255)))[2:].rjust(2, '0') + \
             str(hex(int(rgb[1] * 255)))[2:].rjust(2, '0') + \
             str(hex(int(rgb[2] * 255)))[2:].rjust(2, '0')
     for point in flood_step["front"]:
         canvas.create_rectangle((point["x"] * 2 + 1) * scale,
                                 (point["y"] * 2 + 1) * scale,
                                 (point["x"] * 2 + 2) * scale,
                                 (point["y"] * 2 + 2) * scale, fill=color, width=0)
         if point['from'] == DIRECTIONS[0]:
             canvas.create_rectangle((point["x"] * 2) * scale,
                                     (point["y"] * 2 + 1) * scale,
                                     (point["x"] * 2 + 1) * scale,
                                     (point["y"] * 2 + 2) * scale, fill=color, width=0)
         elif point['from'] == DIRECTIONS[1]:
             canvas.create_rectangle((point["x"] * 2 + 1) * scale,
                                     (point["y"] * 2) * scale,
                                     (point["x"] * 2 + 2) * scale,
                                     (point["y"] * 2 + 1) * scale, fill=color, width=0)
         elif point['from'] == DIRECTIONS[2]:
             canvas.create_rectangle((point["x"] * 2 + 2) * scale,
                                     (point["y"] * 2 + 1) * scale,
                                     (point["x"] * 2 + 3) * scale,
                                     (point["y"] * 2 + 2) * scale, fill=color, width=0)
         elif point['from'] == DIRECTIONS[3]:
             canvas.create_rectangle((point["x"] * 2 + 1) * scale,
                                     (point["y"] * 2 + 2) * scale,
                                     (point["x"] * 2 + 2) * scale,
                                     (point["y"] * 2 + 3) * scale, fill=color, width=0)
     if len(flood_step["front"]) > 0:
         canvas.after(step_time_ms, lambda: self.draw_flood(canvas, step_time_ms))
示例#2
0
class StarField:
    def __init__(self, width, height, depth=32, num_stars=500):
        self.master = Tk()
        self.master.title("StarField")
        self.master.resizable(False, False)
        self.master.maxsize(width, height)
        self.fov = 180 * math.pi / 180
        self.view_distance = 0
        self.stars = []
        self.width = width
        self.height = height
        self.max_depth = depth
        self.canvas = Canvas(self.master,
                             width=width,
                             height=height,
                             bg="#000000")
        self.canvas.pack()

        for x in range(num_stars):
            star = Star(x=randrange(-self.width, self.width),
                        y=randrange(-self.height, self.height),
                        z=randrange(1, self.max_depth))
            star.id = self.canvas.create_oval(star.x - star.radius,
                                              star.y - star.radius,
                                              star.x + star.radius,
                                              star.y + star.radius,
                                              fill='#FFFFFF')
            self.stars.append(star)
        self.draw()
        mainloop()

    def draw(self):
        for star in self.stars:
            # move depth
            star.z -= 0.19
            star.radius = (1 - float(star.z) / self.max_depth) * 1.7
            star.fill = int((1 - float(star.z) / self.max_depth) * 255)

            # reset depth
            if star.z <= 0:
                star.x = randrange(-self.width, self.width)
                star.y = randrange(-self.height, self.height)
                star.z = self.max_depth
                star.radius = 1
                star.fill = 0

            # Transforms this 3D point to 2D using a perspective projection.
            factor = self.fov / (self.view_distance + star.z)
            x = star.x * factor + self.width / 2
            y = -star.y * factor + self.height / 2

            self.canvas.coords(star.id, x - star.radius, y - star.radius,
                               x + star.radius, y + star.radius)
            self.canvas.itemconfig(star.id,
                                   fill='#%02x%02x%02x' %
                                   (star.fill, star.fill, star.fill))
        self.canvas.after(30, self.draw)
示例#3
0
class MainWindow(Frame):

    def __init__(self):
        super().__init__()
        self.initUI()

        self.to_clear = []

    def initUI(self):
        self.master.title('Simulación caja')
        self.pack(fill=tk.BOTH, expand=1)
        self.canvas = Canvas(self)
        self.canvas.pack(fill=tk.BOTH, expand=1)

        self.x = 20

        self.canvas.create_rectangle(0, 0, WIDTH, HEIGHT, fill='#fff')
        box(self.canvas, 10, 10)

        self.boton_siguiente = Button(self, text='siguiente', command=siguiente)
        print(self.winfo_width())
        self.boton_siguiente.place(x=500, y=50)


    def clear(self, fast=True):
        if fast:
            for item in self.to_clear:
                self.canvas.create_rectangle(*item,
                                             outline='#fff', fill='#fff')

    def draw(self):
        self.clear()

        for i_row, row in enumerate(deposito):
            for i_col, cell in enumerate(row):
                if cell == True:
                    posicion = Position(row=i_row, col=i_col)
                    c = (i_row, i_col)
                    if posicion == posicion_inicial:
                        cell_image = box(self.canvas,
                                         i_col, i_row,
                                         color='#FAA')
                    elif c in posicion_actual.cells:
                        cell_image = box(self.canvas,
                                         i_col, i_row,
                                         color='#FFA')
                    elif c in posicion_destino.cells:
                        cell_image = box(self.canvas,
                                         i_col, i_row,
                                         color='#AFA')
                    else:
                        cell_image = box(self.canvas,
                                         i_col, i_row,
                                         color='#AAf')
                    self.to_clear.append(cell_image)

        self.canvas.after(30, self.draw)
示例#4
0
class GUI(object):
    def __init__(self, universe):
        self.ticks = 0
        self.universe = universe
        self.width = universe.width
        self.height = universe.height

        self.window = Tk()
        self.window.title("Mars Explorer")

        temp_x, temp_y = self.get_window_coordinates()
        self.window.geometry('%dx%d+%d+%d' %
                             (self.width, self.height, temp_x, temp_y))

        self.canvas = Canvas(self.window, width=self.width, height=self.height)
        self.canvas.pack()
        self.canvas.after(1, self.tick())

    def start(self):
        print('GUI:: Starting loop...')
        self.window.mainloop()

    def get_window_coordinates(self):
        # Get screen width and height.
        screen_width = self.window.winfo_screenwidth()
        screen_height = self.window.winfo_screenheight()
        # Get x and y
        window_x = screen_width / 2 - self.width / 2
        window_y = screen_height / 2 - self.height / 2
        return window_x, window_y

    def tick(self):
        # Stop if done.
        if self.universe.universe_is_no_more():
            return

        self.universe.tick()
        self.draw()

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

    def draw(self):
        self.canvas.delete('all')
        self.universe.draw(self.canvas)
        for obj in self.universe.objects:
            obj.draw(self.canvas)

        self.canvas.create_text(70, 10, text=str(self.ticks))
        self.canvas.create_text(70,
                                50,
                                text='Rocks delivered: %d' %
                                self.universe.n_rocks_collected)
        self.canvas.create_text(70,
                                70,
                                text='Total rocks: %d' % self.universe.n_rocks)
示例#5
0
class Animation(object):
    # Override these methods when creating an animation
    def mousePressed(self, event):
        pass

    def keyPressed(self, event):
        pass

    def timerFired(self):
        pass

    def init(self):
        pass

    def redrawAll(self):
        pass

    def run(self, width=1000, height=600):
        # create the root and the canvas
        root = Tk()
        self.width = width
        self.height = height
        self.boardDim = self.width - 400
        self.canvas = Canvas(root, width=width, height=height)
        self.canvas.pack()

        # set up events
        def redrawAllWrapper():
            self.canvas.delete(ALL)
            self.redrawAll()

        def mousePressedWrapper(event):
            self.mousePressed(event)
            redrawAllWrapper()

        def keyPressedWrapper(event):
            self.keyPressed(event)
            redrawAllWrapper()

        root.bind("<Button-1>", mousePressedWrapper)
        root.bind("<Key>", keyPressedWrapper)
        # set up timerFired events
        self.timerFiredDelay = 50

        def timerFiredWrapper():
            self.timerFired()
            redrawAllWrapper()
            # pause, then call timerFired again
            self.canvas.after(self.timerFiredDelay, timerFiredWrapper)

        # init and get timerFired running
        self.init()
        timerFiredWrapper()
        pygame.init()
        # launch the app
        root.mainloop()
def loo_lumi(aken, lume_pilt, kingi_pilt):
    """Create new snow, gifts and make both move with another function."""
    lumi = Canvas(aken, bg="Blue", highlightthickness=0, width=20, height=20)
    pilt = [lume_pilt, kingi_pilt]
    pilt = random.choice(pilt)
    positsioon_x = random.randint(0, 780)
    lumi.create_image(9, 9, image=pilt)
    lumi.pack()
    lumi.after(500, loo_lumi, aken, lume_pilt, kingi_pilt)
    lumesadu(aken, lumi, positsioon_x, 120)
class PulseText:
    def __init__(self, parent):
        self.canvas = Canvas(parent,
                             bg=ApiSettings.Background,
                             highlightthickness=0)
        width = int(self.canvas.cget("width")) / 2
        height = int(self.canvas.cget("height")) / 2
        self.text = self.canvas.create_text(width,
                                            height,
                                            fill=ApiSettings.Foreground,
                                            font=(ApiSettings.Font,
                                                  ApiSettings.LargeTextSize),
                                            text="no text")

        self.run = False
        self.color = 0
        self.brighten = True

        Logger.debug("Initialization of PulseText class")

    def _animation(self):
        pulse_color = "#{:02x}{:02x}{:02x}".format(self.color, self.color,
                                                   self.color)

        if self.color == 0:
            self.brighten = True

        if self.color == 255:
            self.brighten = False

        if self.brighten:
            self.color += 5
        else:
            self.color -= 5
        self.canvas.itemconfig(self.text, fill=pulse_color)

        if self.run:
            self.canvas.after(15, self._animation)

    def set_text(self, text):
        self.canvas.itemconfig(self.text, text=text)
        Logger.debug("Set pulse text animation: {0}".format(text))

    def start_animation(self):
        self.canvas.pack()
        self.run = True
        self._animation()
        Logger.debug("Start pulse text animation")

    def stop_animation(self):
        self.run = False
        self.canvas.pack_forget()
        Logger.debug("Stop pulse text animation")
示例#8
0
class Gui(object):
    def __init__(self, width, height, world):
        self.ticks = 0
        self.world = world
        self.width = width
        self.height = height
        self.keepGoing = True

        self.root = Tk()
        self.root.title("Mars Explorer Agent")
        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)

        self.root.protocol("WM_DELETE_WINDOW", self.onClosing)

    def onClosing(self):
        self.root.destroy()

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

    def _tick(self):
        self.world.tick()
        self._draw()
        self.ticks += 1
        if self.keepGoing: self.canvas.after(10, self._tick)

    def _draw(self):
        self.canvas.delete('all')
        self.world.draw(self.canvas)
        self.canvas.create_text(self.width - 20, 10, text=str(self.ticks))
        self.canvas.create_text(self.width - 70,
                                50,
                                text='Rocks delivered: %d' %
                                self.world.collectedSamples)
        self.canvas.create_text(self.width - 55,
                                70,
                                text='Total rocks: %d' %
                                self.world.existingSamples)

    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
示例#9
0
class SS(Tk):
    def __init__(self):
        super().__init__()
        # self.lift()
        # self.attributes("-fullscreen", True)
        # self.attributes('-topmost', True)

        self.sw = 700  # self.winfo_screenwidth()
        self.sh = 500  # self.winfo_screenheight()

        self.x = self.sw / 2
        self.y = self.sh / 2
        self.vx = randint(-3, 3)
        self.vy = randint(-3, 3)
        self.img_index = 0

        self.c = Canvas(width=self.sw, height=self.sh)
        self.c.config(bg="black", bd=0, highlightthickness=0)
        self.c.pack()

        dvd_img = PhotoImage(file=f"{this_dir}/data/{self.img_index}.gif")
        self.dvd = dvd_img

        self.dvd_w = self.dvd.width() / 2
        self.dvd_h = self.dvd.height() / 2

        self.img = self.c.create_image(self.x, self.y, image=dvd_img)

        self.main()

    def change_img(self):
        self.img_index += 1
        self.dvd["file"] = f"{this_dir}/data/{self.img_index}.gif"

    def main(self):
        self.x = self.x + self.vx
        self.y = self.y + self.vy

        if self.x - self.dvd_w < 0 or self.x + self.dvd_w > self.sw:
            self.vx = -self.vx
            self.change_img()

        if self.y - self.dvd_h < 0 or self.y + self.dvd_h > self.sh:
            self.vy = -self.vy
            self.change_img()

        if self.img_index >= 6:
            self.img_index = 0

        self.c.coords(self.img, self.x, self.y)
        self.c.after(20, self.main)
示例#10
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, 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
示例#11
0
def make_game(tk: Tk):
    """
    The main activity constructor. It turns on the music volume to max level, allocates canvas and
    manages its entity motions. Generally speaking, there're just two sprites over here: the ball
    and the paddle. The first one is periodically re-rendered by the game, the last one's managed
    by the player. The endgame condition is the ball being fallen over the bottom viewport border.
    """
    music.set_volume(GAME_VOLUME)
    canvas_width, canvas_height = tk.winfo_width(), tk.winfo_height()
    canvas = Canvas(tk,
                    width=canvas_width,
                    height=canvas_height,
                    highlightthickness=0,
                    bg=BACKGROUND_COLOR)
    canvas.pack_configure(expand=True, fill='both')
    canvas.setvar(GAME_IS_RUNNING)
    canvas.setvar(BALL_IS_MOVING)
    canvas.update()
    paddle_width, paddle_height = 150, 10
    paddle_x, paddle_y = (canvas.winfo_width() -
                          paddle_width) // 2, canvas.winfo_height() - 300
    paddle_id = canvas.create_rectangle(paddle_x,
                                        paddle_y,
                                        paddle_x + paddle_width,
                                        paddle_y + paddle_height,
                                        width=0,
                                        fill=SPRITE_COLOR)
    paddle_vx = 8
    canvas.bind_all(KEY_LEFT, move_paddle_left(canvas, paddle_id, paddle_vx))
    canvas.bind_all(KEY_RIGHT, move_paddle_right(canvas, paddle_id, paddle_vx))
    ball_x, ball_y, ball_r = 455, 300, 15
    ball_id = canvas.create_oval(ball_x,
                                 ball_y,
                                 ball_x + 2 * ball_r,
                                 ball_y + 2 * ball_r,
                                 width=0,
                                 fill=SPRITE_COLOR)
    ball_vx, ball_vy = uniform(-3, -1), uniform(-4, -2)
    delay = 10
    canvas.after(
        0,
        move_ball(canvas, ball_id, paddle_id, choice([ball_vx, -ball_vx]),
                  ball_vy, delay))
    canvas.after(0, check_fall(tk, canvas, ball_id, delay))
示例#12
0
class World(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.queue = queue
        self.is_game_over = False
        self.canvas = Canvas(self, width=500, height=300, bg='red')
        self.canvas.pack()
        self.snake = self.canvas.create_line((0, 0), (0, 0),
                                             fill='black',
                                             width=10)
        self.food = self.canvas.create_rectangle(0,
                                                 0,
                                                 0,
                                                 0,
                                                 fill='#FFCC4C',
                                                 outline='#FFCC4C')
        self.points_earned = self.canvas.create_text(450,
                                                     20,
                                                     fill='white',
                                                     text='SCORE:0')
        self.queue_handler()

    def queue_handler(self):
        while True:
            try:
                task = self.queue.get(block=False)
                if task.get('game_over'):
                    self.game_over()
                if task.get('move'):
                    points = [x for point in task['move'] for x in point]
                    self.canvas.coords(self.snake, *point)
            except queue.Empty:
                if not self.is_game_over:
                    self.canvas.after(100, self.queue_handler)

    def game_over(self):
        self.is_game_over = True
        self.canvas.create_text('Game Over')
        qb = Button(self, text='Quit', command=self.destroy)
        rb = Button(self, text='Again', command=self.__init__)
示例#13
0
class Visual(object):
    def __init__(self, width=800, height=600):
        root = Tk()
        self.root = root
        self.margin = 0.12*height
        self.width, self.height = width, height - self.margin
        self.cx, self.cy = width/2, (height - self.margin)/2
        self.toolbar = \
            Canvas(self.root, width=self.width, height=self.margin)
        self.toolbar.pack()
        self.canvas = Canvas(root, width=width, height=height - self.margin)
        self.canvas.pack()
        self.init_animation()
        root.bind("<Button-1>", lambda e: self.mouse_event(e))
        root.bind("<Key>", lambda e: self.key_event(e))
        root.mainloop()

    def draw_users(self):
        """Draw all users"""
        for user in self.users:
            user.draw()

    def draw_connections(self):
        """Draw all of user's connections"""
        for user in self.users:
            user.draw_students()

    def draw_start_screen(self):
        """Start screen text"""
        self.canvas.delete(ALL)
        cx, cy = self.width/2, self.height/2
        font = ("Impact", "128")
        self.canvas.create_text(cx, 0.8*cy, text="INFECTION", font=font)
        font = ("Impact", 32)
        self.canvas.create_text(cx, 1.5*cy, text="Press s to Begin", font=font)

    def draw_setup_screen(self):
        """User setup screen"""
        self.canvas.delete(ALL)
        cx, cy = self.width/2, self.height/2
        text = "Number of Users (1-{})".format(self.max_users)
        font = ("Impact", 24)
        self.canvas.create_text(cx, 0.4*cy, text=text, font=font)
        self.num_users_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.5*cy, window=self.num_users_entry)
        self.num_users_entry.insert(0, str(self.default_users))

        text = "Number of Coaches"
        self.canvas.create_text(cx, 0.6*cy, text=text, font=font)
        self.num_coaches_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.7*cy, window=self.num_coaches_entry)
        self.num_coaches_entry.insert(0, str(self.default_coaches))

        text = "Max Number of Students"
        self.canvas.create_text(cx, 0.8*cy, text=text, font=font)
        self.num_students_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.9*cy, window=self.num_students_entry)
        self.num_students_entry.insert(0, str(self.default_students))

        self.button = Button(cx, 1.5*cy, 0.3*cx, 0.2*cy, "Begin")
        self.button.draw(self.canvas)

    def draw_toolbar(self):
        """Toolbar for main animation"""
        self.toolbar.create_text(self.cx, 0.1*self.cy, text="INFECTION",
                                 font=("Impact", 32))
        self.toolbar.create_text(self.cx*0.05, 0.1*self.cy,
                                 text="Total Infection: Click User",
                                 font=("Impact", 20), anchor="w")
        self.toolbar.create_text(self.cx*1.8, 0.1*self.cy,
                                 text="Limited Infection",
                                 font=("Impact", 20), anchor="e")
        self.limited_entry = Entry(self.toolbar, justify=CENTER, width=3)
        self.toolbar.create_window(self.cx*1.85, 0.1*self.cy,
                                   window=self.limited_entry)
        self.limited_entry.insert(0, str(self.default_users//2))
        cx, cy = self.cx*1.95, self.margin*0.35
        r = self.margin/5
        self.limited_button = (cx, cy, r)
        self.toolbar.create_oval((cx-r, cy-r, cx+r, cy+r), width=2, fill="RED")
        self.toolbar.create_text(cx, cy, text="X", font=("Courier Bold", 30))
        side = self.width/self.versions
        self.side = side
        y = 50
        self.gradient = (y, y+side)
        for col in range(int(self.versions)):
            fill = self.get_fill(col)
            width = 2 if col == self.version else 0
            self.toolbar.create_rectangle(col*side, y, (col+1)*side, y+side,
                                          fill=fill, width=width)
        self.select_version()

    def redraw_all(self):
        """Refresh frame for infection animation"""
        self.canvas.delete(ALL)
        # Draw connections first so circles get drawn on top of lines
        self.draw_connections()
        self.draw_users()

    def init_users(self):
        """Initializes list of VisualUser objects from users"""
        for user in self.raw_users:
            self.users.append(VisualUser(user, self))

    def update_locations(self):
        """Update locations of all users"""
        for user in self.users:
            user.update_location()

    def get_fill(self, v):
        """
        Convert version number into RGB hex value

        Creates gradient covering range of colors
        """
        if v is None:
            return "white"
        b = 0
        quarter = self.versions/4
        if v < quarter:  # Red -> Yellow
            r = 255
            g = int(255*min((v/quarter), 1))
        elif quarter <= v < 2*quarter:  # Yellow -> Green
            r = int(255*max(0, (1-(v-quarter)/quarter)))
            g = 255
        elif 2*quarter <= v < 3*quarter:  # Green -> Blue
            r = 0
            g = int(255*max(0, (1-(v-2*quarter)/quarter)))
            b = int(255*min(((v-2*quarter)/quarter), 1))
        else:  # Blue -> Purple
            g = 0
            r = int(255*min(((v-3*quarter)/quarter), 1))
            b = 255
        return "#{:02x}{:02x}{:02x}".format(r, g, b)

    def draw_random_point(self):
        """Draw randomly colored point on screen"""
        fill = self.get_fill(self.start_counter % 100)
        self.start_counter += 1
        x = random.randint(0, self.width)
        y = random.randint(0, self.height)
        self.canvas.create_rectangle(x, y, x+2, y+2, width=0, fill=fill)

    def timer_fired(self):
        """Called every frame refresh"""
        if self.mode == Mode.START:
            for _ in range(10):
                self.draw_random_point()
        if self.mode == Mode.MAIN and not self.paused:
            self.update_locations()
            self.redraw_all()

    def timer(self):
        """Setup timer loop"""
        self.timer_fired()
        self.canvas.after(self.timer_delay, self.timer)

    def init_animation(self):
        """Initialize or reset animation"""
        self.users = []
        self.timer_delay = 100
        self.start_counter = 0
        self.versions = 40
        self.default_users = 20
        self.default_coaches = 5
        self.default_students = 5
        self.max_users = 100
        self.version = None
        self.paused = False
        self.mode = Mode.START
        self.draw_start_screen()
        self.error_text = None
        self.error_font_size = 20
        self.version_select = None
        self.timer()

    def start_infection(self):
        """Initialize users and start infections"""
        num_users_text = self.num_users_entry.get()
        num_coaches_text = self.num_coaches_entry.get()
        num_students_text = self.num_students_entry.get()
        try:
            error = "Invalid Number of Users"
            num_users = int(num_users_text)
            if not (1 <= num_users <= self.max_users):
                raise ValueError
            num_coaches = int(num_coaches_text)
            error = "Invalid Number of Coaches"
            if not (1 <= num_coaches <= num_users):
                raise ValueError
            error = "Invalid Number of Students"
            num_students = int(num_students_text)
            if not (1 <= num_students <= num_users):
                raise ValueError
        except ValueError:
            if self.error_text:
                self.canvas.delete(self.error_text)
            self.error_text = \
                self.canvas.create_text(self.cx, 0.2*self.cy,
                                        text=error,
                                        font=("Impact", self.error_font_size))
            self.error_font_size += 2
            return
        self.infection = Infection(num_users=num_users, num_coaches=num_coaches,
                                   students=(1, num_students))
        self.num_users = num_users
        self.num_coaches = num_coaches
        self.num_students = num_students
        self.raw_users = self.infection.network.users
        self.init_users()
        self.draw_toolbar()
        self.mode = Mode.MAIN

    def limited_infection(self):
        size_text = self.limited_entry.get()
        try:
            size = int(size_text)
            if not (1 <= size <= self.num_users):
                raise ValueError
        except ValueError:
            print("Bad input")  # TODO: display to user
            return
        self.infection.limited_infection(size, self.version)
        print("Limited infection of size", size, self.num_users)

    def select_version(self):
        if self.version_select:  # Erase old selection
            self.toolbar.delete(self.version_select)
        if self.version is None:
            return
        y0, y1 = self.gradient
        x0, x1 = self.version*self.side, (self.version + 1)*self.side
        self.version_select = \
            self.toolbar.create_rectangle(x0, y0, x1, y1, width="2")

    def mouse_event(self, e):
        """Process click event"""
        x, y = e.x, e.y
        if self.mode == Mode.SETUP:
            if self.button.clicked(x, y):
                self.start_infection()
        if self.mode == Mode.MAIN:
            cx, cy, r = self.limited_button
            if distance(cx, cy, x, y) < r:
                self.limited_infection()
            elif self.gradient[0] <= y <= self.gradient[1]:
                print("gradient bar", x)
                self.version = int(x / self.side)
                print(self.versions, self.version)
                self.select_version()
            else:
                for user in self.users:
                    if user.clicked(x, y):
                        print("user clicked", user)
                        user.infect()
                        break

    def key_event(self, e):
        """Process keyboard event"""
        if e.keysym == 'r':
            self.init_animation()
            self.paused = False
        elif e.keysym == 'p':
            self.paused = not self.paused
        elif e.keysym == 's' and self.mode == Mode.START:
            self.mode = Mode.SETUP
            self.draw_setup_screen()
        elif e.keysym == 'b' and self.mode == Mode.SETUP:
            self.start_infection()
        elif e.keysym == 'q':
            self.root.destroy()
示例#14
0
class Gem:
	def __init__(self):
		self.frame = Tk();
		self.frame.resizable(False, False)

		self.status = 1
		self.scorePlayerA = 0
		self.scorePlayerB = 0

		self.scoreRoundA = 0
		self.scoreRoundB = 0

		self.countRound = 0
		self.quitMatch = 0
		self.isQuitRound = 0

		self.canvas_after_2 = 0
		self.canvas_after_1 = 0
		self.isPause = 0

		#register event
		self.frame.bind("<F4>", self.quitGame)
		self.frame.bind("<F5>", self.pauseGame)
		self.frame.protocol("WM_DELETE_WINDOW", self.on_closing)

		self.registerKeyboard()

	def setName(self, title):
		self.frame.title(title)

	def setBall(self, ball):
		self.ball = ball

	def setLeftBar(self, bar):
		self.leftBar = bar

	def setRightBar(self, bar):
		self.rightBar = bar

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

	def getFrame(self):
		return self.frame;

	def getCanvas(self):
		return self.canvas

	def setSize(self, size):
		self.frame.geometry(("%dx%d")%(size[0], size[1]))
		self.frame.update()

	def getSize(self):
		return (self.frame.winfo_width(), self.frame.winfo_height())

	def setBackground(self, color):
		self.background = color

	def setPlayers(self, players):
		self.players = players

	def setScoreBoard(self):
		players = self.players
		size = self.getSize()
		mid = round(size[0]/2)
		# Board
		self.canvas.create_rectangle(mid - 100, 0, mid + 100, 35, fill="grey58", outline="white", tag="boarda")

		# Player name 1
		self.canvas.create_text(mid - 80, 15, text=players[0], fill="magenta2", tag="boardb")

		# Round score 1
		r1 = players[0]+"a"
		self.canvas.create_text(mid - 80, 28, text="0", fill="pale green", tag="scoreplayera")

		# Player name 2
		self.canvas.create_text(mid + 80, 15, text=players[1], fill="magenta2", tag="boardc")

		# Round score 2
		self.canvas.create_text(mid + 80, 28, text="0", fill="pale green", tag="scoreplayerb")

		# Box score 1
		self.canvas.create_rectangle(mid - 50, 5, mid - 10, 25, fill="thistle3", outline="white", tag="boardd")

		# Score 1
		self.canvas.create_text(mid - 30, 15, text="000", fill="cyan", tag=players[0])

		# Box score 2
		self.canvas.create_rectangle(mid + 10, 5, mid + 50, 25, fill="thistle3", outline="white", tag="boarde")

		# Score 2
		self.canvas.create_text(mid + 30, 15, text="000", fill="cyan", tag=players[1])

		self.canvas.pack()
		self.frame.update()

	def clearScoreBoard(self):
		self.canvas.delete(self.players[0])
		self.canvas.delete(self.players[1])
		self.canvas.delete("boarda")
		self.canvas.delete("boardb")
		self.canvas.delete("boardc")
		self.canvas.delete("boardd")
		self.canvas.delete("boarde")
		self.canvas.delete("scoreplayera")
		self.canvas.delete("scoreplayerb")
		self.canvas.update()

	def initCanvas(self):
		canvas_width = self.frame.winfo_width()
		canvas_height = self.frame.winfo_height()
		self.canvas = Canvas(self.frame, width=canvas_width, height=canvas_height, bg=self.background)
		self.frame.update()

	def setDashboard(self):
		size = self.getSize();
		midw = round(size[0]/2)
		midh = round(size[1]/2)
		self.canvas.create_oval(midw - 120, midh - 70, midw + 120, midh+70, fill="alice blue", outline="white", tag="dash1")
		self.canvas.create_text(midw, midh - 35, text="F1: Machine Vs Machine", fill="blue violet", tag="dash2")
		self.canvas.create_text(midw, midh - 10, text="F2: Human Vs Machine  ", fill="blue violet", tag="dash3")
		self.canvas.create_text(midw, midh + 15, text="F3: Human Vs Human     ", fill="blue violet", tag="dash4")
		self.canvas.create_text(midw, midh + 38, text="F4: Quit Game                  ", fill="blue violet", tag="dash5")
		self.canvas.pack()

	def clearDashboard(self):
		self.canvas.delete("dash1")
		self.canvas.delete("dash2")
		self.canvas.delete("dash3")
		self.canvas.delete("dash4")
		self.canvas.delete("dash5")
		self.canvas.update()

	def setWinter(self, status = -1):
		size = self.getSize();
		midw = round(size[0]/2)
		midh = round(size[1]/2)

		if status == 1:
			textstr = self.players[0] + " Win"
		elif status == 2:
			textstr = self.players[1] + " Win"
		elif self == 3 and self.scorePlayerA != self.scorePlayerB:
			if self.scoreRoundB > self.scorePlayerA:
				textstr = self.players[1] + " Win"
			else:
				textstr = self.players[0] + " Win"
		else:
			textstr = "Not Match"

		self.canvas.create_oval(midw - 50, midh - 20, midw + 50, midh+20, fill="alice blue", outline="white", tag="wintera")
		self.canvas.create_text(midw, midh, text=textstr, fill="blue violet", tag="winterb")

		self.canvas.pack()
		self.canvas.update();

	def clearWinter(self):
		self.canvas.delete("wintera")
		self.canvas.delete("winterb")
		self.canvas.update()

	def quitRound(self, status):
		if self.scorePlayerA >= self.maxRoundScore and self.scorePlayerB >= self.maxRoundScore:
			self.isQuitRound = 1
		if status == 1 or status == 2 or self.isQuitRound == 1 or self.quitMatch == 1:
			if self.isQuitRound == 0:
				self.updateScoreRound(status - 1)
			self.isQuitRound = 1
			self.ball.quit(self.canvas)
			self.leftBar.quit(self.canvas)
			self.rightBar.quit(self.canvas)
		return self.isQuitRound

	def nextRound(self, status):
		self.canvas.after_cancel(self.canvas_after_2)
		if status == 2 or status == 1:
			if self.maxRound > self.countRound:
				#self.ball.quit(self.canvas)
				#self.leftBar.quit(self.canvas)
				#self.rightBar.quit(self.canvas)
				self.resetRound()
				self.countRound += 1
				self.leftBar.reset(self.canvas)
				self.rightBar.reset(self.canvas)
				if status == 1:
					self.leftBar.transferBall(self.canvas, self.ball)
				else:
					self.leftBar.transferBall(self.canvas, self.ball)
				#print(self.canvas.find_withtag(self.ball.name))
			else:
				self.stopMatch()

	def play(self, event):
		self.clearDashboard()
		self.unRegisterKeyboard()

		if event.keycode == 112:
			self.isPause = 4
			self.startMatch()
			self.machineVSmachine()
		elif event.keycode == 113:
			self.isPause = 5
			self.leftBar.registerKeyboard(self.frame)
			self.startMatch()
			self.machineVShuman()
		elif event.keycode == 114:
			self.isPause = 6
			self.leftBar.registerKeyboard(self.frame)
			self.rightBar.registerKeyboard(self.frame)
			self.startMatch()
			self.humanVShuman()

	def machineVSmachine(self):
		try:
			if self.ball.exists == False:
				self.isQuitRound = 0
			if self.isQuitRound == 0:
				rs = self.ball.move(self.canvas)
				self.leftBar.autoMove(self.canvas)
				self.rightBar.autoMove(self.canvas)

				rs = self.update(rs)
				if rs == 1:
					return ;
			self.canvas_after_1 = self.canvas.after(10, self.machineVSmachine)
		except:
			print("I am so sorry!")
			self.stopMatch(0)

	def machineVShuman(self):
		try:
			if self.ball.exists == False:
				self.isQuitRound = 0

			if self.isQuitRound == 0:
				rs = self.ball.move(self.canvas)
				self.leftBar.move(self.canvas)
				self.rightBar.autoMove(self.canvas)

				rs = self.update(rs)
				if rs == 1:
					return ;
			self.canvas_after_1 = self.canvas.after(10, self.machineVShuman)
		except:
			print("I am so sorry!")
			self.stopMatch(0)

	def humanVShuman(self):
		try:
			if self.ball.exists == False:
				self.isQuitRound = 0
			if self.isQuitRound == 0:
				rs = self.ball.move(self.canvas)
				self.leftBar.move(self.canvas)
				self.rightBar.move(self.canvas)

				rs = self.update(rs)
				if rs == 1:
					return ;
			self.canvas_after_1 = self.canvas.after(10, self.humanVShuman)
		except:
			print("I am so sorry!")
			self.stopMatch(0)

	def startMatch(self):
		self.setScoreBoard()
		self.quitMatch = 0
		self.isQuitRound = 0
		self.countRound = 0
		self.nextRound(1)

	def resetRound(self):
		self.scorePlayerA = 0
		self.scorePlayerB = 0
		self.isQuitRound = 0
		self.updateScorePlayer()
		self.leftBar.registerKeyboard(self.frame)
		self.rightBar.registerKeyboard(self.frame)

	def update(self, status):
		self.updateScorePlayer(status-3)

		self.canvas.update()
		if self.quitRound(status) == 1 and self.quitMatch == 0:
			self.leftBar.unRegisterKeyboard(self.frame)
			self.rightBar.unRegisterKeyboard(self.frame)
			self.canvas_after_2 = self.canvas.after(800, self.nextRound, status)
		if self.quitMatch == 1:
			self.leftBar.unRegisterKeyboard(self.frame)
			self.rightBar.unRegisterKeyboard(self.frame)
			self.isQuitRound == 1
		return self.quitMatch

	def updateScoreRound(self, status):
		if self.scorePlayerB == 0 and self.scorePlayerA == 0:
			return
		if status == 0:
			self.scoreRoundA += 1
			self.canvas.itemconfig("scoreplayera", text=self.scoreRoundA)
		elif status == 1:
			self.scoreRoundB += 1
			self.canvas.itemconfig("scoreplayerb", text=self.scoreRoundB)

	def updateScorePlayer(self, status = 5):
		if status == 0:
			self.scorePlayerA += 1
			self.canvas.itemconfig(self.players[0], text=self.__countScore(self.scorePlayerA))
			if self.scorePlayerA != 0 and self.scorePlayerA % 5 == 0:
				self.ball.speed +=1
		elif status == 1:
			self.scorePlayerB += 1
			self.canvas.itemconfig(self.players[1], text=self.__countScore(self.scorePlayerB))
		elif status == 5:
			self.canvas.itemconfig(self.players[0], text=self.__countScore(self.scorePlayerA))
			self.canvas.itemconfig(self.players[1], text=self.__countScore(self.scorePlayerB))

		self.canvas.update()

	def __countScore(self, score):
		if score < 10:
			scorestr = "00" + str(score);
		elif score < 100:
			scorestr = "0" + str(score)
		else:
			scorestr = str(score)
		return scorestr

	def stopMatch(self, event = 0):
		self.isQuitRound = 1
		self.quitMatch = 1
		self.leftBar.unRegisterKeyboard(self.frame)
		self.rightBar.unRegisterKeyboard(self.frame)
		self.canvas.after_cancel(self.canvas_after_1);
		self.canvas_after_3 = self.canvas.after(500, self.returnMenu)

	def quitGame(self, event):
		self.isQuitRound = 1
		self.quitMatch = 1
		self.leftBar.unRegisterKeyboard(self.frame)
		self.rightBar.unRegisterKeyboard(self.frame)
		self.canvas.after_cancel(self.canvas_after_1);
		self.canvas_after_3 = self.canvas.after(200, self.destroy)

	def destroy(self):
		self.canvas.after_cancel(self.canvas_after_3)
		self.frame.destroy()

	def returnMenu(self):
		self.canvas.after_cancel(self.canvas_after_3)
		self.ball.quit(self.canvas)
		self.leftBar.quit(self.canvas)
		self.rightBar.quit(self.canvas)
		self.clearScoreBoard()
		self.clearWinter()
		self.setDashboard()
		self.registerKeyboard()

	def setMaxRound(self, max):
		self.maxRound = max

	def setMaxRoundScore(self, max):
		self.maxRoundScore = max

	def registerKeyboard(self):
		self.frame.bind("<F1>", self.play)
		self.frame.bind("<F2>", self.play)
		self.frame.bind("<F3>", self.play)
		self.frame.unbind("<Escape>")

	def unRegisterKeyboard(self):
		self.frame.unbind("<F1>")
		self.frame.unbind("<F2>")
		self.frame.unbind("<F3>")
		self.frame.bind("<Escape>", self.stopMatch)

	def on_closing(self):
		self.quitGame(0)
	def pauseGame(self, event):
		if self.isPause == 1:
			self.isPause += 3
			self.machineVSmachine()
		elif self.isPause == 2:
			self.isPause += 3
			self.machineVShuman()
		elif self.isPause == 3:
			self.isPause += 3
			self.humanVShuman()
		elif self.isPause > 3:
			self.canvas.after_cancel(self.canvas_after_1)
			self.isPause -= 3
示例#15
0
文件: collision.py 项目: obiejuan/101
class Painter:
    def __init__(
        self, root, width=800, height=600, offset=5, min_radius=5, max_radius=10, num_balls=20, refresh_speed=5
    ):

        # Draw frame etc
        self.app_frame = Frame(root)
        self.app_frame.pack()
        self.canvas = Canvas(self.app_frame, width=width, height=height)
        self.canvas_size = (int(self.canvas.cget("width")), int(self.canvas.cget("height")))
        self.canvas.pack()
        self.refresh_speed = refresh_speed

        # Work area
        self.min_x = offset
        self.max_x = width - offset
        self.min_y = offset
        self.max_y = height - offset

        self.num_balls = num_balls
        self.balls = []
        self.ball_handles = dict()
        self.init_balls(max_radius, min_radius, num_balls)

        self.time = 0

        self.wall_collision_times = np.zeros(num_balls)
        self.init_wall_collision_times()

        self.ball_collision_times = np.zeros((num_balls, num_balls))
        self.init_ball_collision_times()

        self.draw()
        self.refresh()
        return

    def init_balls(self, max_radius, min_radius, num_balls):
        for i in np.arange(num_balls):
            while True:
                radius = (max_radius - min_radius) * rand.random_sample() + min_radius

                ball_min_x = self.min_x + radius
                ball_max_x = self.max_x - radius
                x = (ball_max_x - ball_min_x) * rand.random_sample() + ball_min_x

                ball_min_y = self.min_y + radius
                ball_max_y = self.max_y - radius
                y = (ball_max_y - ball_min_y) * rand.random_sample() + ball_min_y

                vx = rand.random_sample()
                vy = rand.random_sample()

                mass = rand.random_sample()
                new_ball = Ball(radius, x, y, vx, vy, mass)

                if not new_ball.check_overlap(self.balls):
                    self.balls.append(new_ball)
                    break

    def draw(self):
        # Draw walls
        self.canvas.create_line((self.min_x, self.min_y), (self.min_x, self.max_y), fill="red")
        self.canvas.create_line((self.min_x, self.min_y), (self.max_x, self.min_y), fill="red")
        self.canvas.create_line((self.min_x, self.max_y), (self.max_x, self.max_y), fill="red")
        self.canvas.create_line((self.max_x, self.min_y), (self.max_x, self.max_y), fill="red")
        # Draw balls
        for b in self.balls:
            obj = self.canvas.create_oval(b.x - b.radius, b.y - b.radius, b.x + b.radius, b.y + b.radius)
            self.ball_handles[b] = obj
        self.canvas.update()

    def next_wall_collision_idx(self):
        collided = []
        for i in np.arange(self.num_balls):
            if self.wall_collision_times[i] <= self.time:
                collided.append(i)
        return collided

    def next_ball_collision_idx(self):
        min_i = 0
        min_j = 0
        collided = []
        # min_tij = float('inf')
        for i in np.arange(self.num_balls):
            for j in np.arange(i, self.num_balls):
                tij = self.ball_collision_times[i][j]
                if tij <= self.time:
                    collided.append((i, j))
        return collided

    # CODE YOU NEED TO IMPLEMENT
    def init_wall_collision_times(self):
        for i in np.arange(self.num_balls):
            self.wall_collision_times[i] = self.balls[i].compute_wall_collision_time(
                self, self.min_x, self.max_x, self.min_y, self.max_y
            )

    #    def update_wall_collision_time(self, i):
    #
    def init_ball_collision_times(self):
        for i in np.arange(self.num_balls):
            for j in np.arange(self.num_balls):
                self.ball_collision_times[i] = self.balls[i].compute_ball_collision_time(self, other)

    #
    #    def update_ball_collision_time(self, i):

    # Do not update this
    def refresh(self):
        wall_i = self.next_wall_collision_idx()
        ball_i = self.next_ball_collision_idx()
        # print wall_i, ball_i
        for i in wall_i:
            bi = self.balls[i]
            old_x = bi.x
            old_y = bi.y
            bi.collide_with_wall(self.min_x, self.max_x, self.min_y, self.max_y)
            self.canvas.move(self.ball_handles[bi], bi.x - old_x, bi.y - old_y)

        for (i, j) in ball_i:
            bi = self.balls[i]
            bj = self.balls[j]
            bi.collide_with_ball(bj)

        collided = wall_i
        for (i, j) in ball_i:
            collided.append(i)
            collided.append(j)

        collided = set(collided)
        # print collided

        for i in collided:
            self.update_ball_collision_time(i)
            self.update_wall_collision_time(i)

        not_collided = set(np.arange(self.num_balls)) - collided

        for i in not_collided:
            bi = self.balls[i]
            old_x = bi.x
            old_y = bi.y
            bi.move()
            self.canvas.move(self.ball_handles[bi], bi.x - old_x, bi.y - old_y)

        self.time += 1
        self.canvas.update()
        self.canvas.after(self.refresh_speed, self.refresh)  # Calls the function again
示例#16
0
            can.delete(line1[int(y/50)])
            can.delete(line2[int(y/50)])
            line1[int(y/50)] = [can.create_line(pos1, fill='#000')]
            line2[int(y/50)] = [can.create_line(pos2, fill='#f00',
                                dash=(3, 2))]
        can.update()

"""
본문
캔버스를 선언하고 원과 선들을 초기화
"""
master = Tk()
can = Canvas(master, width=500, height=500)
obj = can.create_oval(240, 240, 260, 260, fill='#aafcdf')
can.pack()

# 라인 초기화
line1 = [can.create_line(0, 0, 1, 1)]*11
line2 = [can.create_line(0, 0, 1, 1)]*11

# 애니메이션 구동
can.after(0, web)
onTarget = False

# bind: 미리 정해져 있는 입력에 따라서 함수를 실행
# 사용자의 드래그 동작은 클릭과 클릭한 후 이동으로 구성되어 있다.
can.bind('<Button-1>', onClick)
can.bind('<B1-Motion>', onDrag)

master.mainloop()
示例#17
0
              len(population.cars[population.max_fit_car].brain.connections))
        # print("Connections checkpoints:", population.cars[population.max_fit_car].checkpoints)
        print("Reproducing...")
        population.reproduction()
        print("Species: ", population.neat.species)
        print("Garbage collecting")
        gc.collect()
        print(len(population.neat.neurons))
        print(len(population.neat.connections))
        print("--------------------------------------------------------")
        print(f"Starting generation {generation}!")

    time = 0
    if step % 10 == 0: time = 1
    canvas.after(time, update)


if __name__ == "__main__":
    window = Tk()
    canvas = Canvas(window)
    for w in route_walls:
        canvas.create_line(w.x1, w.y1, w.x2, w.y2)

    for w in checkpoints:
        canvas.create_line(w.x1, w.y1, w.x2, w.y2, fill="green")

    canvas.pack(fill=BOTH, expand=1)
    canvas.after(1000, update)
    window.mainloop()

# Possible futura GUI amb tkinter
示例#18
0
class SearchFrame:
    def __init__(self, logicManger, root):
        self.logicManager = logicManger
        # images setup
        self.backgroundImg = None
        self.connectImg = None
        self.backImg = None
        self.initPictures()
        # frame setup
        self.frame = None
        self.clients_list = None
        self.connect_button = None
        self.back_button = None
        self.timeUpdateMobileList = 1000  # in ms
        self.initFrame(root)

    def initPictures(self):
        self.backgroundImg = getPhoto('\\img\\ConnectScreen.png')
        self.connectImg = getPhoto('\\img\\MouseButton.png')
        self.backImg = getPhoto('\\img\\BackButton.png')

    def initFrame(self, root):
        self.frame = Canvas(root, bg=DARK_BLUE)
        self.frame.create_image(0, 0, anchor=NW, image=self.backgroundImg)
        self.frame.pack(expand="true", fill="both")
        padyClients = (200, 0)
        padyButtons = 4
        padx = (35, 0)
        y_grid = 0
        y_grid = self.initClients(self.frame, y_grid, padyClients, padx)
        self.initButtons(self.frame, y_grid, 0, padx, padyButtons)
        self.frame.after(self.timeUpdateMobileList, self.addClient)

    def initClients(self, frame, y_grid, pady, padx):
        rapper_frame = Frame(frame, bg=GRAY_BLUE)
        rapper_frame.grid(row=y_grid,
                          column=0,
                          rowspan=1,
                          columnspan=4,
                          padx=padx,
                          pady=pady)
        label = Label(rapper_frame,
                      text='Select your Smartphone',
                      width=23,
                      font=("Calibri", 14),
                      bg=DARK_GRAY_BLUE,
                      fg=WHITE)
        label.pack(side="top")
        self.clients_list = Listbox(rapper_frame,
                                    width=25,
                                    height=9,
                                    bd=0,
                                    font=("Calibri", 12))
        # set the listbox contains func
        self.clients_list.contains = lambda x: x in self.clients_list.get(
            0, "end")
        self.clients_list.pack(side="left", fill="y", padx=(2, 0), pady=2)
        scrollbar = Scrollbar(rapper_frame, orient="vertical")
        scrollbar.config(command=self.clients_list.yview)
        scrollbar.pack(side="right", fill="y", padx=(0, 2), pady=2)
        self.clients_list.config(yscrollcommand=scrollbar.set)
        return y_grid + 1

    def initButtons(self, frame, y_grid, x_grid, padx, pady):
        self.connect_button = Button(frame,
                                     image=self.connectImg,
                                     bg=GRAY,
                                     font=SMALL_BUTTON_FONT)
        self.connect_button.grid(row=y_grid,
                                 column=x_grid,
                                 rowspan=1,
                                 padx=padx,
                                 pady=pady)
        x_grid = x_grid + 3
        self.back_button = Button(frame,
                                  image=self.backImg,
                                  bg=GRAY,
                                  font=SMALL_BUTTON_FONT)
        self.back_button.grid(row=y_grid,
                              column=x_grid,
                              rowspan=1,
                              padx=5,
                              pady=pady)

    def setBackButtonFunction(self, func):
        self.back_button["command"] = func

    def setConnectionSelectFunction(self, func):
        def select():
            index = self.clients_list.curselection()
            connection = self.clients_list.get(index)
            # empty tuple whike return false
            if connection:
                func(connection)

        self.connect_button["command"] = select

    def addClient(self):
        connections = self.logicManager.getConnections()
        for connection in connections.values():
            if not self.clients_list.contains(connection):
                index = self.clients_list.size()
                self.clients_list.insert(index, str(connection))
        self.frame.after(self.timeUpdateMobileList, self.addClient)

    def hideFrame(self):
        self.frame.pack_forget()
示例#19
0
class Painter:
    #__init__ performs the construction of a Painter object
    def __init__(self,
                 root,
                 scale=500,
                 border=5,
                 refresh_speed=5,
                 filename='balls.txt',
                 min_radius=5,
                 max_radius=10,
                 num_balls=20):
        #width and height are used to set the simulation borders
        width = scale + border
        height = scale + border
        #Time is the time stamp for the simulation; it is set to 0 to indicate the beginning of the simulation
        self.time = 0
        #setup will set up the necessary graphics window and the ball list
        self.setup(root, width, height, border, refresh_speed)
        #Check the input parameter 'filename' to load predetermined simulation
        #otherwise set up the default simulation
        if filename is None:
            self.init_balls(max_radius, min_radius, num_balls)
            self.num_balls = num_balls
        else:
            self.num_balls = self.read_balls(scale, filename)
        #Create the priority data structure
        self.PQ = ArrayPQ(self.num_balls)
        #Initialize all possible collision times
        self.init_ball_collision_times()
        self.init_wall_collision_times()
        #draw will draw the graphics to the window
        self.draw()
        #refresh is a loop method intended to create animations
        self.refresh()
        #A blank return indicates the end of the function
        return

    #setup creates the window to display the graphics along with the red border
    #of the simulation
    def setup(self, root, width, height, border, refresh_speed):
        # Draw frame etc
        self.app_frame = Frame(root)
        self.app_frame.pack()
        self.canvas = Canvas(self.app_frame, width=width, height=height)
        self.canvas_size = (int(self.canvas.cget('width')),
                            int(self.canvas.cget('height')))
        self.canvas.pack()
        self.refresh_speed = refresh_speed

        # Work area
        self.min_x = border
        self.max_x = width - border
        self.min_y = border
        self.max_y = height - border
        #create array to hold the n number of balls
        self.balls = []
        self.ball_handles = dict()

        return

    #This function reads in predefined ball numbers and locations to implement predetermined simulations
    def read_balls(self, scale, filename):
        f = open(filename)
        num_balls = int(f.readline().strip())

        for l in f:
            ll = l.strip().split(" ")
            x = scale * float(ll[0])
            y = scale * float(ll[1])
            vx = scale * float(ll[2])
            vy = scale * float(ll[3])
            radius = scale * float(ll[4])
            mass = float(ll[5])
            r = int(ll[6])
            g = int(ll[7])
            b = int(ll[8])
            tk_rgb = "#%02x%02x%02x" % (r, g, b)
            new_ball = Ball(radius, x, y, vx, vy, mass, tk_rgb)
            self.balls.append(new_ball)
        return num_balls

    #init_balls will create an array of size "num_balls" stored within self.balls
    def init_balls(self, max_radius, min_radius, num_balls):
        for i in np.arange(num_balls):
            while (True):
                radius = (max_radius -
                          min_radius) * rand.random_sample() + min_radius

                ball_min_x = self.min_x + radius
                ball_max_x = self.max_x - radius
                x = (ball_max_x -
                     ball_min_x) * rand.random_sample() + ball_min_x

                ball_min_y = self.min_y + radius
                ball_max_y = self.max_y - radius
                y = (ball_max_y -
                     ball_min_y) * rand.random_sample() + ball_min_y

                vx = rand.random_sample()
                vy = rand.random_sample()

                mass = 1.0  # rand.random_sample()
                new_ball = Ball(radius, x, y, vx, vy, mass)

                if not new_ball.check_overlap(self.balls):
                    self.balls.append(new_ball)
                    break

    #init_wall_collision_times will set all of the balls' minimum collision time
    #for both horizontal and vertical walls and store that time in their respective arrays
    def init_wall_collision_times(self):
        for i in np.arange(len(self.balls)):
            bi = self.balls[i]
            tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
            tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
            self.PQ.insert(i, -1, tix + self.time, self.balls[i].count, -1)
            self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
        return

    #init_ball_collision_times will set all of the balls' minimum collision time
    #with all other balls and store that time within the ith and jth index of
    #PQ.ball_collision_time
    def init_ball_collision_times(self):
        for i in np.arange(self.num_balls):
            bi = self.balls[i]
            for j in np.arange(i + 1, self.num_balls):
                bj = self.balls[j]
                tij = bi.ball_collision_time(bj)
                self.PQ.insert(i, j, tij + self.time, self.balls[i].count,
                               self.balls[j].count)
                # self.ball_collision_times[i][j] = tij
                # self.ball_collision_times[j][i] = tij
        return

    #update collision times is meant to update collision times of ball i with all
    #walls (horizontal and vertical) and all other balls within the PQ array
    def update_collision_times(self, i):
        bi = self.balls[i]
        tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
        tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
        self.PQ.insert(i, -1, tix + self.time, self.balls[i].count, -1)
        self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
        for j in np.arange(self.num_balls):
            bj = self.balls[j]
            tij = bi.ball_collision_time(bj) + self.time
            if i > j:
                self.PQ.insert(j, i, tij, self.balls[j].count,
                               self.balls[i].count)
            else:
                self.PQ.insert(i, j, tij, self.balls[i].count,
                               self.balls[j].count)
        return

    #draw will draw the borders and all balls within self.balls
    def draw(self):
        #Draw walls
        self.canvas.create_line((self.min_x, self.min_y),
                                (self.min_x, self.max_y),
                                fill="red")
        self.canvas.create_line((self.min_x, self.min_y),
                                (self.max_x, self.min_y),
                                fill="red")
        self.canvas.create_line((self.min_x, self.max_y),
                                (self.max_x, self.max_y),
                                fill="red")
        self.canvas.create_line((self.max_x, self.min_y),
                                (self.max_x, self.max_y),
                                fill="red")
        #Draw balls
        for b in self.balls:
            obj = self.canvas.create_oval(b.x - b.radius,
                                          b.y - b.radius,
                                          b.x + b.radius,
                                          b.y + b.radius,
                                          outline=b.tk_rgb,
                                          fill=b.tk_rgb)
            self.ball_handles[b] = obj
        self.canvas.update()

    #refresh is called to update the state of the simulation
    #-each refresh call can be considered one iteration of the simulation
    #-all balls will be moved and if there is a collision then it will be computed
    def refresh(self):
        #get the next collision
        i, j, t, num_collisions_i, num_collision_j = self.PQ.get_next()
        #gather the current collisions of the ith and jth ball
        current_collisions_i = self.balls[i].count
        current_collisions_j = self.balls[j].count

        #Check the difference in time between the predicted collision time and
        #the current time stamp of the simulation
        delta = t - self.time
        #If the difference is greater than 1, then just move the balls
        if delta > 1.0:
            # cap delta to 1.0
            for bi in self.balls:
                bi.move()
                self.canvas.move(self.ball_handles[bi], bi.vx, bi.vy)
            self.time += 1.0
        #Otherwise a collision has occurred
        else:
            #Move all balls
            for bi in self.balls:
                bi.move(delta)
                self.canvas.move(self.ball_handles[bi], bi.vx * delta,
                                 bi.vy * delta)
            #increment the simulation time stamp
            self.time += delta
            #Delete the top element within the Priority Queue
            self.PQ.delete()
            #if i is -1 then this indicates a collision with a vertical wall
            #also this if statement checks if the number of collisions recorded
            #when the collision returned by PQ.get_next() is equal to the
            #number of collisions within the jth ball
            #this acts as a test to check if the collision is still valid
            if i == -1 and num_collision_j == current_collisions_j:
                #compute what happens from the vertical wall collision
                self.balls[j].collide_with_vertical_wall()
                #update collision times for the jth ball
                self.update_collision_times(j)
            #if j is -1 then this indicates a collision a horizontal wall
            #while also checking if the number of collisions match
            #to see if the collision is valid
            elif j == -1 and num_collisions_i == current_collisions_i:
                #compute what happens from the horizontal wall collision
                self.balls[i].collide_with_horizontal_wall()
                #update collision times for the ith ball
                self.update_collision_times(i)
            #Otherwise i and j are not equal to -1 indicating that the collision is between two balls
            #check if no collisions have occurred between both balls before the collision returned from PQ.get_next
            #if true then this means that the collision is still valid and must be executed
            elif num_collision_j == current_collisions_j and num_collisions_i == current_collisions_i:
                #Execute collision across the ith and jth ball
                self.balls[i].collide_with_ball(self.balls[j])
                #update collision times for both the ith and jth ball
                self.update_collision_times(i)
                self.update_collision_times(j)

        #update the canvas to draw the new locations of each ball
        self.canvas.update()

        self.canvas.after(self.refresh_speed,
                          self.refresh)  #Calls the function again
示例#20
0
class Graphics:
    """
    Wraps tk graphics primitives to make graphics concepts easier for beginners.
    """
    def __init__(self, w, h):
        self.tk = Tk()
        self.width = w
        self.height = h
        self.canvas = Canvas(self.tk, width=self.width, height=self.height)
        self.canvas.pack()

    def circle(self, center, radius, **kwargs):
        x, y = center
        self.checkbounds([(x - radius, y - radius), (x + radius, y + radius)])

        return self.canvas.create_oval(x - radius, y - radius, x + radius,
                                       y + radius, kwargs)

    def show_grid(self, size=50, color='black'):
        w = self.width  # Get current width of canvas
        h = self.height  # Get current height of canvas

        # Creates all vertical lines at intevals of 100
        for i in range(0, w + size, size):
            self.line((i, 0), (i, h), fill=color, tag='grid_line')
            label = Label(self.canvas, text=str(i), fg='red')
            x_off = 0
            if i > 0:
                x_off = 15
            if i == w:
                print("w....")
                x_off = 25
            label.place(x=i - x_off, y=0)

        # Creates all horizontal lines at intevals of 100
        for i in range(0, h + size, size):

            label = Label(self.canvas, text=str(i), fg='red')
            y_off = 0
            if i > 0:
                y_off = 15
            if i == h:
                y_off = 20
            label.place(x=0, y=i - y_off)
            self.line((0, i), (w, i), fill=color, tag='grid_line')

    def hide_grid(self):
        self.canvas.delete('grid_line')

    def rectangle(self, topleft, bottomright, **kwargs):

        self.checkbounds([topleft, bottomright])
        xmin, ymin, xmax, ymax = extent([topleft, bottomright])
        return self.canvas.create_rectangle(xmin, ymin, xmax, ymax, kwargs)

    def polygon(self, points, **kwargs):
        self.checkbounds(points)
        return self.canvas.create_polygon(points, kwargs)

    def line(self, a, b, **kwargs):
        self.checkbounds([a, b])
        xmin, ymin, xmax, ymax = extent([a, b])
        return self.canvas.create_line(xmin, ymin, xmax, ymax, kwargs)

    def coords(self, obj, *args):
        points = self.canvas.coords(obj, *args)
        coords = []
        for i in range(0, len(points), 2):
            coords.append((points[i], points[i + 1]))
        return coords

    def move(self, obj, delta):
        self.canvas.move(obj, delta[0], delta[1])

    def update(self, after=20):
        self.canvas.update()
        self.canvas.after(after)

    def show(self):
        self.tk.mainloop()

    def checkbounds(self, points):
        xmin, ymin, xmax, ymax = extent(points)

        if xmax > self.width:
            print(
                "WARNING:The shape extends beyond the canvas: x=%d is greater than canvas width %d"
                % (xmax, self.width))

        if xmin < 0:
            print("WARNING: The minimum boundary x=%d cannot be less than 0" %
                  xmin)

        if ymax > self.height:
            print(
                "WARNING:The shape extends beyond the canvas: y=%d is greater than window height %d "
                % (ymax, self.height))

        if ymin < 0:
            print("WARNING: The minimum boundary y=%d cannot be less than 0" %
                  ymin)
class Painter:
    #__init__ performs the construction of a Painter object
    def __init__(self, root, scale=500, border=5, refresh_speed=5, filename='balls.txt', min_radius=5, max_radius=10, num_balls=20):
        #width and height are used to set the simulation borders
        width = scale + border
        height = scale + border
        #Time is the time stamp for the simulation; it is set to 0 to indicate the beginning of the simulation
        self.time = 0
        #setup will set up the necessary graphics window and the ball list
        self.setup(root, width, height, border, refresh_speed)
        #Check the input parameter 'filename' to load predetermined simulation
        #otherwise set up the default simulation
        if filename is None:
            self.init_balls(max_radius, min_radius, num_balls)
            self.num_balls = num_balls
        else:
            self.num_balls = self.read_balls(scale, filename)
        #Create the priority data structure
        self.PQ = ArrayPQ(self.num_balls)
        #Initialize all possible collision times
        self.init_ball_collision_times()
        self.init_wall_collision_times()
        #draw will draw the graphics to the window
        self.draw()
        #refresh is a loop method intended to create animations
        self.refresh()
        #A blank return indicates the end of the function
        return

    #setup creates the window to display the graphics along with the red border
    #of the simulation
    def setup(self, root, width, height, border, refresh_speed):
        # Draw frame etc
        self.app_frame = Frame(root)
        self.app_frame.pack()
        self.canvas = Canvas(self.app_frame, width = width, height = height)
        self.canvas_size = (int(self.canvas.cget('width')), int(self.canvas.cget('height')))
        self.canvas.pack()
        self.refresh_speed = refresh_speed
        
        # Work area
        self.min_x = border
        self.max_x = width - border
        self.min_y = border
        self.max_y = height - border
        #create array to hold the n number of balls
        self.balls = []
        self.ball_handles = dict()        

        return

    #This function reads in predefined ball numbers and locations to implement predetermined simulations
    def read_balls(self, scale, filename):
        f = open(filename)
        num_balls = int(f.readline().strip())
        
        for l in f:
            ll = l.strip().split(" ")
            x = scale*float(ll[0])
            y = scale*float(ll[1])
            vx = scale*float(ll[2])
            vy = scale*float(ll[3])
            radius = scale*float(ll[4])
            mass = float(ll[5])
            r = int(ll[6])
            g = int(ll[7])
            b = int(ll[8])
            tk_rgb = "#%02x%02x%02x" % (r, g, b)            
            new_ball = Ball(radius, x, y, vx, vy, mass, tk_rgb)
            self.balls.append(new_ball)
        return num_balls
            
    #init_balls will create an array of size "num_balls" stored within self.balls
    def init_balls(self, max_radius, min_radius, num_balls):
        for i in np.arange(num_balls):
            while(True):
                radius = (max_radius - min_radius) * rand.random_sample() + min_radius

                ball_min_x = self.min_x + radius
                ball_max_x = self.max_x - radius
                x = (ball_max_x - ball_min_x)*rand.random_sample() + ball_min_x

                ball_min_y = self.min_y + radius
                ball_max_y = self.max_y - radius                
                y = (ball_max_y - ball_min_y)*rand.random_sample() + ball_min_y

                vx = rand.random_sample()
                vy = rand.random_sample()

                mass = 1.0 # rand.random_sample()
                new_ball = Ball(radius, x, y, vx, vy, mass)
                
                if not new_ball.check_overlap(self.balls):
                    self.balls.append(new_ball)
                    break

    #init_wall_collision_times will set all of the balls' minimum collision time
    #for both horizontal and vertical walls and store that time in their respective arrays
    def init_wall_collision_times(self):
        for i in np.arange(len(self.balls)):
            bi = self.balls[i]
            tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
            tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
            self.PQ.insert(i, -1, tix + self.time, self.balls[i].count, -1)
            self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
        return
    
    #init_ball_collision_times will set all of the balls' minimum collision time
    #with all other balls and store that time within the ith and jth index of
    #PQ.ball_collision_time
    def init_ball_collision_times(self):
        for i in np.arange(self.num_balls):
            bi = self.balls[i]
            for j in np.arange(i+1, self.num_balls):
                bj = self.balls[j]
                tij = bi.ball_collision_time(bj)
                self.PQ.insert(i, j, tij + self.time, self.balls[i].count, self.balls[j].count)
                # self.ball_collision_times[i][j] = tij
                # self.ball_collision_times[j][i] = tij
        return
    
    #update collision times is meant to update collision times of ball i with all
    #walls (horizontal and vertical) and all other balls within the PQ array
    def update_collision_times(self, i):
        bi = self.balls[i]
        tix = bi.horizontal_wall_collision_time(self.min_x, self.max_x)
        tiy = bi.vertical_wall_collision_time(self.min_y, self.max_y)
        self.PQ.insert(i, -1, tix + self.time,self.balls[i].count, -1)
        self.PQ.insert(-1, i, tiy + self.time, -1, self.balls[i].count)
        for j in np.arange(self.num_balls):
            bj = self.balls[j]
            tij = bi.ball_collision_time(bj) + self.time
            if i > j:
                self.PQ.insert(j, i, tij,self.balls[j].count,self.balls[i].count)
            else:
                self.PQ.insert(i, j, tij,self.balls[i].count, self.balls[j].count)
        return

    #draw will draw the borders and all balls within self.balls
    def draw(self):
        #Draw walls
        self.canvas.create_line((self.min_x, self.min_y), (self.min_x, self.max_y), fill = "red")
        self.canvas.create_line((self.min_x, self.min_y), (self.max_x, self.min_y), fill = "red")
        self.canvas.create_line((self.min_x, self.max_y), (self.max_x, self.max_y), fill = "red")
        self.canvas.create_line((self.max_x, self.min_y), (self.max_x, self.max_y), fill = "red")
        #Draw balls        
        for b in self.balls:
            obj = self.canvas.create_oval(b.x - b.radius, b.y - b.radius, b.x + b.radius, b.y + b.radius, outline=b.tk_rgb, fill=b.tk_rgb)
            self.ball_handles[b] = obj
        self.canvas.update()


    #refresh is called to update the state of the simulation
    #-each refresh call can be considered one iteration of the simulation
    #-all balls will be moved and if there is a collision then it will be computed
    def refresh(self):
        #get the next collision
        i, j, t, num_collisions_i, num_collision_j  = self.PQ.get_next()
        #gather the current collisions of the ith and jth ball
        current_collisions_i = self.balls[i].count
        current_collisions_j = self.balls[j].count
        
        #Check the difference in time between the predicted collision time and 
        #the current time stamp of the simulation
        delta = t - self.time
        #If the difference is greater than 1, then just move the balls
        if delta > 1.0:
            # cap delta to 1.0
            for bi in self.balls:
                bi.move()
                self.canvas.move(self.ball_handles[bi], bi.vx, bi.vy)
            self.time += 1.0
        #Otherwise a collision has occurred
        else:
            #Move all balls
            for bi in self.balls:
                bi.move(delta)
                self.canvas.move(self.ball_handles[bi], bi.vx*delta, bi.vy*delta)
            #increment the simulation time stamp
            self.time += delta
            #Delete the top element within the Priority Queue
            self.PQ.delete()
            #if i is -1 then this indicates a collision with a vertical wall
            #also this if statement checks if the number of collisions recorded 
            #when the collision returned by PQ.get_next() is equal to the 
            #number of collisions within the jth ball
            #this acts as a test to check if the collision is still valid
            if i == -1 and num_collision_j == current_collisions_j:
                #compute what happens from the vertical wall collision
                self.balls[j].collide_with_vertical_wall()
                #update collision times for the jth ball
                self.update_collision_times(j)
            #if j is -1 then this indicates a collision a horizontal wall
            #while also checking if the number of collisions match
            #to see if the collision is valid
            elif j == -1 and num_collisions_i == current_collisions_i:
                #compute what happens from the horizontal wall collision
                self.balls[i].collide_with_horizontal_wall()
                #update collision times for the ith ball
                self.update_collision_times(i)
            #Otherwise i and j are not equal to -1 indicating that the collision is between two balls
            #check if no collisions have occurred between both balls before the collision returned from PQ.get_next
            #if true then this means that the collision is still valid and must be executed
            elif num_collision_j == current_collisions_j and num_collisions_i == current_collisions_i:
                #Execute collision across the ith and jth ball                
                self.balls[i].collide_with_ball(self.balls[j])
                #update collision times for both the ith and jth ball
                self.update_collision_times(i)
                self.update_collision_times(j)
                
        #update the canvas to draw the new locations of each ball
        self.canvas.update()

        self.canvas.after(self.refresh_speed, self.refresh) #Calls the function again
示例#22
0
class Earth:
    DELAY_STEP = 10

    def __init__(self,
                 nsize,
                 msize,
                 scale,
                 dencity=None,
                 lifeRule=None,
                 root=None):
        self.root = root
        self.lifeRule = lifeRule
        self.RowSize = nsize
        self.ColumnSize = msize
        self.Scale = scale
        self.dencity = dencity
        self.drawArray = []
        self.MyArray = array('H',
                             (False
                              for s in range(self.RowSize * self.ColumnSize)))
        self.canvas = Canvas(root,
                             width=self.RowSize * self.Scale,
                             height=self.ColumnSize * self.Scale,
                             bg="black")
        self.canvas.pack()
        self.delay = 10
        self.__init_life()

    def delay_increase(self):
        self.delay += self.DELAY_STEP

    def delay_decrease(self):
        if self.delay > 0:
            self.delay -= self.DELAY_STEP

    def get(self, row_pos, column_pos):
        row_pos = row_pos % self.RowSize
        column_pos = column_pos % self.ColumnSize
        return self.MyArray[row_pos * self.ColumnSize + column_pos]

    def __set(self, row_pos, column_pos):
        self.MyArray[row_pos * self.ColumnSize + column_pos] = True
        self.canvas.itemconfigure(self.drawArray[row_pos * self.ColumnSize +
                                                 column_pos],
                                  fill='yellow')

    def __unset(self, row_pos, column_pos):
        self.MyArray[row_pos * self.ColumnSize + column_pos] = False
        self.canvas.itemconfigure(self.drawArray[row_pos * self.ColumnSize +
                                                 column_pos],
                                  fill='black')

    def __init_life(self):
        for i in range(self.RowSize):
            for j in range(self.ColumnSize):
                self.drawArray.append(
                    self.canvas.create_oval(i * self.Scale,
                                            j * self.Scale,
                                            i * self.Scale + self.Scale,
                                            j * self.Scale + self.Scale,
                                            fill='black'))
        for i in range(self.RowSize):
            for j in range(self.ColumnSize):
                if random.randint(1, self.dencity) == self.dencity:
                    self.__set(i, j)

    def __next_generation(self):
        for i in range(self.RowSize):
            for j in range(self.ColumnSize):
                alive = self.get(i, j)
                comfort_level = self.lifeRule(self, self.RowSize,
                                              self.ColumnSize, i, j)
                if alive and comfort_level == IS_UNPLEASURE:
                    self.__unset(i, j)
                if not alive and comfort_level == IS_PLEASURE:
                    self.__set(i, j)

    def next_move(self):
        self.__next_generation()
        self.canvas.after(self.delay, self.next_move)
示例#23
0
        stvorec(x + 20 * i, y)


def stvorecStvorcov(x, y, dx, dy):
    for i in range(0, dy):
        riadok(x, y + 20 * i, dx)


def mindfuck(amt):
    for i in range(0, 20):
        stvorecStvorcov(i * amt, i * amt, i, i)


def loop():
    global t, c
    c.delete('all')

    mindfuck(t)

    if t > 20:
        t = 0
    else:
        t += 1

    c.update_idletasks()
    c.update()
    c.after(0, loop)


c.after(0, loop)
c.mainloop()
示例#24
0
class PathFindingBfs:
    def __init__(self, myCanvas: Canvas, columns: int, rows: int, width: float,
                 height: float):
        self.Canvas = myCanvas
        self.columns = columns
        self.rows = rows
        self.width = width
        self.height = height
        self.operation = 0

        self.dr = [-1, 1, 0, 0]
        self.dc = [0, 0, 1, -1]
        self.rq = []  # Row Queue
        self.cq = []  # Column Queue
        self.queue = []  # Containing the path
        self.visited = list()  # Visited Matrix
        self.reached = False  # To check if we get to the destination
        self.move_count = 0
        self.nodes_left_in_layer = 1
        self.nodes_in_next_layer = 0
        self.secondarylist = list()

        self.columnwidth = float(self.width / self.columns)
        self.rowheight = float(self.height / self.rows)
        self.isstartselected = False
        self.isendselected = False
        self.startid = 0
        self.endid = 0
        self.barrierlist = list()
        self.operationlist = list()

        self.canvas = Canvas(self.Canvas,
                             height=self.height,
                             width=self.width,
                             bg="#FDE69F")  # Canvas within the canvas
        self.canvas1 = self.Canvas.create_window(0,
                                                 0,
                                                 anchor="nw",
                                                 window=self.canvas)

        for i in range(self.rows):
            for j in range(self.columns):
                self.x = self.canvas.create_rectangle(
                    0 + j * self.columnwidth, 0 + i * self.rowheight,
                    self.columnwidth + j * self.columnwidth,
                    self.rowheight + i * self.rowheight)

        # Responsible for choosing the start and end point
        self.canvas.bind("<Double-Button-1>", lambda event: self.start(event))
        # Responsible for Adding Barriers
        self.canvas.bind("<B1-Motion>", lambda event: self.motion(event))
        # Responsible
        self.canvas.bind("<B3-Motion>", lambda event: self.removemotion(event))

    def clear(self):
        # Empty Out the stored variables
        self.rq = []
        self.cq = []
        self.queue = []
        self.reached = False
        self.move_count = 0
        self.nodes_left_in_layer = 1
        self.nodes_in_next_layer = 0
        self.operation = 0
        self.isstartselected = False
        self.isendselected = False
        self.barrierlist = []
        self.startid = 0
        self.endid = 0
        self.operationlist = list()

        for i in range(self.rows):
            for j in range(self.columns):
                id = self.getwidgetid(i, j)
                self.canvas.itemconfig(id, fill="#FDE69F")

    def start(self, event):
        x = event.widget.find_closest(event.x, event.y)  # id of the widget
        if not self.isstartselected:
            self.canvas.itemconfig(x, fill="yellow")
            self.isstartselected = True
            self.startid = x[0]
        elif not self.isendselected:
            self.canvas.itemconfig(x, fill="green")
            self.isendselected = True
            self.endid = x[0]
        elif x[0] == self.startid:
            self.canvas.itemconfig(x, fill="#FDE69F")
            self.isstartselected = False
            self.startid = 0
        elif x[0] == self.endid:
            self.canvas.itemconfig(x, fill="#FDE69F")
            self.isendselected = False
            self.endid = 0

    def motion(self, event):
        if self.isstartselected and self.isendselected:
            x = event.widget.find_closest(event.x, event.y)
            if x[0] not in self.barrierlist and x[0] != self.startid and x[
                    0] != self.endid:
                self.canvas.itemconfig(x, fill="black")
                self.barrierlist.append(x[0])

    def removemotion(self, event):
        x = event.widget.find_closest(event.x, event.y)
        if x[0] in self.barrierlist:
            self.canvas.itemconfigure(x, fill="#FDE69F")
            self.barrierlist.remove(x[0])

    def getlistcoordinates(self, number):
        if not (number % self.columns == 0):
            row = number // self.columns
            column = number % self.columns - 1
        else:
            column = self.columns - 1
            row = (number - 1) // self.columns

        return int(row), int(column)

    def getwidgetid(self, row, column):
        return row * self.columns + column + 1

    def bfs(self, event):
        if self.isstartselected and self.isstartselected:
            # empty the list so that we operate after we make modification
            self.operationlist = [["" for i in range(self.columns)]
                                  for j in range(self.rows)]
            # adding the start path
            i, j = self.getlistcoordinates(self.startid)
            self.operationlist[i][j] = "S"
            k, l = self.getlistcoordinates(self.endid)
            self.operationlist[k][l] = "E"
            for i in self.barrierlist:
                n, m = self.getlistcoordinates(i)
                self.operationlist[n][m] = "#"
            i, j = self.getlistcoordinates(self.startid)
            self.Solve(i, j)

    def explore_neighbors(self, r: int, c: int):
        list1 = list()
        for i in range(4):
            rr = r + self.dr[i]
            cc = c + self.dc[i]
            # Skipping the wrong choices
            if rr < 0 or cc < 0:
                continue
            if rr >= self.rows or cc >= self.columns:
                continue
            # Skipping visited locations or blocked cells
            if self.visited[rr][cc]:
                continue
            if self.operationlist[rr][cc] == "#":
                continue
            list1.append(i)
            self.VisitedColor(rr, cc)
            self.operation += 1
            self.rq.append(rr)
            self.cq.append(cc)
            self.visited[rr][cc] = True
            self.nodes_in_next_layer += 1
        # Tracking The Path Of the Solution Part

        if len(list1) != 0:
            path = self.queue.pop(0)
            for i in range(len(list1)):
                if list1[i] == 0:
                    string = path + "U"
                    self.queue.append(string)
                elif list1[i] == 1:
                    string = path + "D"
                    self.queue.append(string)
                elif list1[i] == 2:
                    string = path + "R"
                    self.queue.append(string)
                elif list1[i] == 3:
                    string = path + "L"
                    self.queue.append(string)
        else:
            self.queue.pop(0)

    def Solve(self, sr: int, sc: int):
        self.visited = [[False for i in range(self.columns)]
                        for j in range(self.rows)]
        self.rq.append(sr)
        self.cq.append(sc)
        self.queue.append("")
        self.visited[sr][sc] = True
        while len(
                self.rq
        ) > 0:  # or self.cq because we add and remove items in the same time
            r = self.rq.pop(0)
            c = self.cq.pop(0)
            if self.operationlist[r][c] == "E":
                self.reached = True
                break
            self.explore_neighbors(r, c)
            self.nodes_left_in_layer -= 1
            if self.nodes_left_in_layer == 0:
                self.nodes_left_in_layer = self.nodes_in_next_layer
                self.nodes_in_next_layer = 0
                self.move_count += 1
        if self.reached:
            k, l = self.getlistcoordinates(self.endid)
            self.backtracking(self.queue[0], k, l)
            text = f"The Shortest Path is {self.move_count} blocks away\nAnd The cells visited are: " \
                   f"{self.operation} ({int((self.operation / (self.columns * self.rows)) * 100)}%)"
            messagebox.showinfo("Solution Details", text)
            return self.move_count
        messagebox.showerror("PathError", "Path Not Found")
        return -1

    def backtracking(self, path: str, r: int, c: int):
        self.ValidateColorSolution(r, c)
        for move in path[-1::-1]:
            if move == "D":
                r -= 1
                self.ValidateColorSolution(r, c)
            elif move == "U":
                r += 1
                self.ValidateColorSolution(r, c)
            elif move == "R":
                c -= 1
                self.ValidateColorSolution(r, c)
            elif move == "L":
                c += 1
                self.ValidateColorSolution(r, c)

    def ValidateColorSolution(self, i: int, j: int):
        id = self.getwidgetid(i, j)
        self.canvas.itemconfig(id, fill="#FCA85A")
        self.canvas.update()
        self.canvas.after(100)

    def VisitedColor(self, i: int, j: int):
        id = self.getwidgetid(i, j)
        self.canvas.itemconfigure(id, fill="red")
        self.canvas.update()

    def delete(self):
        self.clear()
        self.Canvas.delete(self.canvas1)
        self.canvas.destroy()
示例#25
0
        speed_y = 0
        y1 = 600
        c.move(player, speed_x, speed_y)
    if x1 < 50:
        speed_x = 0
    c.after(50, PhysMove)

def PhysKey(key):
    global player, speed_y, speed_x
    print("с.coords")
    x1, y1 = c.coords(player)
    if key.char == "d" and speed_x < 10 and is_available(x1+50, y1):
       speed_x = speed_x + 10
       c.move(player, speed_x, speed_y)
       print("right")
    if key.char == "a" and speed_x > -10 and is_available(x1-50, y1):
        speed_x = speed_x - 10
        c.move(player, speed_x, speed_y)
        print("left")
    if key.char == " "   and speed_y == 0:
        speed_y = speed_y - 40
        print("space")
        c.move(player, speed_x, speed_y)

    
        
c.after(50, PhysMove)    
tk.bind("<KeyPress>", PhysKey)
mainloop()

示例#26
0
class Visual(Frame):
    '''Class that takes a world as argument and present it graphically
    on a tkinter canvas.'''
    def __init__(self):
        '''Sets up a simulation GUI in tkinter.
        '''
        Frame.__init__(self)
        self.master.title("The Schelling Segregation Model in Python")
        self.master.wm_resizable(0, 0)
        self.grid()

        self.movement_possible = True

        # --------------------------------------- #
        # --------- FRAMES FOR GUI -------------- #
        # --------------------------------------- #

        # The pane for user values
        self._entryPane = Frame(self, borderwidth=5, relief='sunken')
        self._entryPane.grid(row=0, column=0, sticky='n')

        # The buttons pane
        self._buttonPane = Frame(self, borderwidth=5)

        self._buttonPane.grid(row=1, column=0, sticky='n')

        # A temp pane where graph is located, just for cosmetic reasons
        width, height = 425, 350
        self._graph = Canvas(self,
                             width=width,
                             height=height,
                             background="black")
        self._graph.configure(relief='sunken', border=2)

        self._graph.grid(row=3, column=0)

        # The pane where the canvas is located
        self._animationPane = Frame(self, borderwidth=5, relief='sunken')
        self._animationPane.grid(row=0,
                                 column=1,
                                 rowspan=4,
                                 pady=10,
                                 sticky="n")

        # --------------------------------------- #
        # --------- FILLING THE FRAMES ---------- #
        # --------------------------------------- #

        self._canvas()  # Create graphics canvas

        self._entry()  # Create entry widgets

        self._buttons()  # Create button widgets

    def _plot_setup(self, time):
        '''Method for crudely annotating the graph window.'''
        time = time

        # Main plot
        width, height = 425, 350
        y0 = -time / 10
        self._graph = Canvas(self,
                             width=width,
                             height=height,
                             background="black",
                             borderwidth=5)
        self._graph.grid(row=3, column=0)
        self.trans = Plotcoords(width, height, y0, -0.2, time, 1.3)

        x, y = self.trans.screen(time // 2, 1.2)
        x1, y1 = self.trans.screen(time // 2, 1.13)
        self._graph.create_text(x,
                                y,
                                text="% Happy",
                                fill="yellow",
                                font="bold 12")
        self._graph.create_text(x1,
                                y1,
                                text="% Unhappy",
                                fill="blue",
                                font="bold 12")

        # Line x-axis
        x, y = self.trans.screen((-5 * (time / 100)), -0.05)
        x1, y = self.trans.screen(time, -0.05)
        self._graph.create_line(x, y, x1, y, fill="white", width=1.5)

        # Text x-axis
        x_text, y_text = self.trans.screen(time / 2, -0.15)
        self._graph.create_text(x_text,
                                y_text,
                                text="Time",
                                fill="white",
                                font="bold 12")

        # Liney-axis
        x, y = self.trans.screen((-0.5 * (time / 100)), -0.05)
        x, y1 = self.trans.screen((-5 * (time / 100)), 1)
        self._graph.create_line(x, y, x, y1, fill="white", width=1.5)

    def _entry(self):
        '''Method for creating widgets for collecting user input.'''

        # N (no of turtles)
        dim = 30 * 30
        self._N_label = Label(self._entryPane,
                              anchor='w',
                              justify='left',
                              text="N:",
                              relief='raised',
                              width=12,
                              height=1,
                              font="italic 20")
        self._N_label.grid(row=0, column=1, ipady=14)

        self._N = Scale(self._entryPane,
                        from_=1,
                        to=dim - 50,
                        resolution=1,
                        bd=3,
                        relief='sunken',
                        orient='horizontal',
                        length=235,
                        tickinterval=849)
        self._N.set(400)
        self._N.grid(row=0, column=2)

        # Ticks (lenght of simulation)
        self._Ticks_label = Label(self._entryPane,
                                  anchor='w',
                                  justify='left',
                                  text="Time:",
                                  relief='raised',
                                  width=12,
                                  height=1,
                                  font="bold 20")
        self._Ticks_label.grid(row=1, column=1, ipady=14)

        self._Ticks = Scale(self._entryPane,
                            from_=10,
                            to=1000,
                            resolution=1,
                            bd=3,
                            relief='sunken',
                            orient='horizontal',
                            length=235,
                            tickinterval=990)
        self._Ticks.set(500)
        self._Ticks.grid(row=1, column=2)

        # % similar wanted
        self._Similar_label = Label(self._entryPane,
                                    anchor='w',
                                    justify='left',
                                    text="Similar wanted:",
                                    relief='raised',
                                    width=12,
                                    height=1,
                                    font="bold 20")

        self._Similar_label.grid(row=2, column=1, ipady=14)

        self._Similar = Scale(self._entryPane,
                              from_=0.0,
                              to=1.0,
                              resolution=0.01,
                              bd=3,
                              relief='sunken',
                              orient='horizontal',
                              length=235,
                              tickinterval=1)
        self._Similar.set(0.76)
        self._Similar.grid(row=2, column=2)

    def _buttons(self):
        '''Method for creating button widgets for setting up, running and plotting results from simulation.'''
        width = 7
        height = 1

        # The 'Setup' button
        self._setupButton = Button(self._buttonPane,
                                   text="Setup",
                                   command=self._setup,
                                   width=width,
                                   height=height,
                                   font="bold 30",
                                   relief='raised',
                                   borderwidth=5)
        self._setupButton.grid(row=0, column=0)

        # The 'Go' button
        self._goButton = Button(self._buttonPane,
                                text="Go",
                                command=self._go,
                                width=width,
                                height=height,
                                font="bold 30",
                                relief='raised',
                                borderwidth=5)
        self._goButton.grid(row=0, column=1)

        # The 'Quit' button
        self._quitButton = Button(self._buttonPane,
                                  text="Quit",
                                  command=self._quit,
                                  width=width,
                                  height=height,
                                  font="bold 30",
                                  relief='raised',
                                  borderwidth=5)
        self._quitButton.grid(row=1, column=0, columnspan=2)

    def _canvas(self):
        '''Creates the canvas on which everything happens.'''
        # The tick counter information
        self._Tick_counter = Label(self._animationPane,
                                   anchor='w',
                                   justify='left',
                                   text="Time:",
                                   width=5,
                                   font="bold 20")
        self._Tick_counter.grid(row=0, column=0, sticky="e")

        self._Tick_counter1 = Label(self._animationPane,
                                    justify='center',
                                    text="",
                                    relief='raised',
                                    width=5,
                                    font="bold 20")
        self._Tick_counter1.grid(row=0, column=1, sticky='w')

        self.canvas_w, self.canvas_h = 750, 750

        self.canvas = Canvas(self._animationPane,
                             width=self.canvas_w,
                             height=self.canvas_h,
                             background="black")

        self.canvas.grid(row=1, column=0, columnspan=2)

    def _setup(self):
        '''Method for 'Setup' button.'''
        ## Clearing the canvas and reset the go button
        self.canvas.delete('all')
        self._goButton['relief'] = 'raised'
        self.N = int(self._N.get())
        self.Ticks = int(self._Ticks.get())
        self.similar = float(self._Similar.get())
        self.data = []
        self.tick_counter = 0
        self._Tick_counter1['text'] = str(self.tick_counter)
        self._plot_setup(self.Ticks)
        self.grid_size = 30
        self.world = World(750, 750, self.grid_size)
        self.create_turtles()
        self.neighbouring_turtles()
        self.draw_turtles()

    def _go(self):
        '''Method for the 'Go' button, i.e. running the simulation.'''
        self._goButton['relief'] = 'sunken'
        if self.tick_counter <= self.Ticks:
            self._Tick_counter1['text'] = str(self.tick_counter)
            self.canvas.update()

            self._graph.update()
            self._graph.after(0)

            # Data collection
            turtles_unhappy = self.check_satisfaction()
            prop_happy, prop_unhappy = self.calc_prop_happy(self.tick_counter)

            self.data_collection(self.tick_counter, prop_happy, prop_unhappy)

            if self.tick_counter >= 1:

                # HAPPY values (%)
                x0 = self.tick_counter - 1
                x1 = self.tick_counter

                # Collecting values from stoblue data
                y0 = self.data[self.tick_counter - 1][1]
                y1 = self.data[self.tick_counter][1]

                # Transforming to tkinter
                x1, y1 = self.trans.screen(x1, y1)
                x0, y0 = self.trans.screen(x0, y0)
                self._graph.create_line(x0,
                                        y0,
                                        x1,
                                        y1,
                                        fill="yellow",
                                        width=1.3,
                                        tag="happy")  # Draw "happy lines

                # UNHAPPY values (%)
                x0 = self.tick_counter - 1
                x1 = self.tick_counter

                # Collecting values from stored data
                y0 = self.data[self.tick_counter - 1][2]
                y1 = self.data[self.tick_counter][2]

                # Transforming to tkinter
                x1, y1 = self.trans.screen(x1, y1)
                x0, y0 = self.trans.screen(x0, y0)
                self._graph.create_line(x0,
                                        y0,
                                        x1,
                                        y1,
                                        fill="blue",
                                        width=1.1,
                                        tag="unhappy")  # Draw unhappy lines

            if prop_happy < 1:
                self.turtle_move(turtles_unhappy)
                self.update_neighbours()
                self.tick_counter += 1
                self.canvas.after(0, self._go())

        self._goButton['relief'] = 'raised'

    def _quit(self):
        '''Method for the 'Quit' button.'''
        self.master.destroy()

    # ------------------------------------------------------ #
    # ---------- FUNCTIONS CALLED AT EACH TICK ------------- #
    # ------------------------------------------------------ #

    def turtle_move(self, unhappy_turtles):
        '''Moves all the unhappy turtles (randomly).'''

        while unhappy_turtles:
            i = random.randint(0, len(unhappy_turtles) - 1)
            turtle = unhappy_turtles.pop(i)
            turtle.move(self)

    def update_neighbours(self):
        '''Updates the turtles neigbour attributes. Called
        after all turtles have moved.'''
        for turtle in self.turtles:
            turtle.update_neighbours()

    def check_satisfaction(self):
        '''Checks to see if turtles are happy or not.
        Returns a list of unhappy turtles, i.e. turtles
        that should move.
 
        Called before the move method.'''

        for turtle in self.turtles:
            turtle.is_happy()

        unhappy_turtles = []
        for element in self.turtles:
            if not element.happy:
                unhappy_turtles.append(element)

        return unhappy_turtles

    def calc_prop_happy(self, i):
        '''Calculates the proportion of happy turtles.'''
        happy = 0
        unhappy = 0

        for turtle in self.turtles:
            if turtle.happy:
                happy += 1
            else:
                unhappy += 1
        prop_happy = happy / len(self.turtles)
        prop_unhappy = unhappy / len(self.turtles)

        return prop_happy, prop_unhappy

    def data_collection(self, i, prop_happy, prop_unhappy):
        '''Method for collecting data at each tick.'''
        self.data.append((i, prop_happy, prop_unhappy))

# ------------------------------------------------------ #
# ---------- INITIALISATION FUNCTIONS ------------------ #
# ------------------------------------------------------ #

    def create_turtles(self):
        '''Method for creating a new list of turtles.
 
        Upon creation they are registered in the World object.'''
        if self.N <= self.grid_size * self.grid_size:
            counter = 0
            self.turtles = []
            while counter < self.N:

                s = "S" + str(counter)
                if counter <= int(self.N / 2):
                    color = "yellow"
                else:
                    color = "blue"

                x = random.randint(0, self.grid_size - 1)
                y = random.randint(0, self.grid_size - 1)

                if not self.world.patch_list[x][y]:
                    new_turtle = Schelling(world=self.world,
                                           x=x,
                                           y=y,
                                           s=s,
                                           color=color,
                                           similar_wanted=self.similar)

                    self.world.register(new_turtle)
                    counter += 1
                    self.turtles.append(new_turtle)
        else:
            print("Number of turtles exceeds world!")

    def draw_turtles(self):
        '''Method for drawing turtles on canvas.
 
           Calls each turtle's own method for drawing.'''
        for turtle in self.turtles:
            turtle.draw(self.canvas)

    def neighbouring_turtles(self):
        '''Method for updating turtles' neighbours.
 
           Calls on each turtle's own method for updating neighbours.'''
        for turtle in self.turtles:
            turtle.get_neighbouring_patches()
示例#27
0
        else:  #иначе начинаем новый цикл сразу
            currentStage = STAGE_CLEANING
            elevatorCanvas.after(INTERVAL, progress)

    elif currentStage == STAGE_DISPATCHING:
        dispatchGrain()
        getStats()
        blinkArrow(elevatorCanvas, [goodGrainArrowToExport])

        currentStage = STAGE_CLEANING
        elevatorCanvas.after(INTERVAL, progress)

    totalExpense += 500
    totalProfit = totalIncome - totalExpense

    kek.append([iters, totalProfit])

    print(totalIncome)
    print(totalExpense)
    print(totalProfit)

    timeGoodExportText.config(text="Через {0} дн.".format(
        str(abs(iters % DISPATCH_DELAY % (-1 * DISPATCH_DELAY)))))
    print()


##################################################################################
elevatorCanvas.after(0, progress)
window.geometry('1280x720')
window.mainloop()
示例#28
0
canvas.grid(row=0, column=0)

delay = 30
rad = 5
color = 'red'
x = rad
y = ch - rad
vx = 4.0
vy = -5.0
ay = 0.05
line = [x, y]
while True:
    canvas.delete(ALL)
    canvas.create_oval(x - rad, y - rad, x + rad, y + rad, fill=color)
    line.append(x)
    line.append(y)
    canvas.create_line(line, fill='blue')
    canvas.update()
    if (x + rad) >= cw:
        vx = -abs(vx)
    elif (y + rad) >= ch:
        vy = -abs(vy)
    elif x <= rad:
        vx = abs(vx)
    elif y <= rad:
        vy = abs(vy)
    x += vx
    y += vy + 0.5 * ay
    vy += ay
    canvas.after(delay)
示例#29
0
class App:
    sg = ""

    def __init__(self, screen):
        self.debug = False
        self.controlMode = "l"  # l = location, s = size
        # user by the x (cross) button to show virtual screen cross
        self.xMode = False  # false - no x is displayed in the middle of the screen
        self.xVertical = 0
        self.xHorizental = 0
        self.xBoundry = 0

        # used by the y (mid button)  button to show mid screen marker
        self.yMode = False  # False - no midScreen marker is displayed
        self.yVertical = 0
        self.yHorizental = 0
        #####
        self.bgColor = 0
        self.vsColor = 0
        self.stimulusColor = 0
        self.appConfig = loadCSV(constants.APP_CONFIG_FILE)
        self.vsX = self.getAppConfig("fishScreenStartX")
        self.vsY = self.getAppConfig("fishScreenStartY")
        self.vsWidth = self.getAppConfig("fishScreenWidth")
        self.vsHeight = self.getAppConfig("fishScreenHeight")
        self.bgColor = self.getAppConfig("backgroundColor", "str")
        self.vsColor = self.getAppConfig("virtualScreenColor", "str")
        self.stimulusColor = self.getAppConfig("stimulusColor", "str")
        self.f9CommunicationEnabled = self.getAppConfig(
            "f9CommunicationEnabled", "str")
        self.NiDaqPulseEnabled = self.getAppConfig("NiDaqPulseEnabled", "str")
        self.DishRadiusSize = self.getAppConfig("DishRadiusSize")
        self.VirtualScreenDegrees = self.getAppConfig("VirtualScreenDegrees")
        self.VirtualScreenWidthActualSize = self.getAppConfig(
            "VirtualScreenWidthActualSize")
        self.VirtualScreenHeightActualSize = self.getAppConfig(
            "VirtualScreenHeightActualSize")
        self.projectorOnMonitor = self.getAppConfig("projectorOnMonitor")

        self.deltaX = 0
        self.deltaY = 0

        self.positionDegreesToVSTable = []
        self.calcConvertPositionToPixelsTable()  # populate the above table

        if self.NiDaqPulseEnabled.lower() == "on":
            # try to add channel
            try:
                task = NiDaqPulse(device_name="Dev2/port{0}/line{1}".format(
                    self.port, self.line))
                self.output_device = task
            except nidaqmx.DaqError as e:
                print(e)
                task.stop()
        else:
            self.output_device = None

        if self.f9CommunicationEnabled.lower() == "on":
            self.f9CommunicationEnabled = False
        else:
            self.f9CommunicationEnabled = False
        logging.info("f9CommunicationEnabled=" +
                     str(self.f9CommunicationEnabled))
        self.printVirtualScreenData()
        self.screen_width = int(screen.winfo_screenwidth() / 4)
        self.screen_height = int(screen.winfo_screenheight() / 4)
        screen.geometry(
            self.calcGeometry(self.screen_width, self.screen_height))
        self.canvas = Canvas(screen, background="black")
        self.textVar = tkinter.StringVar()
        self.label = ttk.Label(self.canvas, textvariable=self.textVar)
        self.label.config(font=("Courier", 20))
        self.label.grid(column=0, row=0)
        self.canvas.pack(fill=BOTH, expand=1)
        self.vs = self.canvas.create_rectangle(self.vsX,
                                               self.vsY,
                                               self.vsX + self.vsWidth,
                                               self.vsY + self.vsHeight,
                                               fill=self.vsColor)
        screen.bind('<Up>', self.processEvent)
        screen.bind('<Down>', self.processEvent)
        screen.bind('<Left>', self.processEvent)
        screen.bind('<Right>', self.processEvent)
        screen.bind(constants.DEBUG, self.turnDebug)
        screen.bind(constants.LOCATION, self.changeControlMode)
        screen.bind(constants.SIZE, self.changeControlMode)
        screen.bind(constants.UPDATE, self.updateConfig)
        screen.bind(constants.EXIT, self.leaveProg)
        screen.bind(constants.RUN, self.manageStimulus)
        screen.bind(constants.PAUSE, self.manageStimulus)
        screen.bind(constants.CROSS, self.showCrossAndBoundries)
        screen.bind(constants.MID_SCREEN, self.showMidScreen)
        screen.bind('?', self.printHelp)
        self.printHelp("")

    def updateConfig(self, event):
        """
        Update config file with current VS settings
        """
        logging.debug(event)
        self.appConfig[0]["fishScreenStartX"] = self.vsX
        self.appConfig[0]["fishScreenStartY"] = self.vsY
        self.appConfig[0]["fishScreenWidth"] = self.vsWidth
        self.appConfig[0]["fishScreenHeight"] = self.vsHeight
        writeCSV(constants.APP_CONFIG_FILE, self.appConfig[0])
        self.printVirtualScreenData()
        logging.debug("Config file updates successfully")

    def leaveProg(self, event):
        logging.debug(event)
        logging.info("Bye bye !")
        if self.output_device is not None:
            self.output_device.stop()
        sys.exit()

    def printHelp(self, event):
        print("NOTE : press the keyboard while focus is on the graphic screen")
        print("========== General actions ==========")
        print('? = for help (this screen)')
        print(constants.EXIT, ' - to exit')
        print(constants.DEBUG, ' - to activate debug')
        print("========== Controlling Virtual Screen ==========")
        print(constants.CROSS, ' - show cross')
        print(constants.LOCATION,
              ' - switch to virtual screen location setting')
        print(constants.SIZE, ' - switch to virtual screen size setting ')
        print('<Up> - move up or reduce virtual screen height')
        print('<Down> - move down or extend virtual screen hegith')
        print('<Left>  - move left or reduce virtual screen width')
        print('<Right> - move right or extend virtual screen size ')
        print(constants.UPDATE,
              ' - to update app config with current virtual screen location')
        print("========== Controlling Stimulus generator ==========")
        print(constants.RUN,
              ' - Run the stimuli, pressing r again will restart')
        print(constants.PAUSE, ' - Pause the run')

    def changeControlMode(self, event):
        logging.debug(event)
        self.chagneVirtualScreenProperties(event.keysym)
        self.controlMode = event.keysym
        logging.debug("ControlMode=" + event.keysym)

    def processEvent(self, event):
        logging.debug(event)
        self.chagneVirtualScreenProperties(event.keysym)
        if self.controlMode == constants.LOCATION:
            self.canvas.move(self.vs, self.deltaX, self.deltaY)
            self.canvas.move(self.xBoundry, self.deltaX, self.deltaY)
            self.canvas.move(self.xHorizental, self.deltaX, self.deltaY)
            self.canvas.move(self.xVertical, self.deltaX, self.deltaY)
        elif self.controlMode == constants.SIZE:
            x0, y0, x1, y1 = self.canvas.coords(self.vs)
            x1 = x0 + self.vsWidth
            y1 = y0 + self.vsHeight
            self.canvas.coords(self.vs, x0, y0, x1, y1)
            if self.xMode:
                self.deleteCross()
                self.createCross()

        return

    def manageStimulus(self, event):
        logging.debug(event)

        if event.keysym == constants.PAUSE:
            self.state = constants.PAUSE
            if self.sg != "":
                self.sg.terminate_run()
        elif event.keysym == constants.RUN:
            self.state = constants.RUN
            self.sg = StimulusGenerator(self.canvas, self, self.output_device)
            self.runStimuli()

    def runStimuli(self):  # this is main loop of stimulus
        if self.state == constants.PAUSE:
            return
        if self.sg.run_stimuli() == constants.DONE:  # call specific stim list
            logging.info("All stimuli were executed ! ")
            self.setDebugText("Done")
            self.state = constants.PAUSE
        else:
            self.canvas.after(constants.SLEEP_TIME, self.runStimuli)

    def calcGeometry(self, screen_width, screen_height):
        geometryStr = str(screen_width) + "x" + str(screen_height) + "+-10+0"
        return geometryStr

    def printVirtualScreenData(self):
        logging.debug("X=" + str(self.vsX) + " Y=" + str(self.vsY) +
                      " Width=" + str(self.vsWidth) + " Height=" +
                      str(self.vsHeight))

    def getAppConfig(self, variableName, type="int"):
        """get appConfig value

        Args:
            variableName ([string]): [the name of the variable]
            type ([type]): [int or str]
        """

        ret = self.appConfig[0][variableName]
        if type == "int":
            return (int(ret))
        else:
            return (ret)

    def showCrossAndBoundries(self, event):
        logging.debug(event)

        if self.xMode:
            self.xMode = False
            self.deleteCross()
        else:
            self.xMode = True
            self.createCross()

    def showMidScreen(self, event):
        logging.debug(event)
        monitor = self.get_monitors_dimensions(self.projectorOnMonitor)

        if self.yMode:
            self.yMode = False
            self.deleteMidScreen()
        else:
            self.createMidScreen(monitor['width'], monitor['height'])
            self.yMode = True

    def deleteCross(self):
        self.canvas.delete(self.xHorizental)
        self.canvas.delete(self.xVertical)
        self.canvas.delete(self.xBoundry)

    def deleteMidScreen(self):
        self.canvas.delete(self.yHorizental)
        self.canvas.delete(self.yVertical)

    def createMidScreen(self, width, height):

        self.yVertical = self.canvas.create_line(
            width / 2,
            0,
            width / 2,
            height,
            fill=constants.FILL_COLOR,
            width=constants.THIN_LINE_WIDTH)

        self.yHorizental = self.canvas.create_line(
            0,
            height / 2,
            width,
            height / 2,
            fill=constants.FILL_COLOR,
            width=constants.THIN_LINE_WIDTH)

    def createCross(self):
        self.xBoundry = self.canvas.create_rectangle(
            self.vsX - 10,
            self.vsY - 10,
            self.vsX + self.vsWidth + 10,
            self.vsY + self.vsHeight + 10,
            fill=constants.FILL_COLOR)
        self.xHorizental = self.canvas.create_line(
            self.vsX,
            self.vsY + self.vsHeight / 2,
            self.vsX + self.vsWidth,
            self.vsY + self.vsHeight / 2,
            fill=constants.FILL_COLOR,
            width=constants.LINE_WIDTH)
        self.xVertical = self.canvas.create_line(self.vsX + self.vsWidth / 2,
                                                 self.vsY,
                                                 self.vsX + self.vsWidth / 2,
                                                 self.vsY + self.vsHeight,
                                                 fill=constants.FILL_COLOR,
                                                 width=constants.LINE_WIDTH)
        self.canvas.tag_lower(self.xBoundry)

    def chagneVirtualScreenProperties(self, direction):
        """
        Change screen Location or Size properties based on controlMode

        Args:
            direction ([String]): the event.keySym Up,Down,Left,Rigth
        """
        # we need delta X and Y as tkinter move is relative to the existing locaiton whereas teh vsX and vsY are absolute
        self.deltaX = 0
        self.deltaY = 0

        if self.controlMode == constants.LOCATION:
            if direction.lower() == "up":
                self.deltaY -= 1
                self.vsY -= 1
            elif direction.lower() == "down":
                self.deltaY += 1
                self.vsY += 1
            elif direction.lower() == "left":
                self.deltaX -= 1
                self.vsX -= 1
            elif direction.lower() == "right":
                self.deltaX += 1
                self.vsX += 1
        elif self.controlMode == constants.SIZE:
            if direction.lower() == "up":
                self.vsHeight -= 1
            elif direction.lower() == "down":
                self.vsHeight += 1
            elif direction.lower() == "left":
                self.vsWidth -= 1
            elif direction.lower() == "right":
                self.vsWidth += 1

    def convertDegreesToMM(self, degrees):
        return 2 * self.DishRadiusSize * sin(degrees * (pi / 180) / 2)

    def convertMMToPixels(self, mm, direction):
        if direction.lower() == "width":
            return (mm * self.vsWidth) / self.VirtualScreenWidthActualSize
        else:
            return (mm * self.vsHeight) / self.VirtualScreenHeightActualSize

    def convertDegreestoPixels(self, degrees, direction):
        """[summary]

        Args:
            degrees ([int]): [degrees to be convereted]
            direction ([string]): [width or height]
        """
        return (self.convertMMToPixels(self.convertDegreesToMM(degrees),
                                       direction))

    def setDebugText(self, str):
        if self.debug:
            s = f'VS WxH {self.vsWidth} X {self.vsHeight}'
            s1 = f'1 degree/ms (LtR) = {round(self.convertDegreestoPixels(1, "widht"), 1)} pixels/ms'
            self.textVar.set(s + '\n' + s1 + '\n' + str)

    def turnDebug(self, event):
        if self.debug:
            logging.info("disable debug")
            self.debug = False
            self.label.grid_remove()
        else:
            logging.info("enable debug")
            self.debug = True
            self.label.grid()

    def get_monitors_dimensions(self, monitor_number):
        monitors = []
        for m in get_monitors():
            print(f'monitor = {m}')
            monitors.append({"width": m.width, "height": m.height})
        return monitors[monitor_number]

    def calcConvertPositionToPixelsTable(self):
        for i in range(0, 181):
            if i <= 90:
                d = 90 - i
                v = 500 - 500 * sin(radians(d)) * cos(radians(d / 2)) / sin(
                    radians(90 - d / 2))
            else:
                d = i - 90
                v = 500 + 500 * sin(radians(d)) * cos(radians(d / 2)) / sin(
                    radians(90 - d / 2))
            self.positionDegreesToVSTable.append(v)
示例#30
0
class Visual(Frame):
    '''Class that takes a world as argument and present it graphically
    on a tkinter canvas.'''

    def __init__(self):
        '''
        Sets up a simulation GUI in tkinter.
        '''
        Frame.__init__(self)
        self.master.title("The Schelling Segregation Model in Python")
        self.master.wm_resizable(0, 0)
        self.grid()
        self.movement_possible = True

        # --------------------------------------- #
        # --------- FRAMES FOR GUI -------------- #
        # --------------------------------------- #

        # The pane for user values
        self._entryPane = Frame(self,
                                borderwidth=5,
                                relief='sunken')
        self._entryPane.grid(row=0, column=0, sticky='n')

        # The buttons pane
        self._buttonPane = Frame(self, borderwidth=5)
        self._buttonPane.grid(row=1, column=0, sticky='n')

        # A temp pane where graph is located, just for cosmetic reasons
        width, height = 425, 350
        self._graph = Canvas(self,
                             width=width,
                             height=height,
                             background="black")
        self._graph.configure(relief='sunken', border=2)
        self._graph.grid(row=3, column=0)

        # The pane where the canvas is located
        self._animationPane = Frame(self,
                                    borderwidth=5,
                                    relief='sunken')
        self._animationPane.grid(row=0, column=1,
                                 rowspan=4, pady=10,
                                 sticky="n")

        # --------------------------------------- #
        # --------- FILLING THE FRAMES ---------- #
        # --------------------------------------- #

        self._canvas()      # Create graphics canvas
        self._entry()       # Create entry widgets
        self._buttons()     # Create button widgets

    def _plot_setup(self, time):
        '''Method for crudely annotating the graph window.'''
        time = time

        # Main plot
        width, height = 425, 350
        y0 = -time/10
        self._graph = Canvas(self, width=width,
                             height=height,
                             background="black",
                             borderwidth=5)
        self._graph.grid(row=3, column=0)
        self.trans = Plotcoords(width, height, y0, -0.2, time, 1.3)

        x, y = self.trans.screen(time // 2, 1.2)
        x1, y1 = self.trans.screen(time // 2, 1.13)
        self._graph.create_text(x, y,
                                text="% Happy",
                                fill="green",
                                font="bold 12")
        
        self._graph.create_text(x1, y1,
                                text="% Unhappy",
                                fill="red",
                                font="bold 12")
 
        # Line x-axis
        x, y = self.trans.screen((-5 * (time / 100)), -0.05)
        x1, y = self.trans.screen(time, -0.05)
        self._graph.create_line(x, y, x1, y, fill="white", width=1.5)
         
        # Text x-axis
        x_text, y_text = self.trans.screen(time / 2, -0.15)
        self._graph.create_text(x_text, y_text,
                                text="Time",
                                fill="white",
                                font="bold 12")

        # Line y-axis
        x, y = self.trans.screen((-0.5 * (time / 100)), -0.05)
        x, y1 = self.trans.screen((-5 * (time / 100)), 1)
        self._graph.create_line(x, y, x, y1, fill="white", width=1.5)
 
    def _entry(self):
        '''Method for creating widgets for collecting user input.'''
         
        # N (no of turtles)
        dim = 30*30

        self.fill_label = Label(self._entryPane,
                                anchor='w',
                                justify='left',
                                text='Fill',
                                relief='raised',
                                width=12,
                                height=1,
                                font='italic 20')
        
        self.fill_label.grid(row=0, column=1, ipady=14)

        self.fill = Scale(self._entryPane,
                          from_=0,
                          to=1,
                          resolution=0.01,
                          bd=3,
                          relief='sunken',
                          orient='horizontal',
                          length=235,
                          tickinterval=20)
        self.fill.grid(row=0, column=2)
        self.fill.set(0.8)
                           
        self._N_label = Label(self._entryPane,
                              anchor='w',
                              justify='left',
                              text="N:",
                              relief='raised',
                              width=12,
                              height=1,
                              font="italic 20")
        self._N_label.grid(row=1, column=1, ipady=14)

        self._N = Scale(self._entryPane,
                        from_=0,
                        to=100,
                        resolution=1,
                        bd=3,
                        relief='sunken',
                        orient='horizontal',
                        length=235,
                        tickinterval=20)
        self._N.set(30)
        self._N.grid(row=1, column=2)

        # Ticks (length of simulation)
        self._Ticks_label = Label(self._entryPane,
                                  anchor='w',
                                  justify='left',
                                  text="Time:",
                                  relief='raised',
                                  width=12,
                                  height=1,
                                  font="bold 20")
        self._Ticks_label.grid(row=2, column=1, ipady=14)
 
        self._Ticks = Scale(self._entryPane,
                            from_=10,
                            to=1000,
                            resolution=1,
                            bd=3,
                            relief='sunken',
                            orient='horizontal',
                            length=235,
                            tickinterval=990)
        self._Ticks.set(500)
        self._Ticks.grid(row=2, column=2)
 
        # % similar wanted
        self._Similar_label = Label(self._entryPane,
                                    anchor='w',
                                    justify='left',
                                    text="Similar wanted:",
                                    relief='raised',
                                    width=12,
                                    height=1,
                                    font="bold 20")
         
        self._Similar_label.grid(row=3, column=1, ipady=14)
 
        self._Similar = Scale(self._entryPane,
                              from_=0.0,
                              to=1.0,
                              resolution=0.01,
                              bd=3,
                              relief='sunken',
                              orient='horizontal',
                              length=235,
                              tickinterval=0.5)
        self._Similar.set(0.76)
        self._Similar.grid(row=3, column=2)

        # Delay between steps
        self._delay_label = Label(self._entryPane,
                                  anchor='w',
                                  justify='left',
                                  text="Delay (s):",
                                  relief='raised',
                                  width=12,
                                  height=1,
                                  font="bold 20")
         
        self._delay_label.grid(row=4, column=1, ipady=14)
 
        self._delay = Scale(self._entryPane,
                            from_=0.0,
                            to=1.0,
                            resolution=0.01,
                            bd=3,
                            relief='sunken',
                            orient='horizontal',
                            length=235,
                            tickinterval=0.5)
        self._delay.set(0.15)
        self._delay.grid(row=4, column=2)

    def _buttons(self):
        '''Method for creating button widgets for setting up,
        running and plotting results from simulation.'''
        width = 7
        height = 1

        # The 'Setup' button
        self._setupButton = Button(self._buttonPane,
                                   text="Setup",
                                   command=self._setup,
                                   width=width,
                                   height=height,
                                   font="bold 30",
                                   relief='raised',
                                   borderwidth=5)
        self._setupButton.grid(row=0, column=0)

        # The 'Go' button
        self._goButton = Button(self._buttonPane,
                                text="Go",
                                command=self._go,
                                width=width,
                                height=height,
                                font="bold 30",
                                relief='raised',
                                borderwidth=5)
        self._goButton.grid(row=0, column=1)

        # The 'Quit' button
        self._quitButton = Button(self._buttonPane,
                                  text="Quit",
                                  command=self._quit,
                                  width=width,
                                  height=height,
                                  font="bold 30",
                                  relief='raised',
                                  borderwidth=5)
        self._quitButton.grid(row=1, column=0, columnspan=2)

    def _canvas(self):
        '''Creates the canvas on which everything happens.'''
        # The tick counter information
        self._Tick_counter = Label(self._animationPane,
                                   anchor='w',
                                   justify='left',
                                   text="Time:",
                                   width=5,
                                   font="bold 20")
        self._Tick_counter.grid(row=0, column=0, sticky="e")
        self._Tick_counter1 = Label(self._animationPane,
                                    justify='center',
                                    text="",
                                    relief='raised',
                                    width=5,
                                    font="bold 20")
        self._Tick_counter1.grid(row=0, column=1, sticky='w')
        self.canvas_w, self.canvas_h = 750, 750
        self.canvas = Canvas(self._animationPane,
                             width=self.canvas_w,
                             height=self.canvas_h,
                             background="black")

        self.canvas.grid(row=1, column=0, columnspan=2)

    def _setup(self):
        '''Method for 'Setup' button.'''
        # Clearing the canvas and reset the go button
        self.canvas.delete('all')
        self._goButton['relief'] = 'raised'
        self.N = int(self._N.get())
        self.Ticks = int(self._Ticks.get())
        self.similar = float(self._Similar.get())
        self.data = []
        self.tick_counter = 0
        self._Tick_counter1['text'] = str(self.tick_counter)
        self._plot_setup(self.Ticks)
        self.grid_size = self.N
        self.world = World(750, 750, self.grid_size)
        self.create_turtles()
        self.neighbouring_turtles()
        self.draw_turtles()

    def _go(self):
        '''Method for the 'Go' button, i.e. running the simulation.'''
        self._goButton['relief'] = 'sunken'
        if self.tick_counter <= self.Ticks:
            self._Tick_counter1['text'] = str(self.tick_counter)
            self.canvas.update()

            self._graph.update()
            self._graph.after(0)

            # Data collection
            turtles_unhappy = self.check_satisfaction()
            prop_happy, prop_unhappy = self.calc_prop_happy(self.tick_counter)

            self.data_collection(self.tick_counter, prop_happy, prop_unhappy)

            if self.tick_counter >= 1:

                # HAPPY values (%)
                x0 = self.tick_counter-1
                x1 = self.tick_counter

                # Collecting values from stored data
                y0 = self.data[self.tick_counter-1][1]
                y1 = self.data[self.tick_counter][1]

                # Transforming to tkinter
                x1, y1 = self.trans.screen(x1, y1)
                x0, y0 = self.trans.screen(x0, y0)
                self._graph.create_line(x0, y0, x1, y1,
                                        fill="green", width=1.3,
                                        tag="happy")  # Draw "happy lines

                # UNHAPPY values (%)
                x0 = self.tick_counter-1
                x1 = self.tick_counter

                # Collecting values from stored data
                y0 = self.data[self.tick_counter-1][2]
                y1 = self.data[self.tick_counter][2]

                # Transforming to tkinter
                x1, y1 = self.trans.screen(x1, y1)
                x0, y0 = self.trans.screen(x0, y0)
                self._graph.create_line(x0, y0, x1, y1,
                                        fill="red", width=1.1,
                                        tag="unhappy")  # Draw unhappy lines
             
            if prop_happy < 1:
                self.turtle_move(turtles_unhappy)
                time.sleep(self._delay.get())
                self.update_neighbours()
                self.tick_counter += 1
                self.canvas.after(0, self._go())

        self._goButton['relief'] = 'raised'

    def _quit(self):
        '''Method for the 'Quit' button.'''
        self.master.destroy()

    # ------------------------------------------------------ #
    # ---------- FUNCTIONS CALLED AT EACH TICK ------------- #
    # ------------------------------------------------------ #

    def turtle_move(self, unhappy_turtles):
        '''Moves all the unhappy turtles (randomly).'''
         
        while unhappy_turtles:
            i = random.randint(0, len(unhappy_turtles)-1)
            turtle = unhappy_turtles.pop(i)
            turtle.move(self)

    def update_neighbours(self):
        '''Updates the turtles neigbour attributes. Called
        after all turtles have moved.'''
        for turtle in self.turtles:
            turtle.update_neighbours()

    def check_satisfaction(self):
        '''Checks to see if turtles are happy or not.
        Returns a list of unhappy turtles, i.e. turtles
        that should move.

        Called before the move method.'''

        for turtle in self.turtles:
            turtle.is_happy()

        unhappy_turtles = []
        for element in self.turtles:
            if not element.happy:
                unhappy_turtles.append(element)

        return unhappy_turtles

    def calc_prop_happy(self, i):
        '''Calculates the proportion of happy turtles.'''
        happy = 0
        unhappy = 0

        for turtle in self.turtles:
            if turtle.happy:
                happy += 1
            else:
                unhappy += 1
        prop_happy = happy/len(self.turtles)
        prop_unhappy = unhappy/len(self.turtles)

        return prop_happy, prop_unhappy

    def data_collection(self, i, prop_happy, prop_unhappy):
        '''Method for collecting data at each tick.'''
        self.data.append((i, prop_happy, prop_unhappy))


# ------------------------------------------------------ #
# ---------- INITIALISATION FUNCTIONS ------------------ #
# ------------------------------------------------------ #

    def create_turtles(self):
        '''Method for creating a new list of turtles.

        Upon creation they are registered in the World object.'''
        if self.N*self.N <= self.grid_size*self.grid_size:
            counter = 0
            self.turtles = []
            while counter < self.N * self.N * self.fill.get():
                             
                s = "S"+str(counter)
                if counter <= int(self.N * self.N * self.fill.get() / 2):
                    color = "green"
                else:
                    color = "red"

                x = random.randint(0, self.grid_size-1)
                y = random.randint(0, self.grid_size-1)

                if not self.world.patch_list[x][y]:
                    new_turtle = Schelling(world=self.world,
                                           x=x,
                                           y=y,
                                           s=s,
                                           color=color,
                                           similar_wanted=self.similar)

                    self.world.register(new_turtle)
                    counter += 1
                    self.turtles.append(new_turtle)
        else:
            print("Number of turtles exceeds world!")

    def draw_turtles(self):
        '''Method for drawing turtles on canvas.

           Calls each turtle's own method for drawing.'''
        for turtle in self.turtles:
            turtle.draw(self.canvas)
 
    def neighbouring_turtles(self):
        '''Method for updating turtles' neighbours.

           Calls on each turtle's own method for updating neighbours.'''
        for turtle in self.turtles:
            turtle.get_neighbouring_patches()
示例#31
0
fen = Tk()

size = (15, 15)
img_size = (32, 32)
photo = PhotoImage(file="sm-feu.gif")

photo_pompier = PhotoImage(file="sm-pomp.gif")

canvas = Canvas(fen, width=img_size[0] * size[0], height=img_size[1] * size[1])

canvas.pack()

i = 0


def next_move():
    global i
    canvas.delete("all")
    canvas.create_image(img_size[0] // 2, img_size[1] // 2, image=photo)
    canvas.create_image(i * img_size[0] + img_size[0] // 2,
                        i * img_size[1] + img_size[1] // 2,
                        image=photo_pompier)
    i += 1
    if i < 12:
        canvas.after(500, next_move)


canvas.after(500, next_move)

fen.mainloop()
示例#32
0
class GameController:
    def __init__(self, mode, dinos_per_gen = 10):
        #can be either a train or a game
        self.mode = mode
        self.master = Tk()
        self.width = 800
        self.height = 800
        self.canvas = Canvas(self.master, width=800, height=800, bg='#fff')
        self.infoPanel = Frame(self.master, bg='#fff')
        self.colisionMonitor = ColisionMonitor(self.master, self.canvas, self.stopGround)
        self.dinos = []
        self.dinosOnScreen = 0
        self.obstacles = []
        self.colisionMonitor = None
        self.obstacleGenerator = None
        self.initialDinoNum = dinos_per_gen
        self.game_params = {'distance': 100, 'speed': 25, 'height': 0, 'width': 50}
        self.master.bind('<r>', self.restart)
        self.scoresCheckPoint = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 80, 110, 140, 200, 250]
        self.imgs_pil_ground = [
            Image.open("./assets/ground.png"),
            Image.open("./assets/ground-1.png")]
        self.ground = ImageTk.PhotoImage(self.imgs_pil_ground[0])
        self.ground_1 = ImageTk.PhotoImage(self.imgs_pil_ground[1])
        # display image on canvas
        self.ground_id = self.canvas.create_image(0, 695, image=self.ground, anchor=NW)
        self.ground_id_1 = self.canvas.create_image(400, 695, image=self.ground_1, anchor=NW)
        self.ground_id_2 = self.canvas.create_image(800, 695, image=self.ground, anchor=NW)
        self.ground_animation_id = None
        self.interfaceObject = {}
        self.score = 0
        self.record = 0
        try:
            general_data = np.load('data/general/game.npy')
            self.general_record = general_data[0]
        except IOError as err:
            self.general_record = 0
            np.save('data/general/game.npy', np.array([0]))
        
        self.n_generations = 0
        self.game_modes =  {
            "train": "train",
            "game": "game",
            "simulation": "simulation"
        }
        self.nn_elements = {
            'neurons': [],
            'connections': []
        }
    def saveGeneralRecord(self):
        if(self.general_record<=self.score):
            print(self.general_record)
            np.save('data/general/game.npy', np.array([self.general_record]))
    def prepareInterface(self):
        #l1.grid(row = 0, column = 0, sticky = W, pady = 2)
        self.infoPanel.pack(fill='x')
        speedLabel = Label(self.infoPanel, text="Speed: "+str(self.game_params['speed'])+"/"+str(len(self.scoresCheckPoint)), bg='#fff')
        speedLabel.grid(row=0, column=0, pady=10, sticky = W)
        self.interfaceObject['speedLabel'] = speedLabel

        dinosAlive = Label(self.infoPanel, text="Dinos: "+str(self.initialDinoNum), bg='#fff')
        dinosAlive.grid(row=1, column=0, pady=10, sticky = W)
        self.interfaceObject['dinosAlive'] = dinosAlive
        
        scoreLabel = Label(self.infoPanel, text="Score: "+str(self.score), bg='#fff')
        scoreLabel.grid(row=2, column=0, pady=10, sticky = W)
        self.interfaceObject['score'] = scoreLabel
        
        record = Label(self.infoPanel, text="Record: "+str(self.record), bg='#fff')
        record.grid(row=0, column=1, padx=20, pady=10, sticky = W)
        self.interfaceObject['record'] = record
        
        n_generation = Label(self.infoPanel, text="Generation: "+str(self.n_generations), bg='#fff')
        n_generation.grid(row=1, column=1, padx=20, pady=10, sticky = W)
        self.interfaceObject['n_generation'] = n_generation
        
        general_record = Label(self.infoPanel, text="General record: "+str(self.general_record), bg='#fff')
        general_record.grid(row=2, column=1, padx=20, pady=10, sticky = W)
        self.interfaceObject['general_record'] = general_record

        weights = np.load('data/brain/best_w.npy')
        weights_flatten = weights.flatten()
        biases = np.load('data/brain/best_b.npy').flatten()
        self.nn_elements = draw_nn(width=self.width, height = self.height, nn_shape=[5, 2], weights = weights, weights_flatten = weights_flatten,biases = biases,
            canvas = self.canvas, padding=[50, 10, 400, 300], neuron_size=10)
    def animateGround(self):
        self.canvas.move(self.ground_id, -9, 0)
        self.canvas.move(self.ground_id_1, -9, 0)
        self.canvas.move(self.ground_id_2, -9, 0)
        #[left top right bottom]
        if(self.canvas.coords(self.ground_id)[0]<-400):
            self.canvas.move(self.ground_id, 1200, 0)
        if(self.canvas.coords(self.ground_id_1)[0]<-400):
            self.canvas.move(self.ground_id_1, 1200, 0)
        if(self.canvas.coords(self.ground_id_2)[0]<-400):
            self.canvas.move(self.ground_id_2, 1200, 0)
        self.ground_animation_id = self.canvas.after(20, self.animateGround)
    
    def run(self):
        if(self.mode == self.game_modes["game"]):
            self.prepareInterface()
            self.canvas.pack()
            self.prepareGame()
            self.animateGround()
            mainloop()
        elif(self.mode == self.game_modes["train"]):
            self.prepareInterface()
            self.canvas.pack()
            self.prepareTrain()
            self.animateGround()
            mainloop()
        elif(self.mode == self.game_modes["simulation"]):
            self.prepareInterface()
            self.canvas.pack()
            self.prepareSimulation()
            self.animateGround()
            mainloop()
    def decreaseDinos(self):
        self.dinosOnScreen-=1
        self.colisionMonitor.dinosOnScreen = self.dinosOnScreen
        self.updateLabels()

    def updateGameParams(self, distance=None, speed=None, height=None, width=None):
        if(not distance is None):
           self.game_params['distance'] = distance
        if(not speed is None):
           self.game_params['speed'] = speed
        if(not height is None):
           self.game_params['height'] = height 
        if(not width is None):
           self.game_params['width'] = width
        #print(self.game_params)
    def updateLabels(self):
        self.interfaceObject['speedLabel'].config(text="Speed: "+str(25 - self.game_params['speed'])+"/"+str(len(self.scoresCheckPoint)))
        self.interfaceObject['dinosAlive'].config(text="Dinos: "+str(self.dinosOnScreen)+"/"+str(self.initialDinoNum))
        self.interfaceObject['score'].config(text="Score: "+str(self.score))
        self.interfaceObject['record'].config(text="Record: "+str(self.record))
        self.interfaceObject['n_generation'].config(text="Generation: "+str(self.n_generations))
        self.interfaceObject['general_record'].config(text="General record: "+str(self.general_record))
    # create game elements
    def prepareGame(self):
        self.dinos.append(Dino(self.master, self.canvas, DinoBrain(), self.game_params, self.decreaseDinos, mode=self.mode, game_modes=self.game_modes, color="black"))
        self.dinos.append(Dino(self.master, self.canvas, DinoBrain(), self.game_params, self.decreaseDinos, mode="train", game_modes=self.game_modes, color="red"))
        self.dinos[-1].brain.load()
        self.dinosOnScreen = 2
        self.obstacleGenerator = ObstacleGenerator(self.master, self.canvas, self.updateGameParams, self.increaseScore)
        self.obstacleGenerator.updateObstaclesSpeed(self.game_params['speed'])
        self.obstacleGenerator.run()
        self.colisionMonitor = ColisionMonitor(self.master, self.canvas, self.stopGround, self.dinos, self.obstacleGenerator.obstacles, self.dinosOnScreen)
        self.colisionMonitor.run()
    # create train elements
    def prepareTrain(self):
        for i in range(self.initialDinoNum):
            self.dinosOnScreen+=1
            dino = Dino(self.master, self.canvas, DinoBrain(), self.game_params, self.decreaseDinos, mode=self.mode, game_modes=self.game_modes)
            dino.brain.load()
            self.dinos.append(dino)

        for dino in self.dinos[1:]:
            dino.brain.mutate()

        self.obstacleGenerator = ObstacleGenerator(self.master, self.canvas, self.updateGameParams, self.increaseScore)
        self.obstacleGenerator.updateObstaclesSpeed(self.game_params['speed'])
        self.obstacleGenerator.run()
        self.colisionMonitor = ColisionMonitor(self.master, self.canvas, self.stopGround, self.dinos, self.obstacleGenerator.obstacles, self.dinosOnScreen)
        self.colisionMonitor.run()
    # create simulation elements
    def prepareSimulation(self):
        for i in range(self.initialDinoNum):
            self.dinosOnScreen+=1
            dino = Dino(self.master, self.canvas, DinoBrain(), self.game_params, self.decreaseDinos, mode=self.mode, game_modes=self.game_modes)
            self.dinos.append(dino)

        self.obstacleGenerator = ObstacleGenerator(self.master, self.canvas, self.updateGameParams, self.increaseScore)
        self.obstacleGenerator.updateObstaclesSpeed(self.game_params['speed'])
        self.obstacleGenerator.run()
        self.colisionMonitor = ColisionMonitor(self.master, self.canvas, self.stopGround, self.dinos, self.obstacleGenerator.obstacles, self.dinosOnScreen)
        self.colisionMonitor.run()
    def stopGround(self):
        print("New gen")

        if(self.general_record<=self.score):
            self.general_record = self.score
            np.save('data/general/game.npy', np.array([self.general_record]))
        self.n_generations+=1
        if(self.record<self.score):
            self.record = self.score
        self.resetGameParams()
        self.canvas.after_cancel(self.ground_animation_id)
        brain_index = None
        for i, dino in enumerate(self.dinos):
            if(dino.best):
                brain_index = i
                print("best: ", brain_index)
                if(self.mode == "train"):
                    dino.brain.save()
        
        self.obstacleGenerator.updateObstaclesSpeed(self.game_params['speed'])
        self.obstacleGenerator.reset()
       
        for  i, dino in enumerate(self.dinos):
            dino.reset()
            if(i != brain_index):
                dino.setBrain(self.dinos[brain_index].brain.getClone(True))
         
        for  i, dino in enumerate(self.dinos):
            dino.game_params = self.game_params
            dino.animate()
            dino.run()
        self.score = 0

        self.dinosOnScreen = len(self.dinos)
        self.colisionMonitor.dinosOnScreen = self.dinosOnScreen

        self.updateLabels()
        self.animateGround()
        self.colisionMonitor.run()
        self.obstacleGenerator.run()
    def increaseScore(self, score):
        self.score+=score
        if(self.score in self.scoresCheckPoint):
            self.game_params['speed']-=1
            self.obstacleGenerator.updateObstaclesSpeed(self.game_params['speed'])
        if(self.score==350 and self.mode == self.game_modes['train']):
            for dino in self.dinos:
                if(dino.onScreen):
                    dino.brain.save()
        if(self.general_record<self.score):
            self.general_record = self.score
        self.updateLabels()
    def resetGameParams(self):
        self.game_params = {'distance': 100, 'speed': 25, 'height': 0, 'width': 50}
    def restart(self, event):
        for dino in self.dinos:
            dino.reset()
        self.resetGameParams()
        self.animateGround()
        self.obstacleGenerator.reset()
        self.obstacleGenerator.run()
示例#33
0
class CellMapWidget(Frame):
    def __init__(self, master, cell_size: int, step_interval: int,
                 cell_map: CellMap):
        self.cells_count = cell_map.cells_count
        self.cell_size = cell_size
        self.cell_map = cell_map
        self.step_interval = step_interval
        self.simulating = False
        self.logging = False

        self.canvas = Canvas(master,
                             width=(self.cells_count * cell_size),
                             height=(self.cells_count * cell_size),
                             bg='white')
        self.canvas.pack(side=TOP)
        self.canvas.bind('<Button-1>', self.on_click)

        self.draw()

    def draw(self):
        self.draw_grid()
        self.draw_map()

    def on_click(self, event):
        x, y = event.x // self.cell_size, event.y // self.cell_size
        self.cell_map.map[x, y] = (self.cell_map.map[x, y] + 1) % 2

        self.canvas.delete('all')
        self.draw()

    def draw_cell(self, x: int, y: int):
        self.canvas.create_rectangle(self.cell_size * x,
                                     self.cell_size * y,
                                     self.cell_size * (x + 1),
                                     self.cell_size * (y + 1),
                                     fill='black')

    def draw_grid(self):
        draw_line_func = self.canvas.create_line

        for i in range(0, self.cells_count * self.cell_size, self.cell_size):
            draw_line_func(0, i, self.cells_count * self.cell_size, i)

        for i in range(0, self.cells_count * self.cell_size, self.cell_size):
            draw_line_func(i, 0, i, self.cells_count * self.cell_size)

    def draw_map(self):
        draw_cell_func = self.draw_cell
        cells_count = self.cells_count

        for i in range(cells_count):
            for j in range(cells_count):
                if self.cell_map.map[i, j] == 1:
                    draw_cell_func(i, j)

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

        self.cell_map.step()

        if self.logging:
            self.logger.log(self.cell_map.map)

        self.draw()

    def simulate_loop(self):
        if self.simulating:
            self.step()
            self.canvas.after(self.step_interval, self.simulate_loop)

    def on_simulate(self, indicator):
        self.simulating = not self.simulating
        self.simulate_loop()

        if indicator:
            if self.simulating:
                indicator.configure(bg='red')
            else:
                indicator.configure(bg='white')

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

        self.cell_map.randomize()

        if self.logging:
            self.logger.log(self.cell_map.map)

        self.draw()

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

        self.cell_map.clear()

        if self.logging:
            self.logger.log(self.cell_map.map)

        self.draw()

    def on_set_config(self, new_map: np.ndarray):
        self.canvas.delete('all')

        self.cell_map.map = new_map

        if self.logging:
            self.logger.log(self.cell_map.map)

        self.draw()

    def on_start_log(self, session_name: str = 'default'):
        self.logging = True
        self.logger = Logger()
        self.logger.start_session(self.cell_map.map, session_name)

    def on_end_log(self):
        self.logger.end_session()
        self.logging = False

    def on_log(self, indicator, session_name: str = 'default'):
        if not self.logging:
            indicator.configure(bg='red')
            self.on_start_log(session_name)
        else:
            indicator.configure(bg='white')
            self.on_end_log()
示例#34
0
class ConnectedFrame:
    def __init__(self, logicManager, root):
        self.logicManger = logicManager
        self.deviceName = self.logicManger.getDeviceName()
        self.battery = self.logicManger.getBattery()
        # images setup
        self.backgroundImg = None
        self.batteryImg = None
        self.logoutImg = None
        self.initPictures()
        # frame setup
        self.frame = None
        self.nameLabel = None
        self.batteryLabel = None
        self.moveLabel = None
        self.files_list = None
        self.logout_button = None
        self.timeUpdate = 1000  # in ms
        self.initFrame(root)

    def initPictures(self):
        self.backgroundImg = getPhoto('\\img\\MainScreen.png')
        self.batteryImg = getPhoto('\\img\\battery.png')
        self.logoutImg = getPhoto('\\img\\LogoutButton.png')

    def initFrame(self, root):
        self.frame = Canvas(root, bg=BLACK)
        self.frame.create_image(0, 0, anchor=NW, image=self.backgroundImg)
        self.frame.pack(expand="true", fill="both")
        y_grid = 1
        x_grid = 0
        pady = (45, 20)
        padx = 20
        y_grid = self.initHeader(self.frame, y_grid, x_grid, pady, padx)
        pady = 0
        y_grid = self.initMainBlock(self.frame, y_grid, x_grid, pady, padx)
        pady = 15
        padx = 10
        self.initButton(self.frame, y_grid, pady, padx)
        self.frame.after(self.timeUpdate, self.updateFrame)

    def initHeader(self, frame, y_grid, x_grid, pady, padx):
        rapper_frame = Frame(frame, bg=WHITE)
        inner_frame = Frame(rapper_frame, bg=DARK_GRAY_BLUE, height=100)
        inner_frame.pack()
        devicename = self.deviceName
        if devicename is not None and len(devicename) > 12:
            devicename = devicename[0:14] + '\n' + devicename[14:]
        self.nameLabel = Label(inner_frame,
                               text=devicename,
                               width=16,
                               font=DEVICE_HEADER_FONT,
                               bg=DARK_GRAY_BLUE,
                               fg=WHITE)
        self.nameLabel.grid(row=0, column=0)
        battery = str(self.battery) + '%   '
        self.batteryLabel = Label(inner_frame,
                                  text=battery,
                                  width=85,
                                  font=BATTERY_HEADER_FONT,
                                  bg=DARK_GRAY_BLUE,
                                  image=self.batteryImg,
                                  fg=BLACK,
                                  compound="center")
        self.batteryLabel.grid(row=0, column=1, padx=(15, 0))
        rapper_frame.grid(row=y_grid,
                          column=x_grid,
                          rowspan=1,
                          columnspan=1,
                          padx=padx,
                          pady=pady)
        return y_grid + 1

    def initMainBlock(self, frame, y_grid, x_grid, pady, padx):
        rapper_frame = Frame(frame, bg=WHITY_BLUE)
        rapper_frame.grid(row=y_grid, column=x_grid, rowspan=1, columnspan=2)
        self.initMouseMovementView(rapper_frame, y_grid, 0, pady, padx)
        self.initFilesView(rapper_frame, y_grid + 1, 0, pady, 0)
        return y_grid + 2

    def initMouseMovementView(self, frame, y_grid, x_grid, pady, padx):
        inner_frame = Frame(frame, bg=WHITY_BLUE)
        inner_frame.grid(row=y_grid,
                         column=x_grid,
                         rowspan=1,
                         columnspan=1,
                         padx=(4, 11))
        label = Label(inner_frame,
                      text='Last Mouse Move:',
                      width=18,
                      font=BATTERY_HEADER_FONT,
                      bg=DARK_GRAY_BLUE,
                      fg=WHITE)
        label.pack(side="left")
        self.moveLabel = Label(inner_frame,
                               text='',
                               width=7,
                               font=BATTERY_HEADER_FONT,
                               bg=WHITY_BLUE,
                               fg=BLACK)
        self.moveLabel.pack(side="right")
        return y_grid + 2

    def initFilesView(self, frame, y_grid, x_grid, pady, padx):
        inner_frame = Frame(frame, bg=BLACK)
        inner_frame.grid(row=y_grid,
                         column=x_grid,
                         rowspan=2,
                         columnspan=2,
                         padx=padx,
                         pady=pady)
        title = Label(inner_frame,
                      text='Recived Files:',
                      width=26,
                      font=BATTERY_HEADER_FONT,
                      bg=DARK_GRAY_BLUE,
                      fg=WHITE)
        title.pack()

        def open(event):
            file = self.files_list.curselection()
            file = self.files_list.get(file)
            self.logicManger.openFile(file)

        self.files_list = Listbox(inner_frame,
                                  bd=0,
                                  font=LISTBOX_FONT,
                                  width=29,
                                  height=10)
        self.files_list.pack(side="left", fill="y", padx=(1, 0), pady=1)
        self.files_list.contains = lambda x: x in self.files_list.get(0, "end")
        self.files_list.bind('<Double-1>', open)
        scrollbar = Scrollbar(inner_frame, orient="vertical")
        scrollbar.config(command=self.files_list)
        scrollbar.pack(side="right", fill="y", padx=(0, 2), pady=1)
        self.files_list.config(yscrollcommand=scrollbar.set)
        return y_grid + 2

    def initButton(self, frame, y_grid, pady, padx):
        rapper_frame = Frame(frame, bg=WHITE)
        self.logout_button = Button(rapper_frame,
                                    image=self.logoutImg,
                                    bg=GRAY,
                                    font=SMALL_BUTTON_FONT)
        self.logout_button.pack(anchor=E)
        rapper_frame.grid(row=y_grid, column=0, columnspan=2, pady=pady)

    def setLogoutButtonFunction(self, func):
        self.logout_button["command"] = func

    def hideFrame(self):
        self.frame.pack_forget()

    def updateFrame(self):
        self.getFiles()
        self.getDirection()
        self.getBattery()
        self.frame.after(self.timeUpdate, self.updateFrame)

    def getFiles(self):
        files = self.logicManger.getFiles()
        for file in files:
            if not self.files_list.contains(file):
                name = self.logicManger.getFileName(file)
                arr = name.split('.')
                print('name recived ', name)
                path = filedialog.asksaveasfilename(initialfile=name,
                                                    filetypes=[(arr[-1],
                                                                '*.' + arr[-1])
                                                               ])
                arr_p = path.split('/')
                if name != arr_p[-1]:
                    path += '.' + arr[-1]
                self.logicManger.saveFileWithPath(file, path)
                index = self.files_list.size()
                self.files_list.insert(index, file)

    def getDirection(self):
        direction = self.logicManger.getDirection()
        self.moveLabel['text'] = direction

    def getBattery(self):
        battery = self.logicManger.getBattery()
        battery = str(battery) + '%   '
        self.batteryLabel['text'] = battery
示例#35
0
class Jeu():
    def __init__(self):  # crée ma fanetre du jeu space invader

        self.vie = 3
        self.score = 0
        self.nb_aliens = 12

        self.liste_alien = []  #Contient les instances de la classe Alien

        #Crée la fenetre principale
        self.fenetre_principale = Tk()
        self.fenetre_principale.title("Space invaders")

    def f_lancerjeu(
            self):  #lance le jeu apres avoir appuyé sur le bouton jouer

        # dimension écran_jeu
        self.dim_ecran_jeu_x = 800
        self.dim_ecran_jeu_y = 600

        #enleve les boutons de lecran
        self.boutonJouer.destroy()
        self.ecran_menu.destroy()

        # crée l'écran de jeu
        self.ecran_jeu = Canvas(
            self.fenetre_principale, bg='white'
        )  #creation d'un canvas a linterieur de la fenetre tkinter auquel on peut ajouter des éléments
        self.ecran_jeu.pack(
            padx=5, pady=5)  #inclusion, affichage du canvas dans la fenetre
        self.ecran_jeu.config(height=self.dim_ecran_jeu_y,
                              width=self.dim_ecran_jeu_x)  #dimension ecran_jeu

        #Crée 12 instances de Alien et les place dans la liste
        for indice_alien in range(self.nb_aliens):

            self.alien = Alien(self, indice_alien)  #cree les aliens
            self.liste_alien.append(self.alien)  #cree les aliens

        self.joueur = Joueur(self)  #cree le vaisseau

        self.f_comportement_alien(
        )  # fct qui définit le comportement des aliens.

    def f_comportement_alien(self):

        for alien in self.liste_alien:  #comportement a adopter pour chacun des aliens en vie

            alien.f_deplacement()
            alien.f_tirer()

        if self.liste_alien != []:  #se répete tant qu'il y a toujours un alien sur le terrain

            self.ecran_jeu.after(30 * len(self.liste_alien),
                                 self.f_comportement_alien)

    def f_quit(self):  #fenetre confirmation quitter le jeu

        self.Quitt = Tk()
        self.Quitt.title("Etes vous sur de quitter ?")
        self.Quitt.geometry('50x25')  #dimension fentre quitter
        self.boutonOui = Button(
            self.Quitt, bg='red', text="Oui",
            command=self.f_quitter)  #bouton qui lance la fct quitter
        self.boutonNon = Button(self.Quitt,
                                bg='blue',
                                text="Non",
                                command=self.Quitt.destroy
                                )  # bouton qui renvoie a la fenetre principale
        self.boutonOui.grid(row=1, column=1)  #placement boutons
        self.boutonNon.grid(row=1, column=2)
        self.Quitt.mainloop()

    def f_quitter(self):  # quitte le jeu apres avoir cliqué sur oui

        self.Quitt.destroy()
        self.fenetre_principale.destroy()

    def f_affichage(self):  #cree le menu

        # canvas ecran de jeu
        self.ecran_menu = Canvas(
            self.fenetre_principale, bg='white'
        )  #creation d'un canvas, zone de dessin a linterieur de la fenetre tkinter auquel on peut ajouter des éléments
        self.ecran_menu.pack(
            padx=5, pady=5)  #inclusion, affichage du canvas dans la fenetre

        # affichage image menu
        self.img_ouverture = PhotoImage(file="image_menu.gif")
        self.ecran_menu.create_image(0,
                                     0,
                                     anchor="nw",
                                     image=self.img_ouverture)
        self.ecran_menu.config(height=self.img_ouverture.height(),
                               width=self.img_ouverture.width())
        self.ecran_menu.pack()

        #bouton jouer
        self.boutonJouer = Button(self.fenetre_principale,
                                  text="Jouer !",
                                  fg='red',
                                  command=self.f_lancerjeu)
        self.boutonJouer.pack()

        #bouton quitter
        self.boutonQuit = Button(self.fenetre_principale,
                                 text="Quitter",
                                 activebackground='red',
                                 activeforeground='white',
                                 command=self.f_quit)
        self.boutonQuit.pack(side='bottom')

        #Label vie
        self.affichage_vie = StringVar()
        self.affichage_vie.set('Vie : ' + str(self.vie))
        self.texteLabel_vie = Label(self.fenetre_principale,
                                    textvariable=self.affichage_vie)
        self.texteLabel_vie.pack(side='bottom')

        #label score
        self.affichage_score = StringVar()
        self.affichage_score.set('Score : ' + str(self.score))
        self.texteLabel_score = Label(self.fenetre_principale,
                                      textvariable=self.affichage_score)
        self.texteLabel_score.pack(side='bottom')

        self.fenetre_principale.mainloop()
示例#36
0
class OrbitViewWindow():
    def __init__(self, auscale, timestep, time_increment=1, start_time=None):
        """time_increment is in days.
           start_time is a an ephem.Date object.
        """
        self.auscale = auscale
        self.timestep = timestep
        self.stepping = True

        self.year = 0

        if start_time:
            self.time = start_time
        else:
            self.time = ephem.Date(datetime.now()) - ephem.hour * 24 * 7
        print("Start time:", ephem.Date(self.time))

        self.opp_date, self.closest_date = find_next_opposition(self.time)
        # print("Next opposition:", self.opp_date)
        # print("Next closest:", self.closest_date)

        self.time_increment = ephem.hour * time_increment * 24

        self.linewidth = 3

        self.width = 1024
        self.height = 768

        self.halfwidth = self.width / 2.
        self.halfheight = self.height / 2.
        self.dist_scale = self.halfheight / self.auscale

        tkmaster = Tk()
        tkmaster.title("Mars Oppositions")
        self.canvas = Canvas(tkmaster,
                             bg="black",
                             width=self.width,
                             height=self.height)
        # Start with just the Sun
        sunrad = 20
        self.canvas.create_oval(self.width / 2 - sunrad,
                                self.height / 2 - sunrad,
                                self.width / 2 + sunrad,
                                self.height / 2 + sunrad,
                                fill="yellow")
        self.canvas.pack()

        tkmaster.bind("<KeyPress-q>", sys.exit)
        tkmaster.bind("<KeyPress-space>", self.toggle_stepping)

        print(table_header)

        # Schedule the first draw
        self.step_draw()

    def toggle_stepping(self, key):
        self.stepping = not self.stepping

    def step_draw(self):
        """Calculate and draw the next position of each planet.
        """
        # If we don't call step_draw at all, we'll never get further key events
        # that could restart the animation. So just step at a much slower pace.
        if not self.stepping:
            self.canvas.after(500, self.step_draw)
            return

        # Adding a float to ephem.Date turns it into a float.
        # You can get back an ephem.Date with: ephem.Date(self.time).
        self.time += self.time_increment

        for p in (earth, mars):
            p["obj"].compute(self.time)

            # ephem treats Earth specially, what a hassle!
            # There is no ephem.Earth body; ephem.Sun gives the Earth's
            # hlon as hlon, but I guess we need to use earth_distance.
            oppy = False
            if p["name"] == "Earth":
                hlon = p["obj"].hlon
                sundist = p["obj"].earth_distance
                earthdist = 0
                size = 0
            else:
                hlon = p["obj"].hlon
                sundist = p["obj"].sun_distance
                earthdist = p["obj"].earth_distance
                size = p["obj"].size

                if abs(self.time - self.opp_date) <= .5:
                    oppy = True
                    if self.opp_date < self.closest_date:
                        print(table_format % (self.opp_date, earthdist, size),
                              "Opposition")
                        print(
                            table_format %
                            (self.closest_date, earthdist, size),
                            "Closest approach")
                    else:
                        print(
                            table_format %
                            (self.closest_date, earthdist, size),
                            "Closest approach")
                        print(table_format % (self.opp_date, earthdist, size),
                              "Opposition")

            xn, yn = self.planet_x_y(hlon, sundist)
            radius = 10

            if oppy:
                # Create outline circles for Mars and Earth at opposition.
                # xn, yn should be Mars since Earth was done first.
                self.canvas.create_oval(xn - radius,
                                        yn - radius,
                                        xn + radius,
                                        yn + radius,
                                        outline=p["color"],
                                        width=3)
                earthx = earth["xypath"][-2]
                earthy = earth["xypath"][-1]
                self.canvas.create_oval(earthx - radius,
                                        earthy - radius,
                                        earthx + radius,
                                        earthy + radius,
                                        outline=earth["color"],
                                        width=3)
                localtz = datetime.now().astimezone().tzinfo
                oppdate = ephem.to_timezone(self.opp_date, localtz)
                opp_str = oppdate.strftime("%Y-%m-%d") + \
                    '\n%.3f AU\n%.1f"' % (earthdist, size)
                if xn < self.width / 2:
                    if yn < self.height / 2:
                        anchor = "se"
                    else:
                        anchor = "ne"
                    xtxt = xn - radius
                else:
                    if yn < self.height / 2:
                        anchor = "sw"
                    else:
                        anchor = "nw"
                    xtxt = xn + radius
                ytxt = yn

                txtobj = self.canvas.create_text(xtxt,
                                                 ytxt,
                                                 fill="white",
                                                 justify=LEFT,
                                                 font=('sans', 14, 'bold'),
                                                 anchor=anchor,
                                                 text=opp_str)
                # Make sure it's not offscreen
                xt1, yt1, xt2, yt2 = self.canvas.bbox(txtobj)
                if xt1 < 0:
                    xtxt -= xt1
                elif xt2 > self.width:
                    xtxt -= (xt2 - self.width)
                if yt1 < 0:
                    ytxt -= yt1
                elif yt2 > self.height:
                    ytxt -= yt2 - self.height
                self.canvas.coords(txtobj, xtxt, ytxt)

                # Done with this opposition: find the next one.
                self.opp_date, self.closest_date \
                    = find_next_opposition(self.time + 500)

            p["xypath"].append(int(xn))
            p["xypath"].append(int(yn))
            if p["line"]:
                self.canvas.coords(p["line"], p["xypath"])
                self.canvas.coords(p["disk"], xn - radius, yn - radius,
                                   xn + radius, yn + radius)

            else:
                p["line"] = self.canvas.create_line(xn,
                                                    yn,
                                                    xn,
                                                    yn,
                                                    width=self.linewidth,
                                                    fill=p["color"])
                p["disk"] = self.canvas.create_oval(xn - radius,
                                                    yn - radius,
                                                    xn + radius,
                                                    yn + radius,
                                                    fill=p["color"])

            p["path"].append((hlon, sundist, earthdist, size))

        if self.stepping:
            self.canvas.after(self.timestep, self.step_draw)

    def planet_x_y(self, hlon, dist):
        return (dist * self.dist_scale * math.cos(hlon) + self.halfwidth,
                dist * self.dist_scale * math.sin(hlon) + self.halfheight)
示例#37
0
    if (event.delta > 0):
        mscale *= 1.1
        canvas.config(width=neural.XMAP * mscale, height=neural.YMAP * mscale)
        canvas.scale("all", 0, 0, 1.1, 1.1)
    elif (event.delta < 0):
        mscale *= 0.9
        canvas.config(width=neural.XMAP * mscale, height=neural.YMAP * mscale)
        canvas.scale("all", 0, 0, 0.9, 0.9)


root = Tk()
root.title("Darwin")
root.resizable(0, 0)

canvas = Canvas(root,
                width=neural.XMAP,
                height=neural.YMAP,
                bd=0,
                highlightthickness=0,
                background='white')
canvas.pack()
# full view to see all creatures, else we follows one (global ugly variable)
fullview = True
world = World(Animal, Plant)
canvas.bind("<KeyRelease>", world.keyup)
canvas.focus_set()
canvas.bind("<MouseWheel>", zoomer)
# Hack to make zoom work on Windows
root.bind_all("<MouseWheel>", zoomer)
canvas.after(100, world.display)
root.mainloop()