Пример #1
0
def turtles_dance(tree):

    screen = Screen()

    #
    # 0. step - Create root turtle
    #
    tutroot = turtle_factory(tree[0]["nodes"][1]["color"])
    tutroot.left(tree[0]["nodes"][1]["theta"])
    tutroot.penup()
    tutroot.forward(tree[0]["nodes"][1]["radius"])
    tutroot.pendown()

    #
    # 0.5 step - Root turtle is now the base "layer" for layer 1 of turtles
    #
    base_turtle = [tutroot]

    for layer in tree[1:]:
        #
        # 1. step - clone new turtles
        #
        cloned_turtle = []
        base_num = -1
        nodes = layer["nodes"]

        for node in nodes:
            if "base_id" in node:
                base_num += 1
                print("Base_num:", base_num)
                pass
            else:
                cloned_turtle.append(
                    turtle_clonery(base_turtle[base_num], node["color"]))

        #
        # 2. Step - Make all turtles face the right direction
        #
        i = 0
        radius = []

        for node in nodes:
            if "base_id" in node:
                continue
            else:
                radius.append(int(node["radius"]))
                cloned_turtle[i].left(node["theta"])
                i += 1

        #
        # 3. Step by step run cloned turtles forward untill they hit
        #     their max radius from the base.
        #
        clone_count = len(radius)
        forward_count = [0 for i in range(clone_count)]
        opened = False

        while not opened:
            opened = True

            for i in range(clone_count):
                if forward_count[i] <= radius[i]:
                    forward_count[i] += 1

                    cloned_turtle[i].forward(1)
                    opened = False

        #
        # 4. Cloned turtles are now the base layer for the next
        #     layer of turtles
        #
        base_turtle = cloned_turtle

    screen.mainloop()
Пример #2
0
def score():
    pad_x, pad_y = paddle.position()
    pad2_x, pad2_y = paddle2.position()
    x, y = ball.position()
    s1 = 0
    s2 = 0
    if y < pad_y:
        s1 + 1
    if y < pad2_y:
        s2 + 1
    if s1 == 9:
        screen.write("BLUE WINS!!! AND IS A TRUE GAMER")
    if s2 == 9:
        screen.write("RED WINS!!! AND IS A TRUE GAMER")


# if you hit the position of the paddle reverse speed

# We assign up and down are the paddle
screen.onkey(up, "q")  # binds q key to the function up for blue()
screen.onkey(down, "a")  # binds a key to the function down for blue()
screen.onkey(up2, "p")  # binds p key to the function up for red()
screen.onkey(down2, "l")  # binds l key to the function down for red()

screen.listen()

move()
score()
screen.mainloop()  # start drawing
Пример #3
0
A = list() # Cria uma lista vazia
for c in range(7):
    try:
        A.append(int(input('Digite um valor: ')))
    except:
        print('Erro encotrado. Só números inteiros podem ser inseridos.')

cor = list()        # Cria uma lista vazia
cor.append(str(input('Digite a cor da borda: '))) # Cria um elemento para a 1ª posição da lista
cor.append(str(input('Digite a cor do prenchimento: '))) # Cria um elemento para a 2ª posição da lista

tela = Screen()     # Mostra a janela e seus atributos
tela.bgcolor("lightgreen")

touche = Turtle()   # Cria a tartaruga 
touche.pensize(3)
touche.penup()
touche.backward(120)
touche.pendown()

try:
    touche.color(cor[0], cor[1])
except:
    print('Erro encontrado. Você não inseriu uma cor válida.')

for a in A:
    histograma(touche, a)

tela.mainloop()
Пример #4
0
    turtle.shapesize(size / CURSOR_SIZE)
    turtle.stamp()

    if depth < 1:
        return

    half = size / 2
    circumradius = half * 3**0.5 / 3

    for _ in range(3):
        turtle.forward(circumradius)  # to
        sierpinski(depth - 1, turtle, half)
        turtle.backward(circumradius)  # and fro
        turtle.left(120)


window = Screen()
window.mode('logo')  # make 0 degrees straight up
window.title('Sierpinski')
window.bgcolor('lightblue')

alex = Turtle('triangle')
alex.fillcolor(window.bgcolor())
alex.penup()

sierpinski(3, alex, 1000)

alex.hideturtle()
window.mainloop()
Пример #5
0
    if nosotros.lower() == nosotros_correct.lower():
        sheet_writer.print_answer('nosotros', nosotros_correct, 'correct')
    else:
        sheet_writer.print_answer('nosotros', nosotros_correct, 'incorrect')
        all_correct = False

    # Conjugate verb for vosotros.
    vosotros = screen.textinput("Yo", "Conjugate the verb for vosotros.")
    vosotros_correct = verb.iloc[0].vosotros
    if vosotros.lower() == vosotros_correct.lower():
        sheet_writer.print_answer('vosotros', vosotros_correct, 'correct')
    else:
        sheet_writer.print_answer('vosotros', vosotros_correct, 'incorrect')
        all_correct = False

    # Conjugate verb for ellos/ellas/ustedes.
    ellos = screen.textinput("Yo",
                             "Conjugate the verb for ellos/ellas/ustedes.")
    ellos_correct = verb.iloc[0].ellos
    if ellos.lower() == ellos_correct.lower():
        sheet_writer.print_answer('ellos/ellas/ustedes', ellos_correct,
                                  'correct')
    else:
        sheet_writer.print_answer('ellos/ellas/ustedes', ellos_correct,
                                  'incorrect')
        all_correct = False

    verbs.updated_verb_info(index, all_correct)

