Пример #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 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)
Пример #4
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)
Пример #5
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()
Пример #6
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)
Пример #7
0
def loadAndDraw(load, draw, indicatorList, trades):
    def get_mouse_click_coor(x, y):
        print(x, y)
        barNumber = round(x / 10)
        barNumber = max(1, barNumber)
        print("Bar Number: ", barNumber, " ", d[startPt + barNumber - 1], " ",
              o[startPt + barNumber - 1], " ", highestHigh)
        # tkMessageBox("Information",str(barNumber)
        # # trtl.write('Vivax Solutions', font=("Arial", 20, "bold")) # chosing the font
        ##        trtl.goto(10,highestHigh-.05*(highestHigh - lowestLow))
        ##        trtl.pendown()
        indexVal = startPt + barNumber - 1
        outPutStr = str(d[indexVal]) + " " + str(o[indexVal]) + " " + str(
            h[indexVal]) + " " + str(l[indexVal]) + " " + str(
                c[indexVal])  # chosing the font
        root.focus_set()
        T.focus_set()
        T.insert(tk.END, outPutStr + "\n")
##        trtl.goto(20,highestHigh-60)
##        trtl.write(str(o[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font
##        trtl.goto(20,highestHigh-80)
##        trtl.write(str(h[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font
##        trtl.goto(20,highestHigh-100)
##        trtl.write(str(l[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font
##        trtl.goto(20,highestHigh-120)
##        trtl.write(str(c[50-(50-barNumber)]), font=("Arial", 8, "bold")) # chosing the font

##
##    #root.withdraw()

    if load == True:
        cnt = 0
        file = askopenfilename(
            filetypes=(('CSV files', '*.csv'), ('TXT files', '*.txt'),
                       ('POR files', '*.por')),
            title='Select Markets or Ports. To Test- CSV format only!')
        with open(file) as f:
            f_csv = csv.reader(f)
            numDecs = 0
            for row in f_csv:
                numCols = len(row)
                cnt += 1
                d.append(int(row[0]))
                dt.append(datetime.datetime.strptime(row[0], '%Y%m%d'))
                o.append(float(row[1]))
                h.append(float(row[2]))
                l.append(float(row[3]))
                c.append(float(row[4]))
                v.append(float(row[5]))
                oi.append(float(row[6]))
                oString = str(o[-1])
                if '.' in oString:
                    decLoc = oString.index('.')
                    numDecs = max(numDecs, len(oString) - decLoc - 1)
        xDate = list()
        yVal = list()
        zVal = list()
        w.Button5.configure(state="normal")
        w.Entry1.insert(0, str(d[-1]))

    if draw == True:
        startDrawDateStr = w.Entry1.get()
        startDrawDate = int(startDrawDateStr)
        cnt = -1
        for x in range(0, len(d)):
            cnt += 1
            if startDrawDate >= d[x]: startPt = x
        numBarsPlot = 60
        if startPt + numBarsPlot > len(d): startPt = len(d) - (numBarsPlot + 1)
        print(startPt, " ", len(d), " ", numBarsPlot)

        indicCnt = 0
        screen = TurtleScreen(w.Canvas1)

        trtl = RawTurtle(screen)

        screen.tracer(False)

        screen.bgcolor('white')
        clr = ['red', 'green', 'blue', 'yellow', 'purple']
        trtl.pensize(6)
        trtl.penup()
        trtl.color("black")
        highestHigh = 0
        lowestLow = 99999999
        #        scaleMult = 10**numDecs
        scaleMult = 1
        for days in range(startPt, startPt + numBarsPlot):
            if h[days] * scaleMult > highestHigh:
                highestHigh = h[days] * scaleMult
            if l[days] * scaleMult < lowestLow: lowestLow = l[days] * scaleMult
        hhllDiffScale = (highestHigh - lowestLow) / 1.65
        hhllDiff = highestHigh - lowestLow
        botOfChart = lowestLow
        screen.setworldcoordinates(-10, highestHigh - hhllDiffScale, 673,
                                   highestHigh)
        print(highestHigh, " ", lowestLow)
        m = 0
        trtl.setheading(0)
        trtl.penup()

        for i in range(startPt, startPt + numBarsPlot + 1):
            m = m + 1
            trtl.goto(m * 10, h[i] * scaleMult)
            trtl.pendown()
            trtl.goto(m * 10, l[i] * scaleMult)
            trtl.penup()
            trtl.goto(m * 10, c[i] * scaleMult)
            trtl.pendown()
            trtl.goto(m * 10 + 5, c[i] * scaleMult)
            trtl.penup()
            trtl.goto(m * 10, o[i] * scaleMult)
            trtl.pendown()
            trtl.goto(m * 10 - 5, o[i] * scaleMult)
            trtl.penup()
            trtl.goto(10, highestHigh)
        print("Indicator List: ", indicatorList)
        if len(indicatorList) != 0:
            movAvgParams = list([])
            if "movAvg" in indicatorList:
                movAvgVal = 0
                movAvgParamIndexVal = indicatorList.index("movAvg")
                movAvgParams.append(indicatorList[movAvgParamIndexVal + 1])
                movAvgParams.append(indicatorList[movAvgParamIndexVal + 2])
                movAvgParams.append(indicatorList[movAvgParamIndexVal + 3])
                for j in range(0, 3):
                    n = 0
                    trtl.penup()
                    if j == 0: trtl.color("red")
                    if j == 1: trtl.color("green")
                    if j == 2: trtl.color("blue")
                    for i in range(startPt, startPt + numBarsPlot):
                        n = n + 1
                        movAvgVal = 0
                        for k in range(i - movAvgParams[j], i):
                            movAvgVal = movAvgVal + c[k] * scaleMult
                        if movAvgParams[j] != 0:
                            movAvgVal = movAvgVal / movAvgParams[j]
                            if i == startPt: trtl.goto(n * 10, movAvgVal)
                            trtl.pendown()
                            trtl.goto(n * 10, movAvgVal)
                trtl.penup()


