Example #1
0
def demo():
    turtle.forward(100)
    turtle.left(120)
    turtle.forward(80)
    turtle.right(90)
    turtle.forward(80)
    turtle.exitonclick()
Example #2
0
def tscheme_exitonclick():
    """Wait for a click on the turtle window, and then close it."""
    global _turtle_screen_on
    if _turtle_screen_on:
        print("Close or click on turtle window to complete exit")
        turtle.exitonclick()
        _turtle_screen_on = False
Example #3
0
def viewer(dna):
	'''Display ORFs and GC content for dna.'''
   
	dna = dna.upper()      # make everything upper case, just in case
   
	t = turtle.Turtle()
	turtle.setup(1440, 240)                  # make a long, thin window
	turtle.screensize(len(dna) * 6, 200)     # make the canvas big enough to hold the sequence
	# scale coordinate system so one character fits at each point
	setworldcoordinates(turtle.getscreen(), 0, 0, len(dna), 6)
	turtle.hideturtle()
	t.speed(0)
	t.tracer(100)
	t.hideturtle()
   
	# Draw the sequence across the bottom of the window.
	t.up()
	for i in range(len(dna)):
		t.goto(i, 0)
		t.write(dna[i],font=("Helvetica",8,"normal"))
      
	# Draw bars for ORFs in forward reading frames 0, 1, 2.
	# Draw the bar for reading frame i at y = i + 1.
	t.width(5)              # width of the pen for each bar
	for i in range(3):
		orf(dna, i, t)
      
	t.width(1)              # reset the pen width
	gcFreq(dna, 20, t)      # plot GC content over windows of size 20
      
	turtle.exitonclick()
Example #4
0
def draw_figures(figures):
    for figure in figures:
        t = turtle.Turtle()
        t.speed('fast')
        figure.draw(t)

    turtle.exitonclick()
Example #5
0
def main():
    # Inputs for interpreter and generator
    grammar = {'[':_push_state, ']':_pop_state,
               'F':_forwards, 'L':_left, 'R':_right,
              }
    rules   = {'T':'F[LT][RT]'}
    data = 'T'
    generations = 5

    # Create a generator
    g = Generator(data, rules)
    data = g.nth_generation(generations)

    # Create and set up interpreter
    i = Interpreter(grammar)
    i.use_memory = True # Use the interpreter's memory, 
                        #  i.e. pass the interpreter as the 
                        # first argument to every callback in the grammar

    # Initialise a turtle
    t = turtle.Turtle()
    t.hideturtle()
    t.left(90)

    # Load required items into interpreter memory
    i.load('turtle', t) # Load in a turtle
    i.load('state', []) # Load in an empty list for turtle's state stack

    i.execute(data)
    
    turtle.exitonclick()
Example #6
0
def dessiner(l,a,m,azimut=0):
    wn = turtle.Screen()
    mike = turtle.Turtle()
    mike.left(azimut)
    coordonneesX=[]
    coordonneesY = []
    coordonneesA = []
    for c in m:
        if c=='F':
            mike.forward(l)
        elif c=='+':
            mike.left(a)
        elif c=='-':
            mike.right(a)
        elif c=='[':
            coordonneesX.append(mike.xcor())
            coordonneesY.append(mike.ycor())
            coordonneesA.append(mike.heading())
        elif c==']':
            mike.penup()
            mike.goto(coordonneesX[-1],coordonneesY[-1])
            mike.setheading(coordonneesA[-1])
            mike.pendown()
            coordonneesX.pop(-1)
            coordonneesY.pop(-1)
            coordonneesA.pop(-1)
        else:
            break
    turtle.exitonclick()
Example #7
0
def main():
    init_turtle()
    koch_curve = lsys.lsystem(alphabet, axiom, rules)
    tree = koch_curve.apply_rules(int(sys.argv[1]))
    koch_curve.perform_actions(tree)
    print 'click to exit'
    turtle.exitonclick()
Example #8
0
def turtlePrint(board, width, height):
    turtle.hideturtle()
    turtle.speed(0)
    turtle.penup()
    turtle.goto(-210, -60)
    turtle.pendown()
    turtle.goto(20*width-210, -60)
    turtle.goto(20*width-210, 20*height-60)
    turtle.goto(-210, 20*height-60)
    turtle.goto(-210, -60)
    turtle.penup()

    for y in xrange(height):
        for x in xrange(width):
            turtle.penup()
            turtle.goto(20*x-200,20*y-50)
            turtle.pendown()
            if board[x][y] is 1:
                turtle.pencolor("green")
                turtle.dot(10)
                turtle.pencolor("black")
            elif board[x][y] is 2:
                turtle.dot(20)
            elif board[x][y] is 3:
                turtle.pencolor("red")
                turtle.dot(10)
                turtle.pencolor("black")
            elif board[x][y] is 8:
                turtle.pencolor("blue")
                turtle.dot()
                turtle.pencolor("black")

    turtle.exitonclick()