screen.mainloop()
Пример #6
0
#Lager lamper
a = Lampe()
b = Lampe()

# Lager skilpadder
a.lag_skilpadde()
b.lag_skilpadde()

a.turtle.forward(100)
b.turtle.backward(100)

#Skru på B


def ff_pa_aav(tut, paa_av):
	def factory_slaa():
		def slaa():
			tut.slaa_ + 'paa_av'+ ()
		return slaa_ + 'paa_av'
	

s.onkey(ff_pa_aav(a, 'paa'), 'a')
s.onkey(ff_pa_aav(a, 'av'), 'z')

s.onkey(ff_pa_aav(b, 'paa'), 's')
s.onkey(ff_pa_aav(b, 'av'), 'x')
s.listen()

s.mainloop()
        return [3, 4]
    elif opc == 2:
        return [4, 6]
    else:
        return [6, 8]


# Programa principal
[filas, columnas] = menu()

pantalla = Screen()
pantalla.setup(columnas * 50, filas * 50)
pantalla.screensize(columnas * 50, filas * 50)
pantalla.setworldcoordinates(-.5, -.5, columnas + .5, filas + .5)
pantalla.delay(0)

tortuga = Turtle()
tortuga.hideturtle()
simbolo = crea_matriz(filas, columnas)
tablero = crea_matriz(filas, columnas)

temporal1 = None
temporal2 = None
inicializa_tablero(tablero)
rellena_simbolos(simbolo)
dibuja_tablero(tablero, simbolo)

pantalla.onclick(clic)

pantalla.mainloop()
Пример #8
0
        self.x = float(x)
        self.y = float(y)

    def __str__(self):
        return str(self.x) + ',' + str(self.y)


def thirdPos(pointA: PointXY, pointB: PointXY):
    third = PointXY()
    distAC = math.dist((pointA.x, pointA.y), (pointB.x, pointB.y))
    theta = math.acos((pointB.x - pointA.x) / distAC) + math.acos(1 / 2)
    third.x = distAC * math.cos(theta) + pointA.x
    third.y = distAC * math.sin(theta) + pointA.y
    return third


if __name__ == '__main__':
    screen_ = Screen()
    turtle_ = Turtle()
    screen_.setup(600, 600)
    turtle_.speed(1)
    pointA = PointXY(0, 0)
    pointB = PointXY(50, -50)
    third = thirdPos(pointA, pointB)
    turtle_.goto(pointB.x, pointB.y)
    turtle_.penup()
    turtle_.goto(pointA.x, pointA.y)
    turtle_.pendown()
    turtle_.goto(third.x, third.y)
    screen_.mainloop()
Пример #9
0
def start():
    global TSM
    global nodeAmount
    TSM = tsm(nodeAmount, moveEnds = False)
    TSM.draw()
s.onkey(start, 'Return')

def drawIterate():
    global TSM
    if TSM is None:
        start()
        return
    TSM.iterate(1000)
    TSM.draw()
s.onkey(drawIterate, 'space')

def clickedOn(x, y):
    global TSM
    if TSM is None:
        start()
        return
    TSM.toggle(x,y)

s.onclick(clickedOn)