#       print("PlotTrades : ",plotTrades)
        if trades.draw:
            debugTradeDate = tradeDate[0]
            debugDate = d[startPt]
            n = 0
            while debugTradeDate <= debugDate:
                n += 1
                debugTradeDate = tradeDate[n]

            m = 0
            for i in range(startPt, startPt + numBarsPlot):
                m = m + 1
                debugDate = d[i]
                if debugDate == debugTradeDate:
                    trtl.penup()
                    tradeValue = tradePrice[n]
                    if tradeType[n] == "buy":
                        trtl.color("Green")
                        trtl.goto(m * 10 - 5, tradeValue - hhllDiff * .03)
                        trtl.pensize(3)
                        trtl.pendown()
                        trtl.goto(m * 10, tradeValue)
                        trtl.goto(m * 10 + 5, tradeValue - hhllDiff * .03)
                        trtl.penup()
                    if tradeType[n] == "sell":
                        trtl.color("Red")
                        trtl.goto(m * 10 - 5, tradeValue + hhllDiff * .03)
                        trtl.pensize(3)
                        trtl.pendown()
                        trtl.goto(m * 10, tradeValue)
                        trtl.goto(m * 10 + 5, tradeValue + hhllDiff * .03)
                        trtl.penup()
                    if tradeType[n] == "longLiq":
                        trtl.color("Blue")
                        trtl.penup()
                        trtl.goto(m * 10 - 5, tradeValue)
                        trtl.pensize(3)
                        trtl.pendown()
                        trtl.goto(m * 10 + 5, tradeValue)
                        trtl.penup()
                    trtl.pensize(1)
                    print("Found a trade: ", tradeValue, " ", debugTradeDate,
                          " m= ", m, " ", tradeValue - hhllDiff * .05)
                    n += 1
                    if n < len(tradeDate): debugTradeDate = tradeDate[n]

        trtl.color("black")
        trtl.goto(-10, botOfChart)
        trtl.pendown()
        trtl.goto(673, botOfChart)
        trtl.penup()
        trtl.goto(-10, botOfChart)

        m = 0
        for i in range(startPt, startPt + numBarsPlot):
            if i % 10 == 0:
                m = m + 1
                trtl.pendown()
                trtl.write(str(d[i]),
                           font=("Arial", 8, "bold"))  # chosing the font
                trtl.penup()
                trtl.goto(m * 100, botOfChart)

        trtl.penup()
        trtl.goto(628, highestHigh)
        trtl.pendown()
        trtl.goto(628, botOfChart)
        trtl.penup()
        m = 0
        vertIncrement = hhllDiff / 10
        for i in range(0, 11):
            trtl.goto(630, highestHigh - m * vertIncrement)
            trtl.pendown()
            trtl.write(str(highestHigh - m * vertIncrement),
                       font=("Arial", 8, "bold"))
            trtl.penup()
            m += 1

        # turtle.done()
        screen.onscreenclick(get_mouse_click_coor)
Пример #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
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
    if nx is not None:
        t.setx(nx)
    if ny is not None:
        t.sety(ny)


# intialise screen and turn off auto-render
window = TK.Canvas(width=W, height=H)
window.pack()

#from turgles import TurgleScreenBase
#TurtleScreen.__bases__ = (TurgleScreenBase,)
#window = pyglet.window.Window(width=W, height=H)

s = TurtleScreen(window)
s.tracer(0, 0)

# random initial positions
turtles = [RawTurtle(s) for i in range(n)]
for t in turtles:
    t.ht()
    t.penup()
    t.goto(randint(0, W) - W / 2, randint(0, H) - H / 2)
    t.right(randint(0, 360))
    t.st()
    t.pendown()


def random_walk(t):
    """Simple random walk"""
    angle = random() * max_turn * 2 - max_turn
Пример #11
0
        t.setx(nx)
    if ny is not None:
        t.sety(ny)


# intialise screen and turn off auto-render
window = TK.Canvas(width=W, height=H)
window.pack()

#from turgles import TurgleScreenBase
#TurtleScreen.__bases__ = (TurgleScreenBase,)
#window = pyglet.window.Window(width=W, height=H)


s = TurtleScreen(window)
s.tracer(0, 0)


# random initial positions
turtles = [RawTurtle(s) for i in range(n)]
for t in turtles:
    t.ht()
    t.penup()
    t.goto(randint(0, W) - W / 2, randint(0, H) - H / 2)
    t.right(randint(0, 360))
    t.st()
    t.pendown()


def random_walk(t):
    """Simple random walk"""