Example #9
0
def start():
#E
    turtle.backward(50)
    turtle.left(90)
    turtle.forward(50)
    turtle.right(90)
    turtle.forward(30)
    turtle.penup()
    turtle.backward(30)
    turtle.pendown()
    turtle.left(90)
    turtle.forward(50)
    turtle.right(90)
    turtle.forward(50)

#F
    turtle.penup()
    turtle.forward(100)
    turtle.pendown()
    turtle.backward(50)
    turtle.right(90)
    turtle.forward(50)
    turtle.left(90)
    turtle.forward(50)
    turtle.penup()
    turtle.backward(50)
    turtle.pendown()
    turtle.right(90)
    turtle.forward(70)

    turtle.exitonclick()
Example #10
0
def draw_figures(figures):
    t = turtle.Turtle()
    t.speed('slow')

    for figure in figures:
        figure.draw(t)
    turtle.exitonclick()
Example #11
0
def plot(a=None,b=None,c=None,scale=10):
    f = lambda x: x ** 2
    _min = -20
    _max = 20
    if hasattr(a,'__call__')   or type(a) == list:
        f = a
    elif hasattr(b,'__call__') or type(b) == list:
        f = b
        _max = a
    elif hasattr(c,'__call__') or type(c) == list:
        f = c
        _max = b
        _min = a
    if type(f) == list:
        _min = 0
        ls = f
        f = lambda i: ls[max(i,0)]
        _max = len(ls)-1
    pen = turtle.Turtle()
    pen.penup()
    pen.goto(_min*scale,f(_min))
    pen.pendown()
    for x in range(_min,_max+1):
        pen.goto(x*scale,f(x))
    turtle.exitonclick()
Example #12
0
def draw_figures(figures_info):
    t = turtle.Turtle()
    t.speed('fast')
    for f_info in figures_info:
        figure_type = f_info['type']
        if figure_type == 'square':
            draw_square(
                turtle_instance=t,
                center_x=f_info['center_x'],
                center_y=f_info['center_y'],
                side_length=f_info['side'],
                color=f_info['color']
            )
        elif figure_type == 'circle':
            draw_circle(
                turtle_instance=t,
                center_x=f_info['center_x'],
                center_y=f_info['center_y'],
                radius=f_info['radius'],
                color=f_info['color']
            )
        else:
            raise ValueError("Unsupported figure")

    turtle.exitonclick()
Example #13
0
File: 30.py Project: jpbat/freetime
def show():
	turtle.hideturtle()
	turtle.speed(0)
	side = turtle.window_height()/7
	grid(side)
	write(side)
	turtle.exitonclick()
Example #14
0
def main():
    board_ac=[10,2,3,4,5,6,7,8,9]
    turtle.screensize(300,300)
    turtle.hideturtle()    
    go_to(0,0,0)
    board()
    #players()
    win=0
    n_jogada=0
    
    player1=input('Player 1:\t')
    player2=input('Player 2:\t')     
    
    while win!=1:
        n_jogada += 1
        if check(board_ac) == True:
            if (-1)**n_jogada == -1:
                win=1
                print(player2, 'Ganhou!')
                
            else:
                win=1
                print(player1, 'Ganhou!')
        else:
            player_turn(n_jogada, board_ac)
    turtle.exitonclick()
def tscm_exitonclick():
    """Wait for a click on the turtle window, and then close it."""
    global _turtle_screen_on
    if _turtle_screen_on:
        turtle.exitonclick()
        _turtle_screen_on = False
    return UNSPEC
Example #16
0
def main():
    turtle.left(90)
    turtle.up()
    turtle.backward(120)
    turtle.down()
    drawTree(60)
    turtle.exitonclick()
Example #17
0
def main():
    """
    Tous les phase du battleship passe par le main()
    et il sert de boucle principal car il est appelé à
    tous les 0.5 secondes
    """
    if i.phase == "PlaceShip":
        i.placeShip()
    elif i.phase == "Attack": # Nom fictif
        i.attack()
    elif i.phase == "win":
        print('Vous avez gagné!')
        turtle.goto(0,0)
        turtle.pencolor('black')
        turtle.write('Vous avez gagné!',align="center",font=("Arial",70, "normal"))
        i.phase = "exit"
    elif i.phase == "lose":
        print('Vous avez perdu!')
        turtle.goto(0,0)
        turtle.pencolor('black')
        turtle.write('Vous avez perdu!',align="center",font=("Arial",70, "normal"))
        i.phase = "exit"
    elif i.phase == "exit":
        turtle.exitonclick()
        return None
    else:
        print('out')

    turtle.ontimer(main,500)
Example #18
0
def drawText(text):
    t = turtle.Turtle()
    #t.speed(0)
    t.ht()
    #turtle.tracer(0,0)
    for i in range(0,len(text)):
        char = text[i]
    turtle.exitonclick()
Example #19
0
def spiral(n):
    """draws a square spircal with n number of lines"""

    for x in range(n):
        turtle.forward(x*5)
        turtle.left(90)
        turtle.forward(x*5)

    turtle.exitonclick()