s.listen()
s.mainloop()
Пример #10
0
class GameView(object):
    """This class handles the user facing part of the game. This draws the
    game board and components."""

    def __init__(
        self,
        controller: GameController,
        board_size: int,
        grid_size: int = 3
    ) -> None:
        self.controller = controller

        #### Setup the screen.
        # Change it to a square 50% larger than the game board size.
        self.screen = Screen()
        screen_size = int(board_size * 1.5)
        self.resize_screen(screen_size, screen_size)

        #### Setup the game board.
        # Initialize the turtle that will draw the game board.
        self.board = GameView.new_turtle()
        self.lineweight = board_size / 60
        self.board.pensize(self.lineweight)
        self.board.speed(0)
        #self.board.dot(0)

        self.board_size = board_size
        self.grid_size = grid_size
        self.grid_line_spacing = board_size / grid_size


        #### Create our player markers.
        self.players = []
        marker_scale = board_size / 100 / grid_size
        marker_lineweight = 8 * marker_scale
        self.create_player_shapes()
        self.players.append(GameView.new_turtle('x marker',
                                                marker_scale,
                                                marker_lineweight))
        self.players.append(GameView.new_turtle('o marker',
                                                marker_scale,
                                                marker_lineweight))

        #### Final initialization
        self.draw_board()
        self.screen.onclick(self.mouse_click)
        self.screen.mainloop()

    def create_player_shapes(self, color: str = 'black') -> None:
        """Creates custom turtle shapes for the x and o player markers.

        This method sets up custom shapes that can be used with the
        turtle.shape() method. Recall that you could make your turtle look
        like an actual turtle (instead of the default arrow shape) by calling
        turtle.shape('turtle'). After this method has been called, you can
        change the sape of your turtle to an x or an o by calling
        turtle.shape('x marker') or turtle.shape('o marker').

        These shapes are initialized at a size appropriate for display on a
        3x3 grid on a 300px game board.
        """

        # Build the x out of a backslash and forward slash.
        # These numbers are the vertices of the slashes.
        backslash = ((-25,-25), (25,25))
        forwardslash = ((-25,25), (25,-25))
        shape = Shape('compound')
        shape.addcomponent(backslash, '', color)
        shape.addcomponent(forwardslash, '', color)
        self.screen.register_shape('x marker', shape)

        # Approximate the o with a 20-sided polygon.
        # These numbers are the vertices of the polygon.
        circle = (( 00.00,-25.00), ( 07.73,-23.78), ( 14.69,-20.23),
                  ( 20.23,-14.69), ( 23.78,-07.73), ( 25.00, 00.00),
                  ( 23.78, 07.73), ( 20.23, 14.69), ( 14.69, 20.23),
                  ( 07.73, 23.78), ( 00.00, 25.00), (-07.73, 23.78),
                  (-14.69, 20.23), (-20.23, 14.69), (-23.78, 07.73),
                  (-25.00, 00.00), (-23.78,-07.73), (-20.23,-14.69),
                  (-14.69,-20.23), (-07.73,-23.78),)
        shape = Shape('compound')
        shape.addcomponent(circle, '', color)
        self.screen.register_shape('o marker', shape)

    def draw_line(self, x: float, y: float, heading: float, length: float) -> None:
        """Draws a line on the game board.

        Args:
            x, y: The coordinates where the line starts.
            heading: The angle of the line.
            length: The length of the line.
        """
        self.board.setheading(heading)

        self.board.penup()
        self.board.goto(x, y)

        self.board.pendown()
        self.board.forward(length)

    def draw_board(self) -> None:
        """Draws the game board centered on the point (0,0)."""
        # Each horizontal line will have a common starting x coordinate.
        # Each vertical line will have a common starting y coordinate.
        # These coordinates are equal to each other.
        anchor = self.board_size / 2

        # The y-coordinates of horizontal lines and the x-coordinates of
        # vertical lines begin equal to each other and increment equally
        increments = list(
            anchor - i * self.grid_line_spacing
            for i in range(1, self.grid_size)
        )

        for i in increments:
            self.draw_line(i, anchor, 270, self.board_size)
            self.draw_line(anchor, i, 180, self.board_size)

    def mark_play(self, player: int, space: List[int]) -> None:
        """Marks a play on the game board.

        Args:
            player: The player to mark, based on play order, starting at 1.
            space: The space to be marked. The bottom-left space is (0,0).
        """
        # Offset the space coordinates so that (0,0) becomes the center space
        space = [s - self.grid_size // 2 for s in space]

        # Calculate the pixel offset between spaces on the game board
        space_offset = self.board_size / self.grid_size

        # Find the screen coordinates of the center of the selected space on
        # the game board.
        center = [space_offset * s for s in space]

        current_player = self.players[player - 1]
        current_player.goto(*center)
        current_player.stamp()

    def mouse_click(self, x: float, y: float) -> None:
        """Handles mouse click actions."""
        # Ignore all clicks outside of the game board area
        extent = self.board_size / 2
        if not (-extent < x < extent and -extent < y < extent):
            return

        # Find the space on the board in which the mose was clicked
        # The bottom-left square is space (0,0).
        space = [round(c / self.grid_line_spacing) + self.grid_size // 2
                 for c in [x, y]]

        # Ask the controller to make a play in this space
        player = self.controller.make_play(space)

        # If the play was successful, the controller will return the player
        # who made the play
        if player:
            # Mark the play on the board
            self.mark_play(player, space)

    def resize_screen(self, width: int, height: int) -> None:
        """Resizes the screen."""
        self.screen.setup(width, height)

    @staticmethod
    def new_turtle(
        shape: Optional[str] = None,
        scale: float = 1.0,
        lineweight: float = 1.0
    ) -> Turtle:
        """Creates a new turtle and hides it.

        Args:
            shape: A valid shapename. See TurtleScreen documentation.
            scale: A factor to scale the size the turtle.
            lineweight: The thickness of the lines composing the shape.

        Yields:
            TurtleGraphicsError: For invalid shape names.
        """
        t = Turtle()
        t.shape(shape)
        t.shapesize(scale, scale, lineweight)
        t.penup()
        t.hideturtle()
        return t
Пример #11
0
chiq = Turtle()
chiq.color('red')
chiq.pensize(5)
chiq.speed(0)
chiq.hideturtle()
chiq.up()
chiq.goto(300, 300)
chiq.down()
chiq.goto(300, -300)
chiq.goto(-300, -300)
chiq.goto(-300, 300)
chiq.goto(300, 300)

top = Turtle()
top.shape('circle')
top.up()
top.goto(0, 0)
top.color('blue')
step_x = 3
step_y = 2
while True:
    x, y = top.position()
    if x + step_x >= 300 or x + step_x <= -300:
        step_x = -step_x
    if y + step_y >= 300 or y + step_y <= -300:
        step_y = -step_y
    top.goto(x + step_x, y + step_y)

oyna.mainloop()
Пример #12
0
class MazeTurtle(Turtle):
    def __init__(self, grid_size=50, maze=0):
        super().__init__()

        self.grid_size = grid_size
        self.maze_conf = MAZES[maze]

        self.screen = Screen()
        self.screen.bgcolor('black')
        self.screen.register_shape("star", ((0, 5), (-4, -5), (5, 1), (-5, 1),
                                            (4, -5)))

        # Draw the maze
        t = Turtle()
        t.color('white')
        t.shape('square')
        t.penup()
        t.resizemode('user')
        t.shapesize(2, 2, 1)
        t.speed('fastest')

        for y, row in enumerate(self.maze_conf.splitlines()):
            for x, chr in enumerate(row):
                if chr == 'X':
                    t.goto(-288 + x * self.grid_size, 288 - y * self.grid_size)
                    t.stamp()

        # Draw the goal
        maze_size = len(self.maze_conf.splitlines()) - 3

        t.shape("star")
        t.color("yellow")
        t.goto(-288 + maze_size * self.grid_size,
               288 - (maze_size + 1) * self.grid_size)
        t.setheading(90)
        t.stamp()

        self.speed('fastest')
        self.color('green')
        self.shape('turtle')
        self.showturtle()
        self.penup()
        self.goto(-288 + self.grid_size, 288 - 2 * self.grid_size)
        self.resizemode('user')
        self.shapesize(2, 2, 1)
        self.pendown()
        self.speed('slowest')

        # Key bindings
        self.screen.listen()
        self.screen.onkey(self.step_up, "Up")
        self.screen.onkey(self.step_right, "Right")
        self.screen.onkey(self.step_down, "Down")
        self.screen.onkey(self.step_left, "Left")

    def step_up(self):
        self._turn_and_move(90)

    def step_right(self):
        self._turn_and_move(0)

    def step_left(self):
        self._turn_and_move(180)

    def step_down(self):
        self._turn_and_move(-90)

    def _turn_and_move(self, heading):
        self.setheading(heading)
        self.forward(self.grid_size)

    def mainloop(self):
        self.screen.mainloop()
Пример #13
0
def week__3(myChar):

    import turtle , random
    from turtle import Turtle, Screen

    print(''' Django 볼을 획득하라!
    노란색 Django볼을 획득하면 Mission clear 됩니다.''')
    screen = Screen()
    screen.setup(1200, 500)
    Django = Turtle()
    Django.shape('circle')
    Django.color('yellow')
    Django.up()
    point_x = random.randint(-500,500)
    point_y = random.randint(-250,250) 
    Django.goto(point_x,point_y)
    player = Turtle()
    player.speed('fastest')
    PlayerY = 0
    PlayerX = 0
    
    def play():
        if player.distance(Django) < 25:
            turtle.clear()
            turtle.write("Mission Clear",False,"center",font=("Arial",50,"normal"))
            myChar.controlPiro(5)
            myChar.controlCoding(10)

        
        if player.distance(Django) > 25:
            turtle.clear()
            turtle.write("Game Over",False,"center",font=("Arial",50,"normal"))
            myChar.controlPiro(5)
            myChar.controlMoney(-2)

    def moveX():
        nonlocal PlayerX
        screen.onkeypress(None, "Right") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerX += 10
        screen.onkeypress(moveX, "Right") 
        
    def moveY():
        nonlocal PlayerY
        screen.onkeypress(None, "Up") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerY += 10
        screen.onkeypress(moveY, "Up")

    def move_X():
        nonlocal PlayerX
        screen.onkeypress(None, "Left") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerX -= 10
        screen.onkeypress(move_X, "Left")

    def move_Y():
        nonlocal PlayerY
        screen.onkeypress(None, "Down") 
        player.clear()
        player.penup()
        player.goto(PlayerX, PlayerY)
        player.pendown()
        player.shape('turtle')
        player.color('blue')
        PlayerY -= 10
        screen.onkeypress(move_Y, "Down")

    screen.listen()
    turtle.ontimer(play, 9000)
    moveY()
    moveX()
    move_X()
    move_Y()

    screen.mainloop()
points.remove(endingPoint)

routes = []
    
getRouteDistance("Route One", startingPoint, points[0], points[1], points[2], endingPoint)
getRouteDistance("Route Two", startingPoint, points[1], points[2], points[0], endingPoint)
getRouteDistance("Route Three", startingPoint, points[2], points[0], points[1], endingPoint)
getRouteDistance("Route Four", startingPoint, points[0], points[2], points[1], endingPoint)
getRouteDistance("Route Five", startingPoint, points[1], points[0], points[2], endingPoint)
getRouteDistance("Route Six", startingPoint, points[2], points[1], points[0], endingPoint)

routesSorted = sorted(routes,key=lambda l:l[1])

print(routesSorted[0])

#Turtle graphics 
scale = 15
window = Screen()
cursor = Turtle()
cursor.penup()
cursor.goto(routesSorted[0][2][0] * scale, routesSorted[0][2][1] * scale)
cursor.pendown()
for i in range(3):
    cursor.goto(routesSorted[0][i+3][0] * scale, routesSorted[0][i+3][1] * scale)
cursor.goto(routesSorted[0][6][0] * scale,routesSorted[0][6][1] * scale)

window.mainloop()    



Пример #15
0
        Dim['Y']['upper']
    ]

    win.setworldcoordinates(D[0], D[1], D[2], D[3])

    G = Grapher(Dim)
    '''
    f = lambda x : sin(x)
    interval = (0,9,0.1)
    Region1 = singlaValueFun_numGen(f,interval)
    
    x_t = lambda t : cos(t)
    y_t = lambda t: 2*sin(t)
    interval = {
        'lower' : 0,
        'upper' : 2*pi,
        'increment' : 0.1
    }
    Region2 = ParametricEqu_numGen(x_t,y_t,interval)
    '''
    r_theta = lambda theta: 3 * cos(2 * theta)
    interval = {'lower': 0, 'upper': 2 * pi, 'increment': 0.01}
    Region3 = PolarEqu_numGen(r_theta, interval)

    win.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
    win.delay(5)

    G.plot(Region3)

    win.mainloop()
