示例#1
0
class Gamefield:
    """Die Klasse Bescreibt wie ein Feld aussieht (Muss kein Gamefeld sein)"""
    def __init__(self, tkFrame, backgroundColor):
        self.rootWindow = TurtleScreen(tkFrame)
        self.rootWindow.bgcolor(backgroundColor)
        self.rootWindow.tracer(0)


    def getRootWindow(self):
        return self.rootWindow
    
    # In der gameListenToPresskey Methode werden alle move Methoden einem Tastatur-Knopf zugewiesen. (für die erste Schlange) 
    def gameListenToPresskey(self, basilisk):
        self.rootWindow.listen()
        self.rootWindow.onkeypress(basilisk.moveUpwards, "Up")
        self.rootWindow.onkeypress(basilisk.moveDownwards, "Down")
        self.rootWindow.onkeypress(basilisk.moveLeftwards, "Left")
        self.rootWindow.onkeypress(basilisk.moveRightwards, "Right")
    
    # In der gameListenToPresskey Methode werden alle move Methoden einem Tastatur-Knopf zugewiesen. (für die zweite Schlange) 
    def gameListenToPresskeyForTowPlayer(self, basilisk):
        self.rootWindow.listen()
        self.rootWindow.onkeypress(basilisk.moveUpwards, "w")
        self.rootWindow.onkeypress(basilisk.moveDownwards, "s")
        self.rootWindow.onkeypress(basilisk.moveLeftwards, "a")
        self.rootWindow.onkeypress(basilisk.moveRightwards, "d")
    
    def gamefieldUpdate(self):
        self.rootWindow.update()
    
    def gamefieldMainloop(self):
        self.rootWindow.mainloop()
    
    def addShape(self, gif):
        self.rootWindow.addshape(gif)
示例#2
0
class TkRenderer(BaseRenderer):

    def __init__(self, width, height, title="NinjaTurtle"):
        self.width = width
        self.height = height
        self.window_title = title

        root = Tk()
        root.wm_title(self.window_title)
        window = TK.Canvas(master=root, width=self.width, height=self.height)
        window.pack()
        self.screen = TurtleScreen(window)
        self.screen.tracer(0, 0)

        self.turtles = dict()

    def create_turtle(self, model, init=None, shape='classic'):
        # TODO use init
        backend = RawTurtle(canvas=self.screen)
        model.backend = backend
        self.turtles[model.id] = model

    def render(self):
        for model in self.turtles.values():
            data = model.data
            turtle = model.backend
            if data[0] != turtle.xcor() or data[1] != turtle.ycor():
                turtle.setpos(data[0], data[1])
            if turtle.heading() != data[4]:
                turtle.setheading(data[4])
        self.screen.update()
示例#3
0
class FractalCanvas(object):
    def __init__(self, parent, levels):
        self.levels = levels
        # Toggles screen update rate
        self.slow_drawing = False

        # Draw button
        button = Button(parent, text='Draw Fractal', command=self._draw_click)
        button.pack()

        width, height = (600, 600)

        self.canvas = Canvas(parent, width=600, height=600)
        # Constrain resizing to a 1:1 aspect ratio
        self.canvas.winfo_toplevel().aspect(1, 1, 1, 1)
        self.canvas.pack(fill=BOTH, expand=YES)

        # Setup a turtle
        self.turtleScreen = TurtleScreen(self.canvas)
        # 5px of padding
        self.turtleScreen.setworldcoordinates(-5, -height - 5, width + 5, 5)
        self.turtle = RawTurtle(self.turtleScreen)
        self.turtleScreen.colormode(255)

        # Listen to resize events
        self.canvas.bind('<Configure>', self._resize_and_draw)

        # Do an initial draw
        self.slow_drawing = True
        self._resize_and_draw()
        self.slow_drawing = False

    def _draw_click(self):
        """Handler for button click."""
        # Draw the fractal slowly when we press the button, but quickly
        # if we're drawing for a resize
        self.slow_drawing = True
        self._resize_and_draw()
        self.slow_drawing = False

    def _resize_and_draw(self, event=None):
        """Handler for when the canvas resizes (due to a window resize)."""
        self.draw(self.canvas.winfo_width(), self.canvas.winfo_height())

    def draw(self, width, height):
        """Draws the fractal."""
        pass

    def update_screen(self):
        """
        Conditionally updates the screen.
        If self.slow_drawing is set, then this method forces image data to be
        pushed to the screen, otherwise it does nothing.
        """
        if self.slow_drawing:
            self.turtleScreen.update()