Example #20
0
def main():
	turtle_init()
	depth = int(sys.argv[1])
	tree = '0'
	while depth > 0:
		tree = apply_rules(tree)
		depth -= 1
	draw_tree(tree)
	turtle.exitonclick()
def draw_sqr(some,length):
    for j in range(0,100):
        for i in range(0,4):
            some.forward(length)
            some.right(90)
        some.right(5)
        limit =+ 1

    turtle.exitonclick()
Example #22
0
def main():
#    for i in range(5):
#        star_arm()
#    hexagon(50)
    side = int( input( "Enter the sides:  >"))
    leng = int( input( "Enter the length of each side:  >"))
    draw_shape( side, leng)
    
    t.exitonclick()
Example #23
0
 def render(self):
     turtle.up()
     w=turtle.window_width()
     self.dist=w/len(self.string)
     turtle.back(w/2)
     turtle.shape("turtle")
     for c in self.string:
         self.draw(c)
     turtle.hideturtle()
     turtle.exitonclick()        
Example #24
0
def main():
    pen =  turtle.Turtle()
    sides = 12
    turn = 150
    
    for x in range(sides):
        pen.forward(200)
        pen.left(turn)

    turtle.exitonclick()
Example #25
0
def squares():
    """\
    Draw the exterior border
    """
    for i in range(3):
        t.left(20)
        for i in range(4):
            t.forward(100)
            t.left(90)
    t.exitonclick()
Example #26
0
def rectangle(int1,int2):
    """makes rectange dimensions int1xint2"""

    i = 1
    while i <= 2:
        forwardleft(int1)
        forwardleft(int2)
        i += 1

    turtle.exitonclick()
Example #27
0
def snail():
	for x in range(25,175):
		turtle.left(5)
		for n in range(0,4):
			turtle.forward(x)
			turtle.left(90)
		
	else:
		window.configure( bg = 'green')
		turtle.exitonclick()		
Example #28
0
def circle():
	for x in range(0,72):
		turtle.left(5)
		for n in range(0,4):
			turtle.forward(50)
			turtle.left(90) 
	
	else:
		window.configure( bg = 'blue')
		turtle.exitonclick()	
def draw_snowflake(sentiment):
    from Tkinter import *
    import turtle
    import random
    sentiment +=1
    # Create the turtles
    a = turtle.Turtle()
    b = turtle.Turtle()
    c = turtle.Turtle()
    d = turtle.Turtle()
    e = turtle.Turtle()
    f = turtle.Turtle()
    g = turtle.Turtle()
    h = turtle.Turtle()


    turtles = [a, b, c, d, e, f, g, h]

    for blah in turtles:
        blah.speed(0)
        blah.tracer(1000000)
        blah.pensize(2)

    # Make all the turtles point in the right directions
    b.left(45)
    c.left(90)
    d.left(135)
    e.left(180)
    f.left(225)
    g.left(270)
    h.left(315)

    ts = turtle.getscreen()


    for i in range(random.randrange(0, 200)): #this should be lower with positive sentiment
        turn = random.randrange(0, round(360/(sentiment*10))) #this should be lower with positive sentiment
        length = random.randrange(0, 30) #this should be higher with positive sentiment
        for blah in turtles:
            blah.right(turn)
            blah.forward(length)


    for i in range(random.randrange(0, 1000)): #this should be lower with positive sentiment
        turn = -1 * random.randrange(0, round(361/(sentiment*10))) #this should be lower with positive sentiment
        length = random.randrange(0, 30) #this should be higher with positive sentiment
        for blah in turtles:
            blah.right(turn)
            blah.forward(length)

    ts.getcanvas().postscript(file="static/duck.eps")
    
    turtle.done()

    turtle.exitonclick()
Example #30
0
def initialize():
    screen = turtle.Screen()
    pen = turtle.Turtle()
    screen.tracer(1000)
    screen.screensize(800,800)
    screen.setworldcoordinates(1.9,0,3.6,1)
    pen.hideturtle()
    drawAxes(pen)
    markC(pen)
    drawOrbits(pen)
    turtle.exitonclick()
Example #31
0
        """
        try:
            print('trying')
            graphTsub(exitOnClick)
            print('did it')
        except:
            print('hiccup')
            graphTsub(exitOnClick)
         """


# Make a list of Rect objects
# @num - number of Rect objects to make
def bunchORects(num):
    rectList = [0] * num
    markers = '*o-.<>#@!`~#$%()&18xc'
    for i in range(num):
        x = random.randint(0, 250)
        y = random.randint(0, 250)
        w = random.randint(20, 30)
        h = random.randint(10, 100)
        fill = random.choice((True, False))
        marker = random.choice(markers)
        rectList[i] = Rect(w, h, marker, fill, x, y)
        rectList[i].graphT(False)  # draw it with turtle
    return rectList