Пример #16
0
TURTLE.end_fill()  # Fill the shape

TURTLE.penup()
TURTLE.goto(100, -50)
TURTLE.setheading(0)
TURTLE.left(30)
TURTLE.pendown()
TURTLE.begin_fill()  # Begin to fill color in a shape
TURTLE.color("yellow")
TURTLE.circle(40, steps=6)  # Draw a hexagon
TURTLE.end_fill()  # Fill the shape

TURTLE.penup()
TURTLE.goto(200, -50)
TURTLE.setheading(0)
TURTLE.left(22.5)
TURTLE.pendown()
TURTLE.begin_fill()  # Begin to fill color in a shape
TURTLE.color("purple")
TURTLE.circle(40, steps=8)  # Draw a circle
TURTLE.end_fill()  # Fill the shape

TURTLE.color("green")
TURTLE.penup()
TURTLE.goto(-100, 50)
TURTLE.pendown()
TURTLE.write("Cool Colorful Shapes", font=("Times", 18, "bold"))
TURTLE.hideturtle()

SCREEN.mainloop()
Пример #17
0
leo = Turtle()

leo.color('green', 'limegreen')
leo.pensize(5)

# Posiciona a caneta lá embaixo
leo.penup()
leo.goto(0, -200)
leo.pendown()
leo.left(45)

