Example #1
0
def main():
    swarmSize = 100
    t = Turtle()
    win = Screen()
    win.setworldcoordinates(-600,-600,600,600)
    t.speed(10)
    t.hideturtle()
    t.tracer(15)

    for i in range(swarmSize):
        if random.randrange(100) == 0:
            LeaderFish()
        else:
            FocalFish()

    for i in range(5):
        Obstacle()

    for turn in range(1000):
        for schooler in Schooler.swarm:
            schooler.getNewHeading()

        for schooler in Schooler.swarm:
            schooler.setHeadingAndMove()

    win.exitonclick()
Example #2
0
def main():
    swarmSize = 100
    t = Turtle()
    win = Screen()
    win.setworldcoordinates(-600, -600, 600, 600)
    t.speed(10)
    t.hideturtle()
    t.tracer(15)

    for i in range(swarmSize):
        if random.randrange(100) == 0:
            LeaderFish()
        else:
            FocalFish()

    for i in range(5):
        Obstacle()

    for turn in range(1000):
        for schooler in Schooler.swarm:
            schooler.getNewHeading()

        for schooler in Schooler.swarm:
            schooler.setHeadingAndMove()

    win.exitonclick()
def main():
    global s, sun
    s = Screen()
    s.setup(800, 600, 50, 50)
    s.screensize(750, 550)
    createPlanetShape()
    ## setup gravitational system
    s.setworldcoordinates(-hfw*4/3, -hfw, hfw*4/3, hfw)
    gs = GravSys()
    sun = Star(mS, Vec2D(0.,0.), Vec2D(0.,0.), gs, "circle")
    sun.color("yellow")
    sun.turtlesize(1.8)
    sun.pu()
    earth = Star(mE, Vec2D(rE,0.), Vec2D(0.,vE), gs, "planet")
    earth.pencolor("green")
    earth.shapesize(0.8)
    mercury = Star(mME, Vec2D(0., perihelME), Vec2D(-perihelvME, 0),
                                                        gs, "planet")
    mercury.pencolor("blue")
    mercury.shapesize(0.5)
    venus = Star(mVE, Vec2D(-rVE, 0.), Vec2D(0., -vVE), gs, "planet")
    venus.pencolor("blue")
    venus.shapesize(0.65)
    mars = Star(mMA, Vec2D(0., -rMA), Vec2D(vMA, 0.), gs, "planet")
    mars.pencolor("blue")
    mars.shapesize(0.45)
    gs.init()
    gs.start()
    return "Done!"
Example #4
0
def main():
    global screen, red, green, blue
    screen = Screen()
    screen.delay(0)
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)

    #red = ColorTurtle(0, .5)
    #green = ColorTurtle(1, .5)
    #blue = ColorTurtle(2, .5)
    setbgcolor()

    writer = Turtle()
    writer.ht()
    writer.pu()
    writer.goto(1, 0.3)

    #writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))

    #writer.write("我们毕业了!", align="center", font=("微软雅黑", 40, "bold"))
    writer.write("我们毕业了!", align="center", font=("宋体", 40, "bold"))

    writer.goto(1, 0.5)
    writer.write("我们毕业了!", align="center", font=("微软雅黑", 40, "bold"))

    writer.goto(1, 0.7)
    writer.write("我们毕业了!", align="center", font=("楷体", 40, "bold"))

    return "EVENTLOOP"
Example #5
0
    def main(self):
        global screen, red, green, blue
        screen = Screen()
        screen.delay(0)
        screen.setworldcoordinates(-1, -0.3, 3, 1.3)

        red = ColorTurtle(0, .5)

        green = ColorTurtle(1, .5)

        blue = ColorTurtle(2, .5)

        setbgcolor()

        writer = Turtle()

        writer.ht()

        writer.pu()

        writer.goto(1, 1.15)

        writer.write("DRAG!",
                     align="center",
                     font=("Arial", 30, ("bold", "italic")))

        return "EVENTLOOP"

        if __name__ == "__main__":

            msg = main()

        print(msg)