bunchORects(10)
turtle.exitonclick()  # click exits the turtle window
Example #32
0
import turtle
a = turtle.Turtle()
a.pencolor('green')
a.pensize(6)
a.fillcolor('blue')
a.begin_fill()
a.circle(100)
a.end_fill()
#a.don()
turtle.exitonclick()
Example #33
0
t=turtle.Turtle() #거북이 모양 생성
t.shape("arrow") #모양을 거북이로
#right->rt forward->fd left->lt
t.color("blue")
t.penup()
t.goto(-200,0)
t.pendown()
t.width(5)
t.circle(50)
t.penup()
t.color("black")
t.goto(-70,0)
t.pendown()
t.circle(50)
t.penup()
t.color("red")
t.goto(60,0)
t.pendown()
t.circle(50)
t.penup()
t.color("yellow")
t.goto(-135,-50)
t.pendown()
t.circle(50)
t.penup()
t.color("green")
t.goto(-5,-50)
t.pendown()
t.circle(50)
turtle.exitonclick() #그래픽창 안 닫히게 하기 위해서 마지막에 추가(클릭시 창 닫힘)
import turtle as tr
tr.shape('turtle')
tr.color('red')
tr.width(5)
tr.pendown()
tr.fd(100)
tr.left(90)
tr.fd(100)
tr.left(90)
tr.fd(100)
tr.left(90)
tr.fd(100)
tr.exitonclick()
Example #35
0
    tim.back(1)
    tim.write("Joe Schmidt",font=("times new roman",16,"normal"))
    tim.back(9)         # moves tim next to name
    tim.right(90)
    tim.forward(15)

tim.speed(20)
bake()
tim.penup()
tim.goto(42, 60)  # places cherries
cherry()
tim.goto(100, 32)
cherry()
tim.goto(100, -22)
cherry()
tim.goto(42, -50)
cherry()
tim.goto(-42, -50)
cherry()
tim.goto(-100, -22)
cherry()
tim.goto(-100, 32)
cherry()
tim.goto(-42, 60)
cherry()
candle()
LIE()
sign()

turtle.exitonclick() #Keeps pycharm window open so we can see the drawing
def CircleOFSquares



turtle.exitonclick()
Example #37
0
        y1 = y + r * sin(angle + (p - 0.5) * ((2 * pi) / points))

        x2 = x + R * cos(angle + p * ((2 * pi) / points))
        y2 = y + R * sin(angle + p * ((2 * pi) / points))

        turtle.goto(x1, y1)
        turtle.pendown()
        turtle.goto(x2, y2)

    turtle.goto(first_point_x, first_point_y)

def ring(turtle, cx, cy, Nstars, radius, points, R, r):
    turtle.bgcolor("blue")
    for n in range(Nstars):
        star_x = cx + radius * cos(n * ((2 * pi) / Nstars))
        star_y = cy + radius * sin(n * ((2 * pi) / Nstars))

        turtle.color("gold")
        turtle.begin_fill()
        star(turtle, star_x, star_y, points, R, r)
        turtle.end_fill()

"""star(exturtle, -300, 0, 5, 50, 20)
star(exturtle, -100, 0, 6, 50, 20)
star(exturtle, 100, 0, 7, 50, 20)
star(exturtle, 300, 0, 8, 50, 20)
exturtle.exitonclick()"""

ring(exturtle, 0, 0, 12, 250, 5, 40, 15)
exturtle.exitonclick()
Example #38
0
import turtle

turtle.home()  # starts program and puts turtle in the center of the window

# Put Movement/Special commands here:


turtle.exitonclick()  # the window will close when you click on it
Example #39
0
def trick(pick="red"):
    speed(0)
    penup()
    goto(-140, 140)

    for step in range(15):
        write(step, align='center')
        right(90)
        for num in range(8):
            penup()
            forward(10)
            pendown()
            forward(10)
        penup()
        backward(160)
        left(90)
        forward(20)

    turtle1 = Turtle()
    turtle1.color('red')
    turtle1.shape('turtle')

    turtle1.penup()
    turtle1.goto(-160, 100)
    turtle1.pendown()

    for turn in range(10):
        turtle1.right(36)

    turtle2 = Turtle()
    turtle2.color('blue')
    turtle2.shape('turtle')

    turtle2.penup()
    turtle2.goto(-160, 40)
    turtle2.pendown()

    total_x = 0
    total_y = 0

    for turn in range(100):

        x = randint(1, 5)
        y = randint(1, 5)

        total_x += x
        total_y += y

        turtle1.forward(x)
        turtle2.forward(y)

    turtle.exitonclick()
    print(total_x, total_y)

    if pick == "red" and total_x > total_y:
        tts = gTTS("Your Turtle Won! Congratulations On Your Cake!")
        tts.save("3.mp3")
        playsound("3.mp3")

        img = Image.open("Cake.jpg")
        img.show()

    elif pick == "blue" and total_y > total_x:

        tts = gTTS("Your Turtle Won! Congratulations On Your Cake!")
        tts.save("4.mp3")
        playsound("4.mp3")

        img = Image.open("cake.jpg")
        img.show()

    else:
        pass
Example #40
0
import turtle

turtle.speed(0)  # これがないとスピードめちゃ遅い