示例#4
0
class TurtleWorld(object):
    def __init__(self, width, height, borders=wrap, title="TurtlePower"):
        self.width = width
        self.half_width = width // 2
        self.height = height
        self.half_height = height // 2
        self.borders = borders
        self.window_title = title

        self.init_screen()

        self.fps = 0
        self.done = True
        self.turtles = []

    def init_screen(self):
        # intialise screen and turn off auto-render
        root = Tk()
        root.wm_title(self.window_title)
        window = TK.Canvas(master=root, width=self.width, height=self.height)
        window.pack()
        self.screen = TurtleScreen(window)
        self.screen.tracer(0, 0)

    def position_turtle(self, t, pos=None, angle=None):
        # move to location
        t.hideturtle()
        t.penup()
        if pos is None:
            pos = (randint(-self.half_width, self.half_width),
                   randint(-self.half_height, self.half_height))
        x, y = pos
        t.goto(x, y)
        if angle is None:
            angle = random() * 360
        t.setheading(angle)
        # ready to go
        t.showturtle()
        t.pendown()
        return t

    def random_position(self, turtle):
        return self.position_turtle(turtle)

    def _print_fps(self):  # pragma: no cover
        if not self.done:
            print(self.fps)
            self.screen.ontimer(self._print_fps, 1000)
        self.fps = 0

    def create_turtle(self, callback, pos=None, angle=None):
        t = PowerTurtle(self)
        t.set_callback(callback)
        self.position_turtle(t, pos, angle)
        self.turtles.append(t)
        return t

    def add_turtle(self, turtle):
        turtle.clear()
        self.turtles.append(turtle)

    def remove_turtle(self, turtle):
        turtle.hideturtle()
        turtle.clear()
        self.turtles.remove(turtle)

    def run(self, ticks=1000):
        # run for 1000 ticks
        self.done = False
        if DEBUG:
            self.screen.ontimer(self._print_fps, 1000)
        self.ticks = ticks
        self.screen.ontimer(self.tick, 33)
        if mainloop:
            mainloop()
        else:
            self.screen.mainloop()

    def tick(self):
        shuffle(self.turtles)
        for t in self.turtles:
            t.callback(self)
            self.borders(t, self.width, self.height)
        self.screen.update()
        self.fps += 1
        self.ticks -= 1
        if self.ticks == 0:
            self.done = True
        else:
            self.screen.ontimer(self.tick, 33)
示例#5
0
def main():
    player_N = 15
    root = TK.Tk()
    canvas = TK.Canvas(root, width=1200, height=700, bg="#ddffff")
    canvas.pack()

    turtleScreen = TurtleScreen(canvas)
    turtleScreen.bgcolor("gray")
    turtleScreen.tracer(0,0)

    pl = []
    for i in range(player_N):               #プレイヤーの生成
        random.seed()
        window_h = turtleScreen.window_height()/2
        window_w = turtleScreen.window_width()/2
        x = random.uniform(-window_w,window_w)
        y = random.uniform(-window_h,window_h)
        m = random.uniform(1,5)
        R = 600
        pl_type = random.choice(["high_level_predator","middle_level_predator","low_level_predator","producer"])
        k_high = random.uniform(0,150)
        k_middle = random.uniform(0,150)
        k_low = random.uniform(0,150)
        k_producer = random.uniform(0,150)
        if pl_type == "high_level_predator":
           #k_high = 0
           pass
        elif pl_type == "middle_level_predator":
           k_middle = 0
           k_high *= -1
        elif pl_type == "low_level_predator":
             #k_low = 0
             k_high *= -1
             k_middle *= -1
        elif pl_type == "producer":
             #k_producer = 0
             k_high *= -1
             k_middle *= -1
             k_low *= -1
        pl.append(Player(turtleScreen,pl_type,(x,y),k_high,k_middle,k_low,k_producer,m,R))
        turtleScreen.update()
        #time.sleep(1)

    while(1):
             for me in turtleScreen.turtles():
                 me.acc -= me.acc
                 for you in turtleScreen.turtles():
                     r = you.pos()-me.pos()
                     r_d = abs(r)
                     if me != you and r_d<me.R and you.isvisible():
                        me.acc += (me.get_K(you)/(me.m*pow(r_d,3)))*r
                        if me.strengthpower == you.strengthpower:
                           me.acc = 0.3*me.acc+0.7*((r_d/me.R)*me.acc + ((me.R-r_d)/me.R)*you.acc)
                        if r_d<10 :
                           if me.strengthpower > you.strengthpower:
                              you.hiding()
                              me.energy += you.energy
                              me.v -= 1.1*me.v
                           elif me.strengthpower == you.strengthpower:
                                me.v = -0.1*r
                 me.v += me.acc
                 if abs(me.v)>10:
                    me.v = me.v*(10/abs(me.v))
                 me.setpos(me.pos()+me.v)
                 if me.xcor()<-600 or me.xcor()>600 or me.ycor()<-350 or me.ycor()>350:
                    me.v = (-0.5/abs(me.pos()))*me.pos()
                    me.acc -= me.acc
                 #print(me.energy)

             turtleScreen.update()
             time.sleep(0.01)