talo(leo)

# Pétalas
leo.color('moccasin', 'gold')
leo.shape("turtle")
leo.pensize(3)
leo.speed(8)

# Comando para fazer as outras pétalas
leo.begin_fill()
for c in range(petala):
    desenho(leo, comp)
    leo.left(360 / petala)
leo.end_fill()

leo.hideturtle()

est.mainloop()
Пример #18
0
    turtle.forward(sqrt(70))
    turtle.left(-145)
    turtle.forward(sqrt(70))
    turtle.penup()
    turtle.goto(WIDTH*(1.26+6),HEIGHT/2)
    turtle.right(0.20 * -90-55)
    turtle.pendown()
    turtle.forward(3.10)

LETTERS = { 'P': letter_P,'A': letter_A,'V':letter_V,'I': letter_I,'K':letter_K,'1': letter_A1}

wn = Screen()
wn.setup(800, 400)
wn.title("Turtle writing my name: {}".format(NAME))
wn.setworldcoordinates(0, 0, BOX_WIDTH * len(NAME), BOX_HEIGHT)

marker = Turtle()
marker.width(4)
for counter, letter in enumerate(NAME):
    marker.penup()
    marker.goto(counter * BOX_WIDTH + BORDER, BORDER)
    marker.setheading(90)

    if letter in LETTERS:
        marker.pendown()
        LETTERS[letter](marker)

marker.hideturtle()

wn.mainloop()
Пример #19
0
def tictoc():
    # Simulate the passage of time for each bubbble
    for b in bubbles:
        b.sim()
    ocean.update()
    ocean.ontimer(tictoc, 20)


# Create the initial set of bubbles
for i in range(numBubbles):
    blowBubble(random.randint(-50, 50), random.randint(-50, 50))

ocean.onclick(blowBubble)
ocean.ontimer(tictoc, 20)

# What happens if the line below is missing
ocean.mainloop()

numBubbles = 0
if len(sys.argv) > 1:
    numBubbles = sys.argv[1]

print("number of bubbles requested", numBubbles)
print("numBubbles type is", type(numBubbles))

# Let's add a few more
numBubbles = numBubbles + 10
print("number of bubbles to make", numBubbles)