for i in range(100):  # for文で動的描画を可能に
    turtle.circle(5 * i)  # 半径を等比数列に

turtle.exitonclick()  # クリックでウィンドウ削除
def run_demo():
    "Run demo"
    speedy = Runner()
    for i in range(1000):
        speedy.step()
    turtle.exitonclick()
Example #42
0
# Draws a rectangular box in the window

import turtle

turtle.pencolor('red')  # Set pen color to red
turtle.forward(200)  # Move pen forward 200 units (create bottom of rectangle)
turtle.left(90)  # Turn pen by 90 degrees
turtle.pencolor('blue')  # Change pen color to blue
turtle.forward(150)  # Move pen forward 150 units (create right wall)
turtle.left(90)  # Turn pen by 90 degrees
turtle.pencolor('green')  # Change pen color to green
turtle.forward(200)  # Move pen forward 200 units (create top)
turtle.left(90)  # Turn pen by 90 degrees
turtle.pencolor('black')  # Change pen color to black
turtle.forward(150)  # Move pen forward 150 units (create left wall)
turtle.hideturtle()  # Make pen invisible
turtle.exitonclick()  # Wait for user input
def main():
    t.penup()
    t.backward(300)
    t.pendown()
    draw_five_star(100)
    t.exitonclick()
Example #44
0
from turtle import forward, left, right, exitonclick

length = 100
angle = 180 - (180 / 3)

for i in range(3):
    forward(length)
    left(angle)