示例#6
0
class TurtleWindow:
    ###############################################################################################################
    def __init__(self, num_vehicles, num_food_sources):
        self.root = None
        self.canvas = None
        self.wn = None
        self.button_frame = None
        self.start_button = None
        self.stop_button = None
        self.reset_button = None
        self.quit_button = None

        self.num_food_sources = num_food_sources
        self.food_source_list = []

        self.num_vehicles = num_vehicles
        self.vehicle_list = []

        self.running = False

        self.create_window()
        self.wn.tracer(0, 0)
        self.create_food_sources()
        self.create_vehicles()
        self.wn.update()

    ###############################################################################################################
    def create_window(self):
        self.root = tk.Tk()
        self.canvas = tk.Canvas(self.root,
                                width=SCREEN_SIZE,
                                height=SCREEN_SIZE)
        self.canvas.pack()
        self.wn = TurtleScreen(self.canvas)
        self.root.title("Braitenberg's Vehicle #2")
        self.wn.onkey(self.start_stop, "space")
        self.wn.listen()

        self.button_frame = tk.Frame(self.root)
        self.button_frame.pack()

        self.start_button = tk.Button(self.button_frame,
                                      text="Start",
                                      fg="black",
                                      command=self.start_stop)
        self.reset_button = tk.Button(self.button_frame,
                                      text="Reset",
                                      fg="black",
                                      command=self.reset)
        self.quit_button = tk.Button(self.button_frame,
                                     text="Quit",
                                     fg="black",
                                     command=self.quit)
        self.start_button.pack(side=tk.LEFT)
        self.reset_button.pack(side=tk.LEFT)
        self.quit_button.pack(side=tk.LEFT)

    ###############################################################################################################
    def create_food_sources(self):
        for i in range(self.num_food_sources):
            food_type = random.choice(['sugar'])
            if food_type == 'sugar':
                self.food_source_list.append(Sugar(self, i))
        print(self.food_source_list)

    ###############################################################################################################
    def create_vehicles(self):
        for i in range(self.num_vehicles):
            self.vehicle_list.append(Vehicle(self, i))

    ###############################################################################################################
    def start_stop(self):
        if self.running:
            self.running = False
            self.start_button.config(text="Start")
        else:
            self.running = True
            self.start_button.config(text="Pause")

        while self.running:
            for i in range(self.num_vehicles):
                self.vehicle_list[i].move()
            self.wn.update()
            time.sleep(0.01)

    ###############################################################################################################
    def reset(self):
        self.vehicle_list = []
        self.food_source_list = []

        self.wn.clear()
        self.wn.tracer(0, 0)
        self.create_food_sources()
        self.create_vehicles()
        self.wn.update()

    ###############################################################################################################
    @staticmethod
    def quit():
        sys.exit()