# How did that work out?
Пример #20
0
class Plotter(object):
    """
    A plotter object provides a graphical window for plotting data and 
    mathematical functions.
    """
    def __init__(self, width, height, min_x, max_x, min_y, max_y):
        """ (Plotter, int, int, int, int, int, int) -> turtle
        
        The constructor initializes the Turtle graphics window. 
        It accepts parameters that define the window’s physical size and 
        ranges of x and y axes.

        Initializes the plotter with a window that is <width> wide and 
        <height> high. Its x-axis ranges from <min_x> to <max_x>, and it's 
        y-axis ranges from <min_y> to <max_y>.

        Establishes the global begining and ending x values for the plot and
        the x_increament value.
        Draws the x-axis and y-axes
        """
        # Init
        self.pen = Pen()  # The plotter object's pen
        self.screen = Screen()  # The plotter object's sceen

        self.pen.speed(0)  # Speed up rendering
        self.screen.tracer(0, 0)  # DONT draw pen while drawing

        # Establish global x and y ranges
        self.min_x, self.max_x = min_x, max_x
        self.min_y, self.max_y = min_y, max_y

        self.screen.setup(width=width,
                          height=height)  # Set up window size, in pixels

        # set up screen size, in pixels
        self.screen.screensize(width, height)
        self.screen.setworldcoordinates(min_x, min_y, max_x, max_y)

        # x-axis distance that correspond to one pixel in window distance
        self.x_increament = (max_x - min_x) / width
        self.draw_grid(20)
        self.draw_axes()
        self.screen.title('Plot')
        self.screen.update()

    def __del__(self):
        """ (Plotter) -> stdout

        Called when the client no longer uses the plotter object. 

        The interpreter calls this method, also known as destructor, 
        when the object is no longer bound to a reference with in the 
        executing program. 
        Among other times, this happens when the program’s execution 
        terminates.
        """
        print('Done Printing')

    def draw_axes(self, grid=False):
        """ (Plotter, bool) -> turtle

        Draws the x and y axes within the plotting window.

        An option Boolean parameter <grid> controls the drawing of
        accessory horizontal and vertical lines
        """
        if grid:
            self.draw_grid(20)
        self.pen.hideturtle()  # Make pen invisible
        prev_width = self.pen.width()
        self.pen.width(2)

        # Draw x axis
        self.pen.color('black')
        self.draw_arrow(self.min_x, 0, self.max_x, 0)

        # Draw y axis
        self.draw_arrow(0, self.min_y, 0, self.max_y)
        self.pen.width(prev_width)

    def draw_grid(self, num):
        """ (Plotter, int) -> turtle

        Draws horizontal and vertical accessory reference coordinate 
        lines on the plot. Parameter <num> control the frequency of the 
        reference lines.
        """
        self.pen.up()
        # self.pen.setposition(self.min_x, self.min_y)
        inc = (self.max_x - self.min_y) / num
        self.pen.color('lightblue')
        x = self.min_x

        while x <= self.max_x:
            self.pen.setposition(x, self.min_y)
            self.pen.down()
            self.pen.setposition(x, self.min_y)
            self.pen.up()
            x += inc  # Next x
        inc = (self.max_y - self.min_y) / num
        y = self.min_y

        while y <= self.max_y:
            self.pen.setposition(self.min_x, y)
            self.pen.down()
            self.pen.setposition(self.max_x, y)
            self.pen.up()
            y += inc  # Next y

    def draw_arrow(self, x1, y1, x2, y2):
        """ (Plotter, int, int, int, int) -> turtle

        Draws a line segment with an attached arrow head. 
        Expects four numeric parameters representing the (x 1 , y 1 ) tail end 
        point and (x 2 , y 2 ) head end point of the arrow.
        """
        # Draw arrow shaft
        self.pen.up()
        self.pen.setposition(x1, y1)  # Move the pen starting point
        self.pen.down()  # Draw line bottom to top
        self.pen.setposition(x2, y2)  # Move the pen starting point

        # Draw arrow head
        dy = y2 - y1
        dx = x2 - x1

        angle = atan2(dy, dx) * 180 / pi
        self.pen.setheading(angle)
        self.pen.stamp()

    def plot_function(self, f, color, update=True):
        """ (Plotter, func, str, bool) -> turtle
        Plots the curve of a given function <f> with a specified color,
        established by initialize_plotter.
        Plots (x, f(x)), for all x in range min_x <= x < max_x
        The color parameter dicatates the curve's color

        An optional Boolean parameter determines if the function renders 
        immediately or requires the client to call the update method after a 
        series of plots (defaults to True).    
        """
        # Move pen to starting position
        self.pen.up()
        self.pen.setposition(self.min_x, f(self.min_x))
        self.pen.color(color)
        self.pen.down()

        # Iterate over the range of x values for min_x <= x < max_x
        x = self.min_x
        while x < self.max_x:
            self.pen.setposition(x, f(x))
            x += self.x_increament  # Next x

        if update:
            self.screen.update()

    def plot_data(self, data, color, update=True):
        """ (Plotter, list, str, bool) -> turtle
        
        Plots the curve (x, y) pairs of values in data_list.
        A parameter <color> specifies the curve’s color. 
        An optional Boolean parameter determines if the function renders 
        immediately or requires the client to call the update method after a 
        series of plots (defaults to True).
        """
        self.pen.up()
        self.pen.setposition(data[0][0], data[0][1])
        self.pen.color(color)
        self.pen.down()

        # Plot the points in th data set
        for x, y in data:
            self.pen.setposition(x, y)
        if update:
            self.screen.update()

    def update(self):
        """ (Plotter) -> turtle
        
        Draws any pending actions to the screen 
        """
        self.screen.update()

    def setcolor(self, color):
        """ (Plotter, str) -> turtle
        
        Sets the current drawing color. 
        """
        self.pen.color(color)

    def onclick(self, fun):
        """ (Plotter, func) -> turtle

        Assigns a callback function that the frame should call when the 
        user clicks the mouse button when the pointer is over the plotter 
        window.
        
        The function <fun> must accept two integer parameters that represent
        the (x, y) location of the mouse when the click occurred
        """
        self.screen.onclick(fun)

    def interact(self):
        """ (Plotter) -> turtle

        Sets the plotter to interactive mode, enabling the user to 
        provide mouse and keyboard input.
        """
        self.screen.mainloop()