exitonclick()
Example #45
0
def main(board_filepath):
    board_objects = [
    ]  # List to store output of board -- DO NOT CHANGE VARIABLE NAME
    output_list = [
    ]  # List to store final output 	-- DO NOT CHANGE VARIABLE NAME

    def sort_grid(l=[]):

        k = sorted(l)
        h = 0
        li = []
        for i in k:
            li.append(tuple(i))

        for i in range(int(m.sqrt(len(l)))):
            for j in range(int(m.sqrt(len(l)))):
                k[h][0] = i + 1
                k[h][1] = j + 1
                h += 1
        return (k)

    def find_shape(c):

        peri = cv2.arcLength(c, True)
        approx = cv2.approxPolyDP(c, 0.04 * peri, True)
        if len(approx) == 3:
            shape = "Triangle"
        elif len(approx) == 4:
            shape = "4-sided"
        else:
            shape = "Circle"
        return shape

    def detect_color(px):
        if px[0] > 240 and px[1] < 10 and px[2] < 10:
            return "blue"
        elif px[0] < 10 and px[1] < 10 and px[2] > 240:
            return "red"
        elif px[0] < 10 and px[1] > 240 and px[2] < 10:
            return "green"
        elif px[0] < 10 and px[1] > 240 and px[2] > 240:
            return "yellow"
        elif px[0] < 10 and px[1] < 10 and px[2] < 10:
            return "black"

    image_board = cv2.imread(board_filepath)
    image_board_gray = cv2.cvtColor(image_board, cv2.COLOR_BGR2GRAY)
    #cv2.imshow("gray",image_board_gray)
    image_board_inrange = cv2.inRange(image_board_gray, 200, 255)
    #cv2.imshow("board",image_board_inrange)

    cnts_b = cv2.findContours(image_board_inrange.copy(), cv2.RETR_TREE,
                              cv2.CHAIN_APPROX_SIMPLE)
    cnts_b = cnts_b[0]
    cnts_b1, heirarchy_b = cv2.findContours(image_board_inrange.copy(),
                                            cv2.RETR_TREE,
                                            cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(image_board, cnts_b, -1, (206, 255, 39), 1)
    cnts_b1 = cnts_b1[0]
    shape = None
    l_board = []
    for j in range(0, len(heirarchy_b[0])):
        if heirarchy_b[0][j][3] == -1:
            c = cnts_b[j]
            M = cv2.moments(c)
            cX = int((M['m10'] / M['m00']))
            cY = int((M['m01'] / M['m00']))
            if heirarchy_b[0][j][2] != -1:
                #cv2.putText(image_board,str(j), (cX, cY), cv2.FONT_ITALIC,0.5, (0,0,0), 2)
                shape = find_shape(cnts_b[heirarchy_b[0][j][2]])
                M1 = cv2.moments(cnts_b[heirarchy_b[0][j][2]])
                cX_object = int((M1['m10'] / M1['m00']))
                cY_object = int((M1['m01'] / M1['m00']))
                px = image_board[cY_object, cX_object]
                color = detect_color(px)
                area = int(M1['m00'])
            else:
                shape = None
                color = None
                area = None
            l_board.append([cX, cY, heirarchy_b[0][j][2], shape, color, area])

    l_board_sorted = sort_grid(l_board)
    #print("^^",l_board_sorted)
    u = dict()
    path_board = {}

    def stopExists(start):
        for j in l_board_sorted:
            if (tuple([start[0], start[1]]) != tuple([j[0], j[1]])
                    and j[3] == start[3] and j[4] == start[4]
                    and abs(j[5] - start[5]) <= 10):
                return (True)
                break
        else:
            return (False)
        return (stop)

    for start_object in l_board_sorted:
        if (start_object[2] != -1 and start_object[4] != "black"
                and stopExists(start_object)):
            for object in l_board_sorted:
                if object[2] == -1:
                    path_board[tuple([object[0], object[1]])] = ["0"]
                elif l_board_sorted.index(
                        start_object) != l_board_sorted.index(
                            object) and object[3] == start_object[
                                3] and object[4] == start_object[4] and object[
                                    5] == start_object[5]:
                    path_board[tuple([object[0], object[1]])] = ["*"]
                elif l_board_sorted.index(
                        start_object) == l_board_sorted.index(object):
                    path_board[tuple([object[0], object[1]])] = ["#"]
                else:
                    path_board[tuple([object[0], object[1]])] = ["1"]
            #print ""
            #print path_board
            #print ""
    ##########################################################################################################################################################
            for i in path_board:
                j = 0
                for j in range(4):
                    path_board[i].append([0, 0])

            closed = set()
            opened = set()
            parent = {}
            g = {}
            gtemp = {}

            def lookup(x, y):
                if (x <= 0) or (y <= 0) or (x > (10)) or (
                        y > (10)) or path_board[(x, y)][0] == '1':
                    return 0
                else:
                    return [x, y]

            def link(t):

                x = t[0]
                y = t[1]
                if path_board[t][0] == '1':
                    return

                path_board[t][1] = lookup(x, y - 1)  #north
                path_board[t][2] = lookup(x - 1, y)  #west
                path_board[t][3] = lookup(x, y + 1)  #south
                path_board[t][4] = lookup(x + 1, y)  #east

            start = tuple([start_object[0], start_object[1]])
            stop = set()
            for j in path_board:
                if (path_board[j][0] == "*"):
                    stop.add(j)
                    #break
            '''
            print(start)
            print(stop)
            '''
            for i in path_board:
                link(i)

            #for i in range(1,11):
            #   for j in range(1,11):
            #      print(i,j,path_board[(i,j)])

            g[start] = 0
            gtemp[start] = g[start]
            opened.add(start)

            def neighbours(t):
                """ Generate a set of neighbouring nodes """
                neighbour = set()
                if path_board[t][1] != 0:
                    neighbour.add(tuple(path_board[t][1]))
                if path_board[t][2] != 0:
                    neighbour.add(tuple(path_board[t][2]))
                if path_board[t][3] != 0:
                    neighbour.add(tuple(path_board[t][3]))
                if path_board[t][4] != 0:
                    neighbour.add(tuple(path_board[t][4]))

                return neighbour

            def path(current_node):
                try:
                    p = path(parent[current_node])
                    return_path = []
                    return_path.extend(p)
                    return_path.append(current_node)

                    return return_path

                except KeyError:
                    # we have reached the start node
                    return [current_node]

            while ((len(opened) > 0) and stop.isdisjoint(closed)):

                gsort = sorted(gtemp, key=lambda t: g[t])
                i = 0
                for i in range(len(gsort) - 1):
                    if (gsort[i] not in closed):
                        break

                current = gsort[i]

                for w in stop:
                    if current == w:
                        s = path(w)
                        #print(path(w))
                        end = w

                try:
                    opened.remove(current)
                    gtemp.pop(current)
                # print("*",len(opened),opened)
                except KeyError:
                    pass
                closed.add(current)

                for neighbour in neighbours(current):
                    if neighbour not in closed:

                        temp_g = g[current] + 1
                        if (neighbour
                                not in opened) or (temp_g < g[neighbour]):
                            # if the neighbour node has not yet been evaluated yet, then we evaluate it
                            # or, if we have just found a shorter way to reach neighbour from the start node,
                            # then we replace the previous route to get to neighbour, with this new quicker route
                            parent[neighbour] = current
                            g[neighbour] = temp_g
                            gtemp[neighbour] = temp_g

                            if neighbour not in opened:
                                opened.add(neighbour)
                #print(len(opened),opened)

            u[(start, end)] = s
            path_board = {}


#####################################################################################################################################################################

    output_object = []
    for j in range(0, len(l_board_sorted)):
        if l_board_sorted[j][2] != -1:
            output_object.append((l_board_sorted[j][0], l_board_sorted[j][1]))
    #print len(output_object)
    print "%", output_object  #this is the output of task 1 - coordinates of occupied grid
    #cv2.imshow("contour",image_board)
    #for k in u:
    #    print "$",k,"   ",u[k]
    print ""
    v = sorted(u)
    print v
    print ""
    for i in v:
        print i, "--->", u[i]

    import turtle as t
    r = 60
    b = 5.5 * r

    t.bgpic("test_image" + str(fyl) + ".gif")
    t.ht()
    t.pensize(10)
    t.penup()
    for p in u:
        t.penup()
        t.clear()
        for i in u[p]:
            t.color("violet", "violet")
            t.setpos(i[0] * r - b, (11 - i[1]) * r - b)
            t.pendown()
    t.exitonclick()
Example #46
0
def main():
    sun = turtle.Turtle()
    mercury = turtle.Turtle()
    venus = turtle.Turtle()
    earth = turtle.Turtle()
    mars = turtle.Turtle()
    jupiter = turtle.Turtle()
    saturn = turtle.Turtle()

    for t in [sun, mercury, venus, earth, mars, jupiter, saturn]:
        t.shape("circle")
        t.speed(0)

    sun.color("yellow")
    mercury.color("blue")
    venus.color("green")
    earth.color("red")
    mars.color("black")
    jupiter.color("orange")
    saturn.color("cyan")

    place(mercury, 30, 30, "left")
    place(venus, 50, 40, "left")
    place(mars, 100, 75, "right")
    place(earth, 125, 50, "left")
    place(jupiter, 150, 30, "left")
    place(saturn, 175, 100, "left")

    for t in [sun, mercury, venus, earth, mars, jupiter, saturn]:
        t.forward(0.01)

    for j in range(4):
        for i in range(1000):
            for t in [mercury, venus, earth, mars, jupiter, saturn]:
                if t == mercury:
                    a, b = 30, 30
                if t == venus:
                    a, b = 50, 40
                if t == earth:
                    a, b = 100, 75
                if t == mars:
                    a, b = 125, 50
                if t == jupiter:
                    a, b = 150, 30
                if t == saturn:
                    a, b = 175, 100
                c = math.sqrt(a**2 - b**2)
                circumference = math.pi * (3 / 2 * (a + b) - math.sqrt(a * b))
                step = circumference / 1000
                p = t.position()
                x = p[0]
                y = p[1]
                if t == mars:
                    angle_rad = math.pi + math.atan2(-b**2 *
                                                     (x + c / 2), a**2 * y)
                else:
                    angle_rad = math.pi + math.atan2(-b**2 *
                                                     (x - c / 2), a**2 * y)
                angle = math.degrees(angle_rad)
                t.setheading(angle)
                t.forward(step)

    turtle.exitonclick()

def main():
    turtle.setup(1200, 750, 0, 0)
    turtle.bgcolor((0.8, 0.8, 1.0))
    turtle.tracer(False)
    rainbow()
    # 输出文字
    turtle.tracer(False)
    turtle.goto(100, -100)
    turtle.pendown()
    turtle.color("red")
    turtle.write("早日战胜疫情", align="center", font=("Script MT Bold", 80, "bold"))
    turtle.tracer(True)
    turtle.mainloop()


if __name__ == "__main__":
    draw_main()  #首先绘制心形框架
    time.sleep(2)
    draw_flag()  #绘制国旗
    time.sleep(0.5)
    draw_word("中国", -500, "left")  #打印加油文字
    draw_word("加油")
    time.sleep(0.5)
    draw_signature()  #签署名
    time.sleep(1)
    turtle.reset()
    main()
    turtle.exitonclick()  # 点击关闭窗口
Example #48
0
def main():
    square()
    rectangle()
    turtle.exitonclick()
Example #49
0
t.setup(width, height, 0, 0)
t.setworldcoordinates(0, 0, width, height)

# pen properties
# (turtle starts out pointed horizontally to the right)
t.speed(0.51)  # set turtle speed to slowest
t.width(8)  # set pen width
t.color(lineColor)

# initial pen position
t.penup()  # don't draw while positioning
t.setpos(60, height / 2 - 60)  # set position

# draw uppercase letter M
t.pendown()
t.dot(20, dotColor)
t.left(90)
t.forward(120)
t.dot(20, dotColor)
t.right(135)
t.forward(60)
t.dot(20, dotColor)
t.left(90)
t.forward(60)
t.dot(20, dotColor)
t.right(135)
t.forward(120)
t.dot(20, dotColor)

t.exitonclick()  # keep window open until mouse click
import turtle
import random
# Draws a regular polygon with the given number of sides.
# The length of each side is length.
# The pen begins at point(x, y).
# The color of the polygon is color (defaults to black).
# The polygon is rendered solid if fill is True (defaults to False).
def polygon(sides, length, x, y, color="black", fill=False):
    turtle.penup()
    turtle.setposition(x, y)
    turtle.pendown()
    turtle.color(color)
    if fill:
        turtle.begin_fill()
    for i in range(sides):
        turtle.forward(length)
        turtle.left(360//sides)
    if fill:
        turtle.end_fill()
# Disable rendering to speed up drawing
turtle.hideturtle()
turtle.tracer(0)
# Draw a few polygons
polygon(3, 30, 10, 10)                 # Black triangle outline
polygon(4, 30, 50, 50, "blue")         # Blue square outline
polygon(5, 30, 100, 100, "red", True)  # Red solid pentagon
polygon(5, 30, 150, 150, True)         # error!
turtle.update()  # Render image
turtle.exitonclick()  # Wait for user's mouse click
Example #51
0
def drow_triangle(length):
    for i in range(3):
        turtle.forward(length)
        turtle.left(120)
    turtle.exitonclick()
Example #52
0

# Program fonksiyona gönderilen parametreler ile çokgen çizer.
# Uzunluk paremetresi girilerek herbir kenarın uzunluğu belirlenir.
# Çizim x ve y parametrelerine girilen koordinat noktalarından başlar.
# Bir sonraki parametre çizimin kenar rengini belirler. (Varsayılan değer olarak siyah).
# Çizilen çokgenin içine dolgu olup olmayacağı belirlenir(Varsayılan False).
def Cokgen(kenarSayisi, uzunluk, x, y, renk="black", dolgu=False):
    turtle.penup()
    turtle.setposition(x, y)
    turtle.pendown()
    turtle.color(renk)
    if dolgu:
        turtle.begin_fill()
    for i in range(kenarSayisi):
        turtle.forward(uzunluk)
        turtle.left(360 // kenarSayisi)
    if dolgu:
        turtle.end_fill()
        # Adım adım çizim işlemi iptal edilerek çizim hızlandırılıyor
        turtle.hideturtle()
        turtle.tracer(0)


# Fonksiyonlar örnek çizimler için kullanılıyor
Cokgen(3, 30, 0, 0)  # Üçgen çizimi
Cokgen(4, 30, 50, 50, "blue")  # Kenar rengi mavi olan Kare çizimi
Cokgen(5, 30, 100, 100, "red", True)  # Dolgusu kırmızı olan beşgen çizimi
turtle.update()
turtle.exitonclick()  # Fare tuşuna tıklandığında çıkış işlemi yapılacaktır.
 def finish(self):
     turtle.done()
     turtle.exitonclick()
Example #54
0
import turtle as tur

tur.title('First turtle')

tur.speed(10)
tur.bgcolor('black')
tur.pencolor('blue')

tur.up()

tur.rt(45)
tur.fd(90)
tur.rt(135)

tur.down()

x = 0
while x < 120:
    i = 0
    while i < 6:
        tur.fd(200), tur.rt(61)
        i += 1
    tur.rt(11.1111)
    x += 1

tur.exitonclick()
Example #55
0
def koch_curve(n, line_length=10):
    for move in koch_turns(n):
        turtle.forward(line_length)
        turtle.left(move)
    turtle.forward(line_length)
    turtle.exitonclick()
Example #56
0
def main():
    ball = Ball()
    for _ in range(100):
        ball.move()
    exitonclick()
Example #57
0
    #====================== Start of lozenge drawing ==========================

    # lozenge angles
    lozenge_angles = [50, 130, 50, 130 + rotation_angle]  # => list

    for corner_angle in lozenge_angles:

        # 100 pixels forward
        turtle.forward(50)  # => NoneType

        # 40 degree clockwise
        turtle.right(corner_angle)  # => NoneType

#====================== End of lozenge drawing ==========================

# first counter incremetation
    counter_1 += 1  # => int

#====================== Start of of the out coming line ==========================

# Set the cursor 90 degree south
turtle.right(90)  # => NoneType

# Move cursor out of the main shape
turtle.forward(150)  # => NoneType

#====================== End of of the out coming line ==========================

# To prevent the canvas to close automatically.
turtle.exitonclick()  # => NoneType
Example #58
0
def square_function():
	for _ in range(4):
		turtle.forward(100)
		turtle.right(90)
	turtle.exitonclick()
Example #59
0
REDUCE_RATE = 0.7
WIDTH_RATE = 0.1
RANDOM_RATE_MIN = 0.9
RANDOM_RATE_MAX = 1.1


def tree(length):
    rate = random.uniform(RANDOM_RATE_MIN, RANDOM_RATE_MAX)
    len = length * rate
    t.width(len * WIDTH_RATE)
    t.forward(len)
    if len > MIN_LENGTH:
        sub = len * REDUCE_RATE
        t.left(ANGLE)
        tree(sub)
        t.right(2 * ANGLE)
        tree(sub)
        t.left(ANGLE)
    t.backward(len)


t.speed(0)
t.penup()
t.goto(0, -200)
t.pendown()
t.setheading(90)

tree(120)

t.exitonclick()
Example #60
0
'''
Modify the starter code below to create your own cool drawing
and then Pull Request it to your instructor.

Turtle Documentation: https://docs.python.org/3.3/library/turtle.html?highlight=turtle

'''
import turtle
yoda = turtle.Turtle()
screen = turtle.Screen()  # makes a screen object
screen.bgcolor('black')  # colors the screen
yoda.pensize(3)  # width of pen line
yoda.speed(10)  # speed of drawing. Go fast to not waste time.
yoda.color("#00FF00")
yoda.circle(100)  #head
yoda.penup()
yoda.setpos(50, 185)  #Birds beak
yoda.pendown()
yoda.goto(200, 210)
yoda.goto(88, 145)
yoda.penup()
yoda.setpos(200, -300)
yoda.pendown()
yoda.pencolor('#00FF00')
yoda.write('Matthew P.', font=("Arial", 12, "normal"))

turtle.exitonclick()  #Keeps pycharm window open