示例#7
0
class TurtleWorld(object):

    def __init__(self, width, height, borders=wrap, title="TurtlePower"):
        self.width = width
        self.half_width = width // 2
        self.height = height
        self.half_height = height // 2
        self.borders = borders
        self.window_title = title

        self.init_screen()

        self.fps = 0
        self.done = True
        self.turtles = []

    def init_screen(self):
        # intialise screen and turn off auto-render
        root = Tk()
        root.wm_title(self.window_title)
        window = TK.Canvas(master=root, width=self.width, height=self.height)
        window.pack()
        self.screen = TurtleScreen(window)
        self.screen.tracer(0, 0)

    def position_turtle(self, t, pos=None, angle=None):
        # move to location
        t.hideturtle()
        t.penup()
        if pos is None:
            pos = (randint(-self.half_width, self.half_width),
                   randint(-self.half_height, self.half_height))
        x, y = pos
        t.goto(x, y)
        if angle is None:
            angle = random() * 360
        t.setheading(angle)
        # ready to go
        t.showturtle()
        t.pendown()
        return t

    def random_position(self, turtle):
        return self.position_turtle(turtle)

    def _print_fps(self):  # pragma: no cover
        if not self.done:
            print(self.fps)
            self.screen.ontimer(self._print_fps, 1000)
        self.fps = 0

    def create_turtle(self, callback, pos=None, angle=None):
        t = PowerTurtle(self)
        t.set_callback(callback)
        self.position_turtle(t, pos, angle)
        self.add_turtle(t)
        return t

    def add_turtle(self, turtle):
        turtle.clear()
        self.turtles.append(turtle)

    def remove_turtle(self, turtle):
        turtle.hideturtle()
        turtle.clear()
        self.turtles.remove(turtle)

    def run(self, ticks=1000):
        # run for 1000 ticks
        self.done = False
        if DEBUG:
            self.screen.ontimer(self._print_fps, 1000)
        self.ticks = ticks
        self.screen.ontimer(self.tick, 33)
        self.screen.update()
        if mainloop:
            mainloop()
        else:
            self.screen.mainloop()

    def tick(self):
        shuffle(self.turtles)
        for t in self.turtles:
            t._do_callback()
            self.borders(t, self.half_width, self.half_height)
        self.screen.update()
        self.fps += 1
        self.ticks -= 1
        if self.ticks == 0:
            self.done = True
        else:
            self.screen.ontimer(self.tick, 33)
示例#8
0
class TurtleWorld(object):

    def __init__(self, width, height, borders=wrap):
        self.width = width
        self.half_width = width // 2
        self.height = height
        self.half_height = height // 2
        self.borders = borders

        # intialise screen and turn off auto-render
        window = TK.Canvas(width=width, height=height)
        window.pack()
        self.screen = TurtleScreen(window)
        self.screen.tracer(0, 0)
        self.fps = 0
        self.done = True
        self.turtles = []
        self.obstacles = []
        self.update_freq = 1000 #int(1 / 30.0 * 1000)

    def position_turtle(self, t, pos, angle):
        # move to location
        t.hideturtle()
        t.penup()
        if pos is None:
            x = randint(-self.half_width, self.half_width)
            y = randint(-self.half_height, self.half_height)
        else:
            x, y = pos
        t.goto(x, y)
        if angle is None:
            angle = random() * 360
        t.setheading(angle)
        # ready to go
        t.showturtle()
        t.pendown()
        return t


    def print_fps(self):
        if not self.done:
            print(self.fps)
            self.screen.ontimer(self.print_fps, 1000)
        self.fps = 0

    def create_turtle(self, callback, pos=None, angle=None):
        t = PowerTurtle(self)
        t.set_callback(callback)
        self.position_turtle(t, pos, angle)
        self.turtles.append(t)
        return t

    def add_turtle(self, turtle):
        turtle.clear()
        self.turtles.append(turtle)

    def remove_turtle(self, turtle):
        turtle.hideturtle()
        turtle.clear()
        self.turtles.remove(turtle)

    def add_obstacle(self, obstacle):
        self.obstacles.append(obstacle)
        self.add_turtle(obstacle)

    def something_at(self, pos):
        for obstacle in self.obstacles:
            if obstacle.contains(pos[0], pos[1]):
                return True
        return False

    def run(self, ticks=1000):
        # run for 1000 ticks
        self.done = False
        #self.screen.ontimer(self.print_fps, 1000)
        self.ticks = ticks
        self.screen.ontimer(self.tick, 33)
        mainloop()

    def tick(self):
        shuffle(self.turtles)
        for t in self.turtles:
            t.callback(self)
            self.borders(t, self.width, self.height)
        self.screen.update()
        self.fps += 1
        self.ticks -= 1
        if self.ticks == 0:
            self.done = True
        else:
            self.screen.ontimer(self.tick, 33)