Пример #21
0
class TurtlePlot:
    def __init__(self, width, height, title=""):
        """
        Initialize a Turtle Plot
        Args:
            width: Width of the screen
            height: Height of the screen
        """

        self.width = width
        self.height = height
        self.title = title
        self.screen = Screen()
        self.screen.clear()

        self.screen.setup(width=width, height=height)
        self.screen.setworldcoordinates(0, 0, width, height)
        self.screen.tracer(0, 1)
        self.screen.onclick(lambda x, y: self.zoom_in(x, y))
        self.screen.title(self.title + "  (click to zoom in)")

    def done(self):
        """
        Wait until user clicks or closes screen.
        """
        self.screen.mainloop()

    def _setworldcoordinates(self, xmin, ymin, xmax, ymax):
        try:
            self.screen.setworldcoordinates(xmin, ymin, xmax, ymax)
        except Exception as e:
            pass

    def zoom_in(self, x, y):
        self._setworldcoordinates(x - 50, y - 50, x + 50, y + 50)
        self.screen.onclick(lambda x, y: self.zoom_out())
        self.screen.title(self.title + "  (click to zoom out)")

    def zoom_out(self):
        self._setworldcoordinates(0, 0, self.width, self.height)
        self.screen.onclick(lambda x, y: self.zoom_in(x, y))
        self.screen.title(self.title + "  (click to zoom in)")

    def draw(self, plot_record: PlotRecord, x_bounds, y_bounds):
        """
        Draw a plot on the turtle screen.
        Args:
            plot_record: The plot record to display.
            x_bounds: The plots x bounds
            y_bounds: The plots y bounds
        """
        outline_turtle = Turtle()
        outline_turtle.hideturtle()

        xy_turtles = [Turtle() for _ in plot_record.xys]
        for i, trtl in enumerate(xy_turtles):
            trtl.penup()
            trtl.pensize(2)
            trtl.pencolor(plot_record.xys[i].color)
            trtl.hideturtle()

        turtle_xmin, turtle_xmax = x_bounds
        turtle_ymin, turtle_ymax = y_bounds
        turtle_dx = turtle_xmax - turtle_xmin
        turtle_dy = turtle_ymax - turtle_ymin

        # leave 20% space on left and bottom
        # for labeling
        turtle_margin_left = 0.2
        turtle_margin_right = 0.2
        turtle_margin_bottom = 0.3
        turtle_margin_top = 0.3
        turtle_x_chart_min = turtle_xmin + (turtle_dx * turtle_margin_left)
        turtle_y_chart_min = turtle_ymin + (turtle_dy * turtle_margin_bottom)
        turtle_x_chart_max = turtle_xmax - (turtle_dx * turtle_margin_right)
        turtle_y_chart_max = turtle_ymax - (turtle_dy * turtle_margin_top)
        turtle_dx_chart = turtle_x_chart_max - turtle_x_chart_min
        turtle_dy_chart = turtle_y_chart_max - turtle_y_chart_min
        fontsize = 8

        outline_turtle.penup()
        outline_turtle.setposition(
            turtle_xmin, (turtle_y_chart_min + turtle_y_chart_max) * 0.5)
        outline_turtle.write(plot_record.ylabel)
        outline_turtle.setposition(turtle_x_chart_min, turtle_y_chart_max)
        outline_turtle.pendown()
        outline_turtle.setposition(turtle_x_chart_min, turtle_y_chart_min)
        outline_turtle.setposition(turtle_x_chart_max, turtle_y_chart_min)
        outline_turtle.penup()

        all_xs = [x for xy in plot_record.xys for x in xy.x]
        all_ys = [y for xy in plot_record.xys for y in xy.y]

        series_xmin = min(all_xs)
        series_xmax = max(all_xs)
        series_ymin = min(all_ys)
        series_ymax = max(all_ys)

        series_dx = (series_xmax - series_xmin) or 1
        series_dy = (series_ymax - series_ymin) or 1

        # scale factor from series to turtle
        xscale = turtle_dx_chart / series_dx
        yscale = turtle_dy_chart / series_dy

        outline_turtle.setposition(turtle_x_chart_min - fontsize,
                                   turtle_y_chart_max - (fontsize * 0.5))
        outline_turtle.write("%0.02f" % series_ymax, align='right')

        outline_turtle.setposition(
            turtle_x_chart_min - fontsize,
            turtle_y_chart_min + (turtle_dy_chart * 0.5) - (fontsize * 0.5))
        outline_turtle.write("%0.02f" % ((series_ymin + series_ymax) * 0.5),
                             align='right')

        outline_turtle.setposition(turtle_x_chart_min - fontsize,
                                   turtle_y_chart_min - (fontsize * 0.5))
        outline_turtle.write("%0.02f" % series_ymin, align='right')

        outline_turtle.setposition(turtle_x_chart_max,
                                   turtle_y_chart_min - (fontsize * 2))
        outline_turtle.write("%0.02f" % series_xmax, align='center')

        outline_turtle.setposition(
            turtle_x_chart_min + (turtle_dx_chart * 0.5) - fontsize,
            turtle_y_chart_min - (fontsize * 2))
        outline_turtle.write("%0.02f" % ((series_xmin + series_xmax) * 0.5),
                             align='center')

        outline_turtle.setposition(turtle_x_chart_min,
                                   turtle_y_chart_min - (fontsize * 2))
        outline_turtle.write("%0.02f" % series_xmin, align='center')

        for i, xy in enumerate(plot_record.xys):

            # position turtle at first xy value
            xy_turtles[i].setposition(
                turtle_x_chart_min + (xscale * (xy.x[0] - series_xmin)),
                turtle_y_chart_min + (yscale * (xy.y[0] - series_ymin)))
            xy_turtles[i].pendown()

            for j in range(min(len(xy.x), len(xy.y))):
                xy_turtles[i].setposition(
                    turtle_x_chart_min + (xscale * (xy.x[j] - series_xmin)),
                    turtle_y_chart_min + (yscale * (xy.y[j] - series_ymin)))

            xy_turtles[i].penup()
            xy_turtles[i].setposition(turtle_x_chart_max + (fontsize * 2),
                                      turtle_y_chart_max - (fontsize * 2 * i))
            xy_turtles[i].write(xy.label, align='left')
         

    def run(self):
        starttime = time.clock()
        anzahl_generationen = 0
        screen.onkey(self.stop, "space")
        generation = generate(self.state)
        self.RUNNING = True
        while self.RUNNING:
            self.newstate = next(generation)
            self.update_display()
            self.state = self.newstate
            anzahl_generationen +=1
        stoptime = time.clock()
        t = stoptime - starttime
        print(anzahl_generationen, t, anzahl_generationen/t)

    def stop(self):
        self.RUNNING = False
        screen.onkey(self.run, "space")