def drawPaths(bodies, skip):
    bounds = getBounds(bodies)
    win = Screen()
    win.setworldcoordinates(bounds[0]-0.05*(bounds[3]-bounds[0]), bounds[1]-0.05*(bounds[4]-bounds[1]), bounds[3]+0.05*(bounds[3]-bounds[0]), bounds[4]+0.05*(bounds[4]-bounds[1]))

    turtles = [Turtle() for body in bodies]
    numTimeSteps = len(bodies[0].getHistory()['position'])
    colors = ["red", "green", "blue", "black", "purple", "pink"]

    for (index, turtle) in enumerate(turtles):
        color = colors[index]
        turtle.fillcolor(color)
        turtle.speed(0)
        turtle.pencolor(color)

    for time in range(0, numTimeSteps, skip):
        for (index, body) in enumerate(bodies):
            # print(body)
            if time == 0:
                turtles[index].up()
            # turtles[index].pensize(
            #     body.getHistory()['velocity'][time].norm()/8)
            turtles[index].goto(
                body.getHistory()['position'][time].toList()[0:2])
            if time == 0:
                turtles[index].down()
    win.exitonclick()
Example #7
0
def setEnv():
    # Set the window size
    # ADD 2 FOR BOREDER !
    WIDTH, HEIGHT = 130, 130
    # Init the screen to be able to change default size
    screen = Screen()
    screen.setup(WIDTH, HEIGHT)
    # set the pointer position
    screen.setworldcoordinates(-64, -64, 64, 64)
    return screen