示例#9
0
文件: world.py 项目: ejs/turtlepower
class TurtleWorld(object):
    def __init__(self, width, height, borders=wrap):
        self.width = width
        self.half_width = width // 2
        self.height = height
        self.half_height = height // 2
        self.borders = borders

        # intialise screen and turn off auto-render
        window = TK.Canvas(width=width, height=height)
        window.pack()
        self.screen = TurtleScreen(window)
        self.screen.tracer(0, 0)
        self.fps = 0
        self.done = True
        self.turtles = []
        self.update_freq = 1000  #int(1 / 30.0 * 1000)

    def position_turtle(self, t, pos, angle):
        # move to location
        t.hideturtle()
        t.penup()
        if pos is None:
            x = randint(-self.half_width, self.half_width)
            y = randint(-self.half_height, self.half_height)
        else:
            x, y = pos
        t.goto(x, y)
        if angle is None:
            angle = random() * 360
        t.setheading(angle)
        # ready to go
        t.showturtle()
        t.pendown()
        return t

    def print_fps(self):
        if not self.done:
            print(self.fps)
            self.screen.ontimer(self.print_fps, 1000)
        self.fps = 0

    def create_turtle(self, callback, pos=None, angle=None):
        t = PowerTurtle(self)
        t.set_callback(callback)
        self.position_turtle(t, pos, angle)
        self.turtles.append(t)
        return t

    def add_turtle(self, turtle):
        turtle.clear()
        self.turtles.append(turtle)

    def remove_turtle(self, turtle):
        turtle.hideturtle()
        turtle.clear()
        self.turtles.remove(turtle)

    def run(self, ticks=1000):
        # run for 1000 ticks
        self.done = False
        #self.screen.ontimer(self.print_fps, 1000)
        self.ticks = ticks
        self.screen.ontimer(self.tick, 33)
        mainloop()

    def tick(self):
        shuffle(self.turtles)
        for t in self.turtles:
            t.callback(self)
            self.borders(t, self.width, self.height)
        self.screen.update()
        self.fps += 1
        self.ticks -= 1
        if self.ticks == 0:
            self.done = True
        else:
            self.screen.ontimer(self.tick, 33)
示例#10
0
frames = 0


def print_frames():
    global frames
    print(frames)
    frames = 0
    s.ontimer(print_frames, 1000)


s.ontimer(print_frames, 1000)

# run for 1000 ticks
mt = mc = 0
rt = rc = 0
for i in range(200):
    start = time()
    for t in turtles:
        random_walk(t)
        wrap(t)
    mt += time() - start
    mc += 1
    start = time()
    s.update()
    rt += time() - start
    rc += 1
    frames += 1

print(mt / mc)
print(rt / rc)
示例#11
0
frames = 0


def print_frames():
    global frames
    print(frames)
    frames = 0
    s.ontimer(print_frames, 1000)

s.ontimer(print_frames, 1000)

# run for 1000 ticks
mt = mc = 0
rt = rc = 0
for i in range(200):
    start = time()
    for t in turtles:
        random_walk(t)
        wrap(t)
    mt += time() - start
    mc += 1
    start = time()
    s.update()
    rt += time() - start
    rc += 1
    frames += 1