def main():
    game=Game()
    return "EVENTLOOP"
    

if __name__ == "__main__":
    msg = main()
    print(msg)
    screen.mainloop()
Пример #23
0
class Plotter:
    """ A plotter object provides a graphical window for 
        plotting data and mathematical functions. """

    def __init__(self, width, height, min_x, max_x, min_y, max_y):
        """ Initializes the plotter with a window that is 
            width wide and height high.  Its x-axis ranges from
            min_x to max_x, and its y-axis ranges from
            min_y to max_y.  Establishes the global beginning and ending
            x values for the plot and the x_increment value.
            Draws the x- and y-axes. """

        self.pen = Pen()   #  The plotter object's pen
        self.screen = Screen()   #  The plotter object's screen

        self.pen.speed(0)            # Speed up rendering
        self.screen.tracer(0, 0)        # Do not draw pen while drawing
        # Establish global x and y ranges
        self.min_x, self.max_x = min_x, max_x
        self.min_y, self.max_y = min_y, max_y
        # Set up window size, in pixels
        self.screen.setup(width=width, height=height)
        # Set up screen size, in pixels
        self.screen.screensize(width, height)
        self.screen.setworldcoordinates(min_x, min_y, max_x, max_y)

        # x-axis distance that corresponds to one pixel in window distance
        self.x_increment = (max_x - min_x)/width
        self.draw_grid(20)
        self.draw_axes()
        self.screen.title("Plot")
        self.screen.update()

    def __del__(self):
        """ Called when the client no longer uses the plotter 
            object. """
        print("Done plotting")

    def draw_axes(self, grid=False):
        """ Draws the x and y axes within the plotting window. 
            The grid parameter controls the drawing of accessory
            horizontal and vertical lines. """
        if grid:
            self.draw_grid(20)
        self.pen.hideturtle()            # Make pen invisible
        prev_width = self.pen.width()
        self.pen.width(2)
        #  Draw x axis
        self.pen.color('black')
        self.draw_arrow(self.min_x, 0, self.max_x, 0) 
        #  Draw y axis
        self.draw_arrow(0, self.min_y, 0, self.max_y) 
        self.pen.width(prev_width)

    def draw_grid(self, n):
        """ Draws horizontal and vertical accessory reference 
            coordinate lines on the plot.  Parameter n controls 
            the frequency of the reference lines. """
        self.pen.up()
        #self.pen.setposition(self.min_x, self.min_y)
        inc = (self.max_x - self.min_x)/n
        self.pen.color("lightblue")
        x = self.min_x
        while x <= self.max_x:
            self.pen.setposition(x, self.min_y)
            self.pen.down()
            self.pen.setposition(x, self.max_y)
            self.pen.up()
            x += inc  # Next x
        inc = (self.max_y - self.min_y)/n
        y = self.min_y
        while y <= self.max_y:
            self.pen.setposition(self.min_x, y)
            self.pen.down()
            self.pen.setposition(self.max_x, y)
            self.pen.up()
            y += inc  # Next y

    def draw_arrow(self, x1, y1, x2, y2):
        """ Draws an arrow starting at (x1, y1) and ending at
            (x2, y2). """
        # Draw arrow shaft
        self.pen.up()
        self.pen.setposition(x1, y1) # Move the pen starting point
        self.pen.down()           # Draw line bottom to top
        self.pen.setposition(x2, y2) # Move the pen starting point
        # Draw arrow head
        dy = y2 - y1
        dx = x2 - x1
        angle = atan2(dy, dx) *180/pi
        self.pen.setheading(angle)
        self.pen.stamp()

    def plot_function(self, f, color, update=True):
        """ Plots function f on the Cartesian coordinate plane
            established by initialize_plotter. Plots (x, f(x)), 
            for all x in the range min_x <= x < max_x. 
            The color parameter dictates the curve's color. """
    
        #  Move pen to starting position
        self.pen.up()
        self.pen.setposition(self.min_x, f(self.min_x))
        self.pen.color(color)
        self.pen.down()
        # Iterate over the range of x values for min_x <= x < max_x
        x = self.min_x
        while x < self.max_x:
            self.pen.setposition(x, f(x))
            x += self.x_increment   # Next x

        if update:
            self.screen.update()

    def plot_data(self, data, color, update=True):
        """ Plots the (x, y) pairs of values in the data list.
            The curve's color is specified by the color parameter. """
        #  Move pen to starting position
        self.pen.up()
        self.pen.setposition(data[0][0], data[0][1])
        self.pen.color(color)
        self.pen.down()
        # Plot the points in the data set
        for x, y in data:
            self.pen.setposition(x, y)
        if update:
            self.screen.update()

    def update(self):
        """ Draws any pending plotting actions to the screen. """
        self.screen.update()

    def setcolor(self, color):
        """ Sets the current drawing color. """
        self.pen.color(color)

    def onclick(self, fun):
        """ This method assigns a function to call when the user
            clicks the mouse over the plotting window.  The
            function must accept two integer parameters that
            represent the (x, y) location of the mouse when the
            click occurred. """
        self.screen.onclick(fun)
    
    def interact(self):
        """ Places the plotting object in interactive mode so the
            user can provide input via the mouse or keyboard. """
        self.screen.mainloop()