Example #8
0
class WorkSpace:
    def __init__(self, size, r, c, v):
        self.canvas = Screen()
        self.size = size
        self.canvas.setup(width=size, height=size)
        self.canvas.setworldcoordinates(-1, -1, size, size)
        self._add_particles(2, r, c, v)
        self.v = v

    def _add_particles(self, n, r, c, v):
        self.particles = []
        for i in range(n):
            self.particles.append(Particle(radius=r, color=c, velocity=v))
        self.particles[0].set_initial_pos((self.size // 2 - 20, self.size / 2))
        self.particles[1].set_initial_pos((self.size // 2 + 20, self.size / 2))

    def move_all(self, step):
        while step > 0:
            for p in self.particles:
                self._move_one(p)
                p.draw()
                if p.color == 'blue':
                    self.particles.remove(p)
            for p in self.particles:
                self.change_color(p)
            step -= 1
        self.canvas.exitonclick()

    def _move_one(self, p):
        pos = p.get_current_pos()
        while True:
            offset = self._generate_new_pos()
            x, y = int(pos[0] + offset[0]), int(pos[1] + offset[1])
            if 0 <= x <= self.size and 0 <= y <= self.size:
                p.move((x, y))
                break

    def change_color(self, curr):
        curr_pos = curr.get_current_pos()
        for p in self.particles:
            if p == curr:
                continue
            if self.collide(curr_pos, p.get_current_pos()):
                curr.set_color('blue')
                p.set_color('blue')

    def collide(self, pos1, pos2):
        if (pos1[0] - pos2[0])**2 + (pos1[1] - pos2[1])**2 < (self.v)**2:
            return True
        return False

    def _generate_new_pos(self):
        random_angle = random() * pi * 2
        return (self.v * cos(random_angle), self.v * sin(random_angle))
Example #9
0
def draw_screen(TURTLE_COUNT):
    # create window
    win = Screen()
    win.setup(WIDTH, HEIGHT)
    win.setworldcoordinates(0, 0, WIDTH, HEIGHT)
    win.title("Turtle Race")

    # color background
    win.bgcolor("chocolate")

    # draw white track lines
    pen = Turtle()
    pen.hideturtle()
    pen.speed(0)
    pen.color("white")
    WHITE_LINES = TURTLE_COUNT + 1
    v_spacing = HEIGHT // WHITE_LINES
    for i in range(WHITE_LINES):
        pen.penup()
        pen.goto(0, i * v_spacing + v_spacing // 2)
        pen.pendown()
        pen.forward(WIDTH)

    # draw finish line
    white_square = Turtle("square")
    white_square.color("white")
    white_square.penup()
    white_square.speed(0)

    black_square = Turtle("square")
    black_square.color("black")
    black_square.penup()
    black_square.speed(0)

    FIRST_ROW_X = WIDTH - WIDTH // 20
    SECOND_ROW_X = FIRST_ROW_X + 21.5
    BASE_Y = HEIGHT - HEIGHT // 50
    OFFSET_Y = HEIGHT - HEIGHT // 50 - 21.5

    for i in range(HEIGHT // 40):
        # first column of white squares
        stamp_square(white_square, FIRST_ROW_X, BASE_Y - 43 * i)

        # second column of black squares
        stamp_square(black_square, SECOND_ROW_X, BASE_Y - 43 * i)

        # first column of black squares
        stamp_square(black_square, FIRST_ROW_X, OFFSET_Y - 43 * i)

        # second column of white squares
        stamp_square(white_square, SECOND_ROW_X, OFFSET_Y - 43 * i)

    return win, v_spacing, pen
Example #10
0
def main():
    e = Turtle()
    s = Screen()
    s.setworldcoordinates(-4, -2, 4, 2)
    s.bgcolor('gray12')
    s.reset()
    e.shapesize(2, 2, 2)
    e.pencolor('grey45')
    e.pensize(4)
    line(-4, 0, 4, 0, e)
    line(0, -2, 0, 2, e)
    graph(sin, e, 'red')
    graph(cos, e, 'yellow')
    return "DONE! :-)"
Example #11
0
def main():
    global screen, red, green, blue
    screen = Screen()
    screen.delay(0)
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)
    red = ColorTurtle(0, 0.5)
    green = ColorTurtle(1, 0.5)
    blue = ColorTurtle(2, 0.5)
    setbgcolor()
    writer = Turtle()
    writer.ht()
    writer.pu()
    writer.goto(1, 1.15)
    writer.write('DRAG!', align='center', font=('Arial', 30, ('bold',
        'italic')))
    return 'EVENTLOOP'
Example #12
0
def main():
    # Dimensiones ventana
    ancho = 625
    alto = 625

    # Lectura de datos
    num_aprobados = int(input("Aprobados: "))
    num_suspensos = int(input("Suspensos: "))
    num_notables = int(input("Notables: "))
    num_sobresalientes = int(input("Sobresalientes: "))

    # Convirtiendo a porcentajes
    total = num_aprobados + num_notables + num_sobresalientes + num_suspensos
    aprobados = (num_aprobados * 100) / total
    suspensos = (num_suspensos * 100) / total
    notables = (num_notables * 100) / total
    sobresalientes = (num_sobresalientes * 100) / total

    # Inicializacion
    pantalla = Screen()
    pantalla.setup(ancho, alto)
    pantalla.screensize(ancho - 25, alto - 25)
    pantalla.setworldcoordinates(0, 0, 100, 100)

    tortuga = Turtle()
    tortuga.speed(0)
    tortuga.penup()
    tortuga.setheading(90)
    tortuga.forward(10)
    tortuga.setheading(0)
    tortuga.pendown()

    # Dibujando barras
    dibuja_barra(tortuga, aprobados, "aprobados", 10)
    reubica_tortuga(tortuga, 2, 10)

    dibuja_barra(tortuga, suspensos, "suspensos", 10)
    reubica_tortuga(tortuga, 2, 10)

    dibuja_barra(tortuga, notables, "notables", 10)
    reubica_tortuga(tortuga, 2, 10)

    dibuja_barra(tortuga, sobresalientes, "sobresalientes", 10)

    tortuga.hideturtle()
    pantalla.exitonclick()
def main():
    turtle = Turtle()
    screen = Screen()
    screen.setworldcoordinates(-4, -2.5, 4, 2.5)
    screen.bgcolor('gray12')
    screen.reset()
    turtle.shapesize(1, 1, 1)
    turtle.pencolor('grey45')
    turtle.pensize(4)
    turtle.speed("fast")

    # Draw grid
    x = -4
    while x <= 4.1:
        turtle.goto(x, 0)
        if round(x, 3) % 1 == 0:
            turtle.goto(x, 0.4)
            turtle.goto(x, -0.4)
        turtle.goto(x, 0)
        x += 0.2
        print("x =", round(x, 4))

    turtle.penup()
    x = 0
    y = -2
    while y <= 2:
        turtle.goto(0, y)
        turtle.pendown()
        if round(y, 3) % 1 == 0:
            turtle.goto(0.4, y)
            turtle.goto(-0.4, y)
        turtle.goto(0, y)
        y += 0.2
    turtle.pencolor('red')

    # Move turtle to start point
    x = -4
    turtle.penup()
    turtle.goto(x, 0)
    turtle.pendown()

    # Draw graph
    while x <= 4:
        turtle.goto(x, sin(x))
        x += 0.1
    return "DONE! :-)"
Example #14
0
def main():
    global screen, red, green, blue
    screen = Screen()
    screen.delay(0)
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)

    red = ColorTurtle(0, .11111111)
    green = ColorTurtle(1, .884444)
    blue = ColorTurtle(2, .999454)
    setbgcolor()

    writer = Turtle()
    writer.ht()
    writer.pu()
    writer.goto(1,1.15)
    writer.write("EAT YOUR VEGTABLES!!!!!!!!!!!!!!!!!!!!!!!!!!!!",align="center",font=("Arial",30,("bold","italic")))
    return "EVENTLOOP"
Example #15
0
def main():
    global screen, red, green, blue
    screen = Screen()
    screen.delay(0)
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)

    red = ColorTurtle(0, .5)
    green = ColorTurtle(1, .5)
    blue = ColorTurtle(2, .5)
    setbgcolor()

    writer = Turtle()
    writer.ht()
    writer.pu()
    writer.goto(1,1.15)
    writer.write("Drag The Sliders To Change The Color!",align="center",font=("Arial",30,("bold","italic")))
    return "ColorChanger"
def main():
    global screen, red, green, blue
    screen = Screen()
    screen.delay(0)
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)

    red = ColorTurtle(0, .5)
    green = ColorTurtle(1, .5)
    blue = ColorTurtle(2, .5)
    setbgcolor()

    writer = Turtle()
    writer.ht()
    writer.pu()
    writer.goto(1,1.15)
    writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
    return "EVENTLOOP"
def main():
    global screen, red, green, blue
    screen = Screen()  # 返回窗口工作区对象
    screen.delay(0)  # 绘图无延迟
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)

    red = ColorTurtle(0, .7)
    green = ColorTurtle(1, .3)
    blue = ColorTurtle(2, .6)
    setbgcolor()

    write = Turtle()
    write.hideturtle()
    write.up()
    write.goto(1, 1.15)
    write.write("Welcome to 小周 GAME!",
                align="center",
                font=("Arial", 30, ("bold", "italic")))
Example #18
0
def main():
    # Set the window size
    WIDTH, HEIGHT = 128, 128
    # Init the screen to be able to change default size
    screen = Screen()
    screen.setup(WIDTH, HEIGHT)
    # set the pointer position
    screen.setworldcoordinates(-64, -64, 64, 64)
    turtle = Turtle()
    # Hide the pointer to be able to draw quick
    turtle.hideturtle()
    face(64, turtle)
    twoEyes('white', 'black', 8, 4, turtle)
    nose(8, turtle)
    mouse(12, turtle)
    # screen.exitonclick()
    cv = screen.getcanvas()
    cv.postscript(file="test.ps", colormode='color')
def main():
    global screen, red, green, blue
    screen = Screen()
    screen.delay(0)
    screen.setworldcoordinates(-1, -0.3, 3, 1.3)
    screen.tracer(8,25)


    red = ColorTurtle(0, .5)
    green = ColorTurtle(1, .5)
    blue = ColorTurtle(2, .5)

    writer = Turtle()
    writer.ht()
    writer.pu()
    writer.goto(1,1.15)
    writer.write("DRAG!",align="center",font=("Arial",30,("bold","italic")))
    return "EVENTLOOP"
Example #20
0
def main():
    global s, sun
    s = Screen()
    s.setup(800, 600)
    s.screensize(750, 550)
    createPlanetShape()
    ## setup gravitational system
    s.setworldcoordinates(-4.e11, -3.e11, 4.e11, 3.e11)
    gs = GravSys()
    sun = Star(mS, Vec2D(0.,0.), Vec2D(0.,0.), gs, "circle")
    sun.color("yellow")
    sun.turtlesize(1.2)
    sun.pu()
    earth = Star(mE, Vec2D(rE,0.), Vec2D(0.,vE), gs, "planet")
    earth.pencolor("green")
    gs.init()
    gs.start()
    return "Done!"
def main():
    global s, sun
    s = Screen()
    s.setup(800, 600)
    s.screensize(750, 550)
    createPlanetShape()
    ## setup gravitational system
    s.setworldcoordinates(-4.e11, -3.e11, 4.e11, 3.e11)
    gs = GravSys()
    sun = Star(mS, Vec2D(0., 0.), Vec2D(0., 0.), gs, "circle")
    sun.color("yellow")
    sun.turtlesize(1.2)
    sun.pu()
    earth = Star(mE, Vec2D(rE, 0.), Vec2D(0., vE), gs, "planet")
    earth.pencolor("green")
    gs.init()
    gs.start()
    return "Done!"
Example #22
0
def main():
    swarmSize = 50
    t = Turtle()
    win = Screen()
    win.setworldcoordinates(-600,-600,600,600)
    t.speed(10)
    t.hideturtle()
    t.tracer(15)

    for i in range(swarmSize):
        FocalFish()

    for turn in range(300):
        for schooler in Schooler.swarm:
            schooler.getNewHeading()

        for schooler in Schooler.swarm:
            schooler.setHeadingAndMove()

    win.exitonclick()
Example #23
0
def main():
    swarmSize = 30
    t = Turtle()
    win = Screen()
    win.setworldcoordinates(-600,-600,600,600)
    t.speed(10)
    t.tracer(15)
    t.hideturtle()

    for i in range(swarmSize):
        Schooler()

    #for turn in range(1000):
    while True:
        try:
            for schooler in Schooler.swarm:
                schooler.moveAllBoidsToNewPositions()
        except KeyboardInterrupt:
            break

    win.exitonclick()
Example #24
0
def ejercicio():
    x1 = float(input("LÍMITE SUPERIOR: "))
    x2 = float(input("LÍMITE INFERIOR: "))
    puntos = int(input("CANTIDAD PUNTOS: "))

    pantalla = Screen()
    pantalla.setup(825, 425)
    pantalla.screensize(800, 400)
    pantalla.setworldcoordinates(x1, -1, x2, 1)

    tortuga = Turtle()

    x = x1
    dx = (x2 - x1) / puntos
    tortuga.penup()
    tortuga.goto(x, sin(x))
    tortuga.pendown()

    while x <= x2:
        tortuga.goto(x, sin(x))
        x += dx

    pantalla.exitonclick()
Example #25
0
#LIBRERÍAS NECESARIAS PARA LA EJECUCIÓN DEL PROGRAMA
from turtle import Screen, Turtle
from math import sqrt
import sys

try:
    # CONFIGURACIÓN INICIAL DE LA VENTANA EMERGENTE CON SUS RESPECTIVAS PROPIEDADES
    pantalla = Screen()
    pantalla.setup(1020, 1025)
    pantalla.screensize(1000, 1000)
    pantalla.setworldcoordinates(-500, -500, 500, 500)
    pantalla.delay(0)

    #VALORES NECESARIOS PARA CADA UNO DE LOS CUERPOS
    x1 = -200
    y1 = -200
    velocidad_x1 = 0.1
    velocidad_y1 = 0
    m1 = 20

    # VALORES NECESARIOS PARA EL SEGUNDO CUERPO
    x2 = 200
    y2 = 200
    velocidad_x2 = -0.1
    velocidad_y2 = 0
    m2 = 20

    x3 = 300
    y3 = 300
    velocidad_x3 = 2.1
    velocidad_y3 = 0
Example #26
0
"""

from time import sleep

from turtle import Turtle, Screen
import turtle
import random
import math

screen = Screen()
screenMinX = -screen.window_width() / 2
screenMinY = -screen.window_height() / 2
screenMaxX = screen.window_width() / 2
screenMaxY = screen.window_height() / 2

screen.setworldcoordinates(screenMinX, screenMinY, screenMaxX, screenMaxY)
screen.bgcolor("black")

offscreen_x = screenMinX - 100

t = Turtle()
t.penup()
t.ht()
t.speed(0)
t.goto(0, screenMaxY - 20)
t.color('grey')
t.write("Turtles in Space!!", align="center", font=("Arial", 20))
t.goto(0, screenMaxY - 33)
t.write("Use the arrow keys to move, 'x' to fire, 'q' to quit", align="center")
t.goto(0, 0)
t.color("red")
Example #27
0
from turtle import Screen, Turtle

pantalla = Screen()
pantalla.setup(425, 425)
pantalla.screensize(400, 400)
pantalla.setworldcoordinates(-50, -150, 350, 250)

tortuga = Turtle()

tortuga.pensize(3)
tortuga.dot(10)
tortuga.forward(100)
tortuga.dot(10)
tortuga.forward(100)
tortuga.dot(10)
tortuga.forward(100)
tortuga.dot(10)

tortuga.penup()
tortuga.goto(0, 100)
tortuga.pendown()

tortuga.pencolor('red')
tortuga.pensize(5)
tortuga.circle(20)
tortuga.forward(50)
tortuga.pensize(4)
tortuga.left(20)
tortuga.circle(20)
tortuga.forward(50)
tortuga.pensize(3)
Example #28
0
        if (self.numberOfTiles[0] * self.numberOfTiles[1] -
                self.numberOfMines == totalRevealed):
            print("I was here")
            self.majorTile.number = -3
            self.majorTile.showTileContent()
            self.screen.onclick(self.endGame)


#settings
numberOfTiles = [20, 15]
numberOfMines = 40
tileSize = 32

screenSize = [
    numberOfTiles[0] * (tileSize + 1) - 1,
    numberOfTiles[1] * (tileSize + 1) - 1
]

screen = Screen()
screen.setup(screenSize[0], screenSize[1])
screen.setworldcoordinates(0, -screenSize[1], screenSize[0], 0)
screen.bgcolor("gray")
screen.tracer(0, 0)  #for making drawing instat

game = GameBoard(numberOfTiles, numberOfMines, tileSize, screenSize, screen)
print(game.tilesWithMine)
screen.onclick(game.click)  #set actions in case of mouse clicking

screen.update()  #for making drawing instat
screen.mainloop()
Example #29
0
class MazeGraphics(object):
    def __init__(self, config):
        self.width = config.getValueAsInt("maze", "maze_size")
        self.height = config.getValueAsInt("maze", "maze_size")
        self.bg_color = config.getValue("maze", "bg_color")
        self.line_color = config.getValue("maze", "line_color")
        self.line_centroid_color = config.getValue("maze", "line_centroid_color")
        self.forward_centroid_color = config.getValue("maze", "forward_centroid_color")
        self.reverse_centroid_color = config.getValue("maze", "reverse_centroid_color")
        self.path_color = config.getValue("maze", "path_color")
        self.screen = Screen()
        self.setupTurtle(self.width, self.height)

    def setupTurtle(self, width, height):
        self.screen.tracer(False)
        self.screen.screensize(width, height)
        # some basic turtle settings
        self.screen.setworldcoordinates(-1, -1, width + 1, height + 1)
        self.screen.title("Random Turtle Maze")
        self.screen.bgcolor(self.bg_color)
        self.screen.delay(None)
        self.designer = Turtle(visible=False)

    def drawGrid(self):
        for i in xrange(0, self.width + 1):
            self.drawXLines(i, self.width, self.line_color)
        for i in xrange(0, self.height + 1):
            self.drawYLines(i, self.width, self.line_color)
        self.screen.update()

    def drawXLines(self, position, width, color):
        self.drawLines(position, 0, width, color, 90)

    def drawYLines(self, position, width, color):
        self.drawLines(0, position, width, color, 0)

    def drawLines(self, xPosition, yPosition, width, color, heading):
        self.designer.up()
        self.designer.setposition(xPosition, yPosition)
        self.designer.color(color)
        self.designer.down()
        self.designer.setheading(heading)
        self.designer.forward(width)
        self.designer.up()

    def drawCentroid(self, cell, color):
        """
        Draw a centroid for animation purposes but then overwrite it.
        """
        self.designer.setposition(cell.centroid)
        self.designer.dot(5, color)
        self.screen.update()
        self.designer.dot(5, self.bg_color)

    def removeWall(self, posx, posy, heading, color):
        """
            We tear down walls to build the maze
        """
        self.designer.up()
        self.designer.setposition(posx, posy)
        self.designer.down()
        self.designer.color(color)
        self.designer.setheading(heading)
        self.designer.forward(1)
        self.designer.up()
        self.screen.update()

    def drawPath(self, cell1, cell2):
        """
            This draws a line for the solution as it's worked out.
        """
        self.designer.setposition(cell1.centroid)
        self.designer.color(self.path_color)
        direction = self.getDirection(cell1, cell2)
        if direction == "N":
            self.designer.setheading(90)
            self.designer.down()
            self.designer.forward(1)
            self.designer.up()
        elif direction == "S":
            self.designer.setheading(270)
            self.designer.down()
            self.designer.forward(1)
            self.designer.up()
        elif direction == "W":
            self.designer.setheading(0)
            self.designer.down()
            self.designer.forward(1)
            self.designer.up()
        elif direction == "E":
            self.designer.setheading(0)
            self.designer.down()
            self.designer.backward(1)
            self.designer.up()
        self.drawCentroid(cell2, self.line_centroid_color)
        self.screen.update()

    def getDirection(self, currCell, nextCell):
        direction = None
        if nextCell.x < currCell.x:
            direction = "E"
        elif nextCell.x > currCell.x:
            direction = "W"
        elif nextCell.y < currCell.y:
            direction = "S"
        elif nextCell.y > currCell.y:
            direction = "N"
        return direction
Example #30
0
    if nivel == 0:
        tortuga.forward(longitud)
    else:
        tortuga.right(45)
        dragon(tortuga, longitud / sqrt(2), nivel - 1)
        tortuga.left(90)
        nogard(tortuga, longitud / sqrt(2), nivel - 1)
        tortuga.right(45)


def nogard(tortuga, longitud, nivel):
    if nivel == 0:
        tortuga.forward(longitud)
    else:
        tortuga.left(45)
        dragon(tortuga, longitud / sqrt(2), nivel - 1)
        tortuga.right(90)
        nogard(tortuga, longitud / sqrt(2), nivel - 1)
        tortuga.left(45)


# Programa principal
pantalla = Screen()
pantalla.setup(500, 500)
pantalla.screensize(500, 500)
pantalla.setworldcoordinates(0, -350, 500, 150)

tortuga = Turtle()
tortuga.speed(0)
dragon(tortuga, 400, 10)
pantalla.exitonclick()
Example #31
0
    @:param number: is the mapped number
    @:param start1: is the lowest value of the range in which number is
    @:param stop1: is the highest value of the range in which number is
    @:param start2: is the lowest value of the range in which number is going to be
    @:param stop2: is the highest value of the range in which number is going to be
    @:return the calculated number
    """
    return ((number - start1) / (stop1 - start1)) * (stop2 - start2) + start2


HEIGHT, WIDTH = 350, 360  # Set screen width and height
ITERATION = 100  # Set max iterations

screen = Screen()
screen.setup(WIDTH, HEIGHT)  # Setup the screen
screen.setworldcoordinates(
    0, 0, WIDTH, HEIGHT)  # Set origin of the turtle in the bottom left corner

tu = Turtle()
tu.hideturtle()
tu.speed(0)
tu.penup()

screen.tracer(
    False
)  # Set screen tracer to false to speed up the process to draw the mandelbrot set

startTime = time()  # Get the current time

for x in range(WIDTH):  # Loop through every pixel in the width

    for y in range(HEIGHT):  # Loop through every pixel in the height
Example #32
0
from turtle import Turtle, Screen


# библиотека содержит функцию `Screen` которая создаёт объект экрана
# этот оъект позволяет нам общаться с окном которое открыло наша программа а так же с экраном компьютера.
# это как мы увидим далее очень полезно.
screen = Screen()

gap = 60
step = 100
canvwidth, canvheight = screen.screensize()
screen.setworldcoordinates(0 - gap, 0 - gap, (canvwidth*2 - gap), (canvheight*2 - gap))


predefined_shapes = ['arrow', 'turtle', 'circle', 'square', 'triangle', 'classic']

turtles = []
for index, shape in enumerate(predefined_shapes):
    turtle  = Turtle()
    turtle.penup()
    turtle.sety(gap*index)
    turtle.shape(shape)
    turtles.append(turtle)

t = Turtle()
t.home()
t.left(150)
t.begin_poly()
for i in range(1, 4):
    t.fd(20)
    t.right(60)
Example #33
0
    def run_turtle(self, n, instant=False, quiet=True):
        if n < 0:
            return

        cmd_str = self.yields(n)

        if not quiet:
            print("Command String: ")
            print(cmd_str)

        win = Screen()

        left, bottom, right, top = -10, -10, 10, 10
        last = (left, bottom, right, top)
        margin = 20

        win.setworldcoordinates(left, bottom, right, top)

        t = Turtle()

        t.speed(10)

        if not instant and not quiet:
            t.shape('turtle')

        win.tracer(0, 0)

        symbols = split_symbols(cmd_str)

        cmd_len = len(symbols)

        last_mark = -0.1

        if cmd_len > 200000 and not quiet:
            print("Render Progress: ", end="", flush=True)

        # for each symbol in the command string, apply to t
        for i in range(len(symbols)):
            progress = i / (float(cmd_len))
            t.color(hls_to_rgb(progress, 0.5, 0.5))
            apply_cmd(symbols[i], t, n)

            left, bottom = min(left, t.pos()[0] - margin), min(bottom, t.pos()[1] - margin)
            right, top = max(right, t.pos()[0] + margin), max(top, t.pos()[1] + margin)

            animate = not last == (left, bottom, right, top) or cmd_len < 7500

            if not instant and animate:
                win.setworldcoordinates(left, bottom, right, top)
                last = left, bottom, right, top

            if cmd_len > 200000 and progress - last_mark >= 0.1 and not quiet:
                print(str(100 * progress)[:4] + "%... ", end="", flush=True)
                last_mark = progress

        if not quiet:
            print("Render Complete.")

        win.setworldcoordinates(left, bottom, right, top)

        win.update()

        win.exitonclick()
Example #34
0
from turtle import Screen, Turtle
from math import sin, pi

pantalla = Screen()
pantalla.setup(825, 425)
pantalla.screensize(800, 400)
pantalla.setworldcoordinates(-2 * pi, -1, 2 * pi, 1)

tortuga = Turtle()

x = -2 * pi
tortuga.penup()
tortuga.goto(x, sin(x))
tortuga.pendown()

while x <= 2 * pi:
    tortuga.goto(x, sin(x))
    x += 0.5

#tortuga.goto(-1.5*pi, sin(-1.5*pi))
#tortuga.goto(-1*pi, sin(-1*pi))
#tortuga.goto(-0.5*pi, sin(-0.5*pi))
#tortuga.goto(0, sin(0))
#tortuga.goto(0.5*pi, sin(0.5*pi))
#tortuga.goto(1*pi, sin(1*pi))
#tortuga.goto(1.5*pi, sin(1.5*pi))
#tortuga.goto(2*pi, sin(2*pi))

pantalla.exitonclick()
Example #35
0
from turtle import Turtle, Screen
import colorgram
import random

colors = colorgram.extract("day-18/image.jpg", 30)
new_color = []
for i, color in enumerate(colors):
    new_color.append(tuple(colors[i].rgb))

print(random.choice(new_color))


turtle = Turtle()
screen = Screen()
screen.colormode(255)
screen.setworldcoordinates(0, 0, 500, 500)
turtle.penup()
turtle.speed("fastest")
for i in range(10):
    for j in range(10):
        turtle.dot(20, random.choice(new_color))
        turtle.forward(50)
    turtle.left(90)
    turtle.forward(50)
    turtle.right(90)
    turtle.back(500)
screen.exitonclick()
Example #36
0
XXOXXXXXXXXOOOOXXOOOOOXXX
XOOOOOOOOXXXXOOOOOXXXXXXX
XOOOOOOOOOOOOOOOOOXXXXXXX
OOOXXXXXOOOOOOOXXXXXXXXXX
OOXXXXXXXXXXXXXXXXXXXXXXX
'''

Map_Array = [list(row) for row in MAP.strip().split('\n')]
Map_Array.reverse()
Scale = 3
Stamp_Size = 20
Width, Height = len(Map_Array[0]), len(Map_Array)

screen = Screen()
screen.setup(Width * Stamp_Size * Scale, Height * Stamp_Size * Scale)
screen.setworldcoordinates(-0.5, -0.5, Width - 0.5, Height - 0.5)

turtle = Turtle('square', visible=False)
turtle.color("blue")
turtle.shapesize(Scale)
turtle.speed('fastest')
turtle.penup()

for y, row in enumerate(Map_Array):
    for x, character in enumerate(row):
        if character == 'X':
            a = (x, y)
            walls.append(a)
            turtle.goto(x, y)
            turtle.stamp()
        elif character == 'W':