print(mt/mc)
print(rt/rc)
示例#12
0
class GuiInterface(object):
    def __init__(self):
        self.pen = None
        self.title = "Maze AI Solver"
        self.algorithms = ["Astar", "biAstar", "IDAstar", "IDS", "UCS"]
        self.path = "ENTER PATH"
        self.mazeScreen = None
        self.pen = None
        self.root = None
        self.combo = None
        self.runtimeEntry = None
        self.canvas = None
        self.visualCheckBox = None
        self.textBox = None

    def setupInterface(self):
        # initialize windows
        self.root = Tk()
        self.root.title(self.title)
        self.root.configure(bd=10)

        # add label and choises of algorithms
        Label(self.root, text="Algorithm:").grid(row=0, column=0, sticky=W)
        self.combo = ttk.Combobox(self.root, width=10, values=self.algorithms)
        self.combo.current(4)
        self.combo.grid(row=0, column=1, sticky=W)

        # add label and time limit entry
        Label(self.root, text="Time Limit").grid(row=1, column=0, sticky=W)
        self.runtimeEntry = Entry(self.root, width=13)
        self.runtimeEntry.grid(row=1, column=1, sticky=W)
        self.runtimeEntry.insert(0, "100")

        # add choose file button
        Button(self.root,
               text="Choose file",
               width=10,
               command=lambda: self.browseFile(),
               cursor="hand2",
               activebackground="Lavender").grid(row=0, column=2, sticky=W)

        # add check button
        self.visualCheckBox = BooleanVar()
        self.visualCheckBox.set(True)
        Checkbutton(self.root,
                    text="visualize",
                    variable=self.visualCheckBox,
                    cursor="hand2").grid(row=1, column=2, sticky=W)

        # add run button
        self.textBox = StringVar()
        self.textBox.set("Welcome")
        Label(self.root, textvariable=self.textBox).grid(row=2,
                                                         column=0,
                                                         sticky=W + E,
                                                         columnspan=4)
        button_run = Button(self.root,
                            text="Run",
                            width=5,
                            height=3,
                            command=lambda: self.runButton(),
                            cursor="hand2",
                            activebackground="Lavender").grid(row=0,
                                                              column=3,
                                                              sticky=W + E,
                                                              columnspan=1,
                                                              rowspan=2)

        # create the maze window
        self.canvas = Canvas(self.root, width=630, height=630)
        self.canvas.grid(column=0, row=3, columnspan=4)

        # add the maze window inside main window
        self.mazeScreen = TurtleScreen(self.canvas)
        self.pen = Pen.getInstance(self.mazeScreen)
        self.root.mainloop()

    def runButton(self):
        # self.mazeScreen.clear()
        maxRunTime = int(self.runtimeEntry.get())
        algorithmName, startNode, goalNode, mazeSize, maze = Utilities.readInstance(
            self.path)
        algorithm, isHeuristic = self.getAlgorithmFromString(
            self.combo.get(), self.visualCheckBox.get())
        self.textBox.set("solving with " + self.combo.get() +
                         ", please wait...")
        self.mazeScreen.update()
        if isHeuristic is True:
            algorithm(maze, maxRunTime, "minimumMoves")
            #algorithm(maze, maxRunTime, "movesCount")
        else:
            algorithm(maze, maxRunTime)
        self.textBox.set("Finished running. See OutputResult.txt for results")
        self.mazeScreen.update()

    def browseFile(self):
        file = filedialog.askopenfile(parent=self.root,
                                      mode='rb',
                                      title='Choose a file')
        algorithmName, startNode, goalNode, mazeSize, maze = Utilities.readInstance(
            file.name)
        for item in self.algorithms:
            if algorithmName.lower() == item.lower():
                self.combo.current(self.algorithms.index(item))
        self.path = file.name

    def getAlgorithmFromString(self, algorithmString, isVisual):

        if algorithmString.lower() == "biastar":
            if isVisual is True:
                return BiAstarVisual, True
            else:
                return BiAstar, True

        elif algorithmString.lower() == "astar":
            if isVisual is True:
                return AstarVisual, True
            else:
                return Astar, True

        elif algorithmString.lower() == "idastar":
            if isVisual is True:
                return IDAstarVisual, True
            else:
                return IDAstar, True

        elif algorithmString.lower() == "ids":
            if isVisual is True:
                return IDSVisual, False
            else:
                return IDS, False

        elif algorithmString.lower() == "ucs":
            if isVisual is True:
                return UCSVisual, False
            else:
                return UCS, False

        else:
            return "ERROR"