def d(fill=False): '''draws a capital D''' turtle.setheading(0) if fill: bf() fd(20) circle(20, 90) fd(70) circle(20, 90) fd(20) lt(90) fd(110) lt(90) if fill: ef() pu() turtle.goto(turtle.xcor() + 10, turtle.ycor() + 10) pd() cfc = fc() fc(turtle.getscreen().bgcolor()) bf() fd(10) circle(10, 90) fd(70) circle(10, 90) fd(10) lt(90) fd(90) ef() lt(90) pu() turtle.goto(turtle.xcor() + 40, turtle.ycor() - 10) pd() fc(cfc)
def verificarPos(self): """ Desc: Método para verificar se a posição e sentido da tartaruga é igual ao inicial Use getPos() para pegar o inicial Printa: String = Erro Retorna: Boolean = True (caso esteja ok) ou False (caso não) Exemplo: cb.getPos() cb.casa(25, 50, 30) cb.verificarPos() """ self._retorno = True if (round(turtle.xcor()) != self.turtlePosX) or (round(turtle.ycor()) != self.turtlePosY): print("A posição atual da tartaruga difere da inicial ({0}, {1})\nEla está em: ({2}, {3})".format(str(self.turtlePosX), str(self.turtlePosY), str(round(turtle.xcor())), str(round(turtle.ycor())))) self._retorno = False if turtle.heading() != self.turtleDir: print("A direção atual da tartaruga difere da inicial (" + str(self.turtleDir) + ")\nEla está em:", str(turtle.heading())) self._retorno = False return self._retorno
def checkybound(): if turtle.ycor() > (wn.screensize()[0]/2): return 3 elif turtle.ycor() < (wn.screensize()[0]/-2): return 4 else: return 0 time.sleep(1)
def gotoandprint(x, y): turtle.goto(x, y) #time.sleep(10) print() print("Set hook:") print(turtle.xcor(), turtle.ycor()) x=turtle.xcor() y=turtle.ycor() coordinate=[x,y] return coordinate
def a(fill=False): '''draws a capital A.''' turtle.setheading(0) if fill: bf() fd(10) turtle.goto(turtle.xcor() + 5, turtle.ycor() + 40) fd(10) turtle.goto(turtle.xcor() + 5, turtle.ycor() - 40) fd(10) turtle.goto(turtle.xcor() - 15, turtle.ycor() + 110) turtle.setx(turtle.xcor() - 10) turtle.goto(turtle.xcor() - 15, turtle.ycor() - 110) if fill: ef() pu() turtle.goto(turtle.xcor() + 17, turtle.ycor() + 50) pd() if fill: cfc = fc() fc(turtle.getscreen().bgcolor()) bf() fd(6) turtle.goto(turtle.xcor() - 3, turtle.ycor() + 40) turtle.goto(turtle.xcor() - 3, turtle.ycor() - 40) if fill: ef() fc(cfc) pu() turtle.goto(turtle.xcor() + 33, turtle.ycor() - 50) pd()
def tree(): '''draw a tree''' oc = color() fc('saddle brown') bf() turtle.goto(turtle.xcor()+20,turtle.ycor()) turtle.goto(turtle.xcor(),turtle.ycor()+80) turtle.goto(turtle.xcor()-20,turtle.ycor()) turtle.goto(turtle.xcor(),turtle.ycor()-80) ef() fc('dark green') color('dark green') pu() turtle.goto(turtle.xcor()+10,turtle.ycor()+80) pd() bf() circle(20) ef() turtle.goto(turtle.xcor()-20,turtle.ycor()-20) bf() circle(20) ef() pu() turtle.goto(turtle.xcor()+40,turtle.ycor()) pd() bf() circle(20) ef() pu() turtle.goto(turtle.xcor()-30,turtle.ycor()-60) pd() color(oc[0]) fc(oc[1])
def passeio(dim, lado, passos): # Prepara grelha turtle.speed(0) grelha_2(dim,lado) turtle.color('red') turtle.home() turtle.pendown() # Passeio turtle.speed(6) turtle.dot() turtle.showturtle() lim_x = lim_y = (dim*lado)//2 cor_x = 0 cor_y = 0 for i in range(passos): vai_para = random.choice(['N','E','S','W']) if (vai_para == 'N') and (cor_y < lim_y): cor_y += lado turtle.setheading(90) turtle.fd(lado) elif (vai_para == 'E') and (cor_x < lim_x): cor_x += lado turtle.setheading(0) turtle.fd(lado) elif (vai_para == 'S') and (cor_y > -lim_y): cor_y -= lado turtle.setheading(270) turtle.fd(lado) elif (vai_para == 'W') and (cor_x > -lim_x): cor_x -= lado turtle.setheading(180) turtle.fd(lado) else: print((vai_para,turtle.xcor(),turtle.ycor())) continue
def drawHouse(wallSize): """ This is the function for drawing house which takes wall size as a input. :pre: (relative) pos (0,0), heading (east), right :post: (relative) pos (wallSize,0), heading (north), up :return: total wood required to built the house. """ turtle.down() turtle.forward(wallSize) turtle.left(90) turtle.forward(wallSize) maxX = turtle.xcor() turtle.left(45) turtle.forward(wallSize / math.sqrt(2)) maxY = turtle.ycor() turtle.left(90) turtle.forward(wallSize / math.sqrt(2)) turtle.left(45) turtle.forward(wallSize) turtle.left(90) turtle.forward(wallSize) turtle.up() return 2 * (wallSize + wallSize / math.sqrt(2))
def main(): drawEnd = False while drawEnd == False: if turtle.xcor() < xEndPoint and turtle.ycor() < yEndPoint: randDir = None while randDir == None: randDir = randomDirection() moveTurtle(turtle, randDir) elif turtle.xcor() < xEndPoint: moveTurtle(turtle, EAST) elif turtle.ycor() < yEndPoint: moveTurtle(turtle, NORTH) else: drawEnd = True
def printwin(turtle): turtle.stamp() turtle.hideturtle() turtle.penup() turtle.goto(turtle.xcor(),turtle.ycor() + 15) turtle.color("green") turtle.write("You Win!",font=("Arial",30), align = "center")
def draw_star(size, color): # from center move to left vertex tt.setpos(tt.xcor()-size/2.0, tt.ycor()+size/2.0/math.tan(math.radians(72.0))) tt.fillcolor(color) tt.begin_fill() for i in range(5): tt.forward(size/2.0/(1+math.sin(math.radians(18)))) tt.left(72) tt.forward(size/2.0/(1+math.sin(math.radians(18)))) tt.right(180-36) tt.end_fill() # back to center tt.setpos(tt.xcor()+size/2.0, tt.ycor()-size/2.0/math.tan(math.radians(72.0)))
def collision_check(self, turtle): self._turtlex = turtle.xcor() self._turtley = turtle.ycor() self._dist = (((self._x1 - self._x2)**2 + (self._y1 - self._y2)**2)**0.5) self._dist2 = (((self._x1 - self._turtlex)**2 + (self._y1 - self._turtley)**2)**0.5) self._dist3 = (((self._turtlex - self._x2)**2 + (self._turtley - self._y2)**2)**0.5) if(self._dist2 + self._dist3 == self._dist): return True
def sinus(amplituda, perioda): deleni = 256 # počet díléčků pro periodu pocatekX = t.xcor() pocatekY = t.ycor() krok = perioda / deleni krokUhel = 2 * math.pi / deleni for i in range(deleni): t.goto(pocatekX + i * krok, pocatekY + amplituda * math.sin( i * krokUhel ) )
def random_location(turtle, x, y, relative=False): if not relative: random_x = random.randint(-x, x) random_y = random.randint(-y, y) turtle.setpos(random_x, random_y) else: random_x = turtle.xcor() + random.randint(-x, x) random_y = turtle.ycor() + random.randint(-y, y) turtle.setpos(random_x, random_y)
def rectangle(length, width, x = None, y = None, color = "black", fill = False): wasDown = turtle.isdown() turtle.up() if x is not None and y is not None: turtle.setpos(x, y) if wasDown: turtle.down() if fill: turtle.color(color, color) turtle.begin_fill() else: turtle.pencolor(color) turtle.goto(turtle.xcor() + length, turtle.ycor()) turtle.goto(turtle.xcor(), turtle.ycor() + width) turtle.goto(turtle.xcor() - length, turtle.ycor()) turtle.goto(turtle.xcor(), turtle.ycor() - width) if fill: turtle.end_fill()
def pox(turtle, x, y, n=10): origx = turtle.xcor() origy = turtle.ycor() turtle.penup() for i in range(n): random_location(turtle, x, y, True) turtle.dot(random.randint(3, 10), random_color()) turtle.setpos(origx, origy) turtle.pendown()
def draw_spiral(radius): original_xcor = t.xcor() original_ycor = t.ycor() speed = 1 while True: t.forward(speed) t.left(10) speed += 0.1 if t.distance(original_xcor, original_ycor) > radius: break
def spiral(radius): xcor = turtle.xcor() ycor = turtle.ycor() speed = 1 while True: turtle.forward(speed) turtle.left(10) speed += 1 * 0.01 if turtle.distance(xcor, ycor) > radius: break
def joonistaLipp(riik, lipud=lipud): värvid = lipud[riik] turtle.pendown() for värv in värvid: turtle.begin_fill() turtle.fillcolor(värv) turtle.forward(100) turtle.right(90) turtle.forward(20) turtle.right(90) turtle.forward(100) turtle.right(90) turtle.forward(20) turtle.end_fill() turtle.sety(turtle.ycor()-20) turtle.right(90) turtle.penup() turtle.sety(turtle.ycor()+60) turtle.setx(turtle.xcor()+110)
def gotoandprint(x, y): if -5 <= x <= 5 and 0 <= y <= -40: # vertical - line 1 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif -75 <= x <= 5 and -40 <= y <= -30: # horizontal - line 2 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif -75 <= x <= -65 and -40 <= y <= 75: # vertical- line 3 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif -75 <= x <= 75 and 65 <= y <= 75: # horizontal - line 4 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif 65 <= x <= 75 and -105 <= y <= 75: # vertical - line 5 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif -145 <= x <= 75 and -105 <= y <= -95: # horizontal - line 6 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif -145 <= x <= -135 and -105 <= y <= 145: # vertical - line 7 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif -145 <= x <= 145 and 135 <= y <= 145: # horizontal - line 8 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" elif 135 <= x <= 145 and -174 <= y <= 145: # vertical - line 9 krisha.reset() krisha.write("Game over", font=("Arial", 40, "normal")) print "error" # # gotoresult = turtle.goto(x, y) # # print(turtle.xcor(), turtle.ycor()) # # return gotoresult else: gotoresult = turtle.goto(x, y) print (turtle.xcor(), turtle.ycor()) print (topPoint, bottomPoint) return gotoresult
def draw_flag(height): tt.penup() # assign parameters defined from # https://en.wikipedia.org/wiki/Flag_of_the_United_States A = height B,C = 1.9*A, (7.0/13.0)*A D = 2.0*B/5.0 E = C/10.0 G = D/12.0 L = A/13.0 K = 4.0*L/5.0 # draw the bottom 6 stripes for color in ['red','white']*3: draw_rectangle(B, L, color) tt.sety(tt.ycor()+L) # draw the top left blue rectangle draw_rectangle(D, C, 'blue') # draw the top right 7 stripes tt.setx(tt.xcor()+D) for color in ['red','white']*3: draw_rectangle(B-D, L, color) tt.sety(tt.ycor()+L) draw_rectangle(B-D, L, 'red') tt.sety(tt.ycor()+L) # draw the 50 stars tt.setx(G) tt.sety(tt.ycor()-E) nums_star = [6,5]*4 nums_star.append(6) for nstar in nums_star: if (nstar == 5): tt.setx(tt.xcor()+G) for i in range(nstar): draw_star(K, 'white') tt.setx(tt.xcor()+2.0*G) tt.setx(G) tt.sety(tt.ycor()-E)
def drawYtickers(): current = yscale*(ymin//yscale) tickerLength = float(xmax-xmin)/40 while current < ymin: current += yscale toXY(-tickerLength/2,current) while current <= ymax: turtle.goto(turtle.xcor()+tickerLength,turtle.ycor()) current += yscale toXY(-tickerLength/2,current)
def drawXtickers(): current = xscale*(xmin//xscale) tickerLength = float(ymax-ymin)/40 while current < xmin: current += xscale toXY(current,-tickerLength/2) while current <= xmax: turtle.goto(turtle.xcor(),turtle.ycor()+tickerLength) current += xscale toXY(current,-tickerLength/2)
def drawCircles(amount): turtle.penup() points = [] turtle.goto(-400, 0) count = 0 while count < amount: turtle.pendown() turtle.circle(20) points = points + [[turtle.xcor(), turtle.ycor() + 20]] turtle.penup() turtle.forward(80) count += 1 return points
def turtlegraph(function, xmin=-100, xmax=100): import turtle global output xmin = int(xmin) xmax = int(xmax) if xmin > 0: raise coordinates = {} # creating coordinate dictionary function = replace_implied_multiplication(function) for xval in range(xmin, xmax+1): coordinates[xval] = eval(function.replace("x","(float(" + str(xval) + "))")) # solve equation for y, add to coordinates dictionary turtle.home() turtle.hideturtle() turtle.speed(0) # meh turtle.penup() print "x , y for function y =", function put_outwin("x , y for function y =", function) output += "x , y for function y=" + str(function) + "\n" for xval in sorted(coordinates.iterkeys()): # graph, baby, graph! turtle.setposition(xval, coordinates[xval]) turtle.pendown() print turtle.xcor(), ",", turtle.ycor() put_outwin(turtle.xcor(), ",", turtle.ycor()) output += str(turtle.xcor()) + " , " + str(turtle.ycor()) + "\n" turtle.update() try: vertex = find_vertex(coordinates) showinfo("Vertex Found",("Parabola vertex was found to be %s" %str(vertex))) print "Vertex found: %s" %str(vertex) put_outwin("Vertex found:", vertex) output += "Vertex found: %s" %str(vertex) except: None print "---------------" put_outwin("---------------") output += "---------------" + "\n" turtle.penup() return
def r(fill=False): '''draws a capital R.''' turtle.setheading(0) if fill: bf() fd(10) lt(90) fd(50) rt(90) turtle.goto(turtle.xcor() + 20, turtle.ycor() - 50) fd(10) turtle.goto(turtle.xcor() - 20, turtle.ycor() + 50) circle(20, 90) fd(20) circle(20, 90) fd(20) lt(90) fd(110) if fill: ef() pu() turtle.goto(turtle.xcor() + 10, turtle.ycor() + 60) pd() lt(90) cfc = fc() fc(turtle.getscreen().bgcolor()) bf() fd(10) circle(10, 90) fd(20) circle(10, 90) fd(10) lt(90) fd(40) ef() fc(cfc) lt(90) pu() turtle.goto(turtle.xcor() + 40, turtle.ycor() - 60) pd()
def getPos(self): """ Desc: Método para pegar posição e sentido da tartaruga Use verificarPos() para verificar se é igual a inicial Exemplo: cb.getPos() cb.casa(25, 50, 30) cb.verificarPos() """ self.turtlePosX = round(turtle.xcor()) self.turtlePosY = round(turtle.ycor()) self.turtleDir = turtle.heading()
def draw_flag(country_str, flag_width_float, orientation_str): """ Asks the for the name of the country, the width and the orientation and draws a the flag using turtle Recieve: The name of country, the width of the flag, and the orientation Return: Nothing Algorithm: Save the initial position Check to make sure the country is valid Check to make sure the width is valid and more than zero Check to make sure the orientation is vallid Check to see what country needs to be drawn and call the corresponding function Go back to the intial position """ turtle.colormode(255) initial_pos_list = [turtle.xcor(), turtle.ycor(), turtle.heading()] country_str = country_str.lower() orientation_str = orientation_str.lower() if is_valid_country(country_str) == False: print('***Invalid country name. Please try again.***') return if type(flag_width_float) == str or flag_width_float <= 0.00: print('***Invalid flag width. Please try again.***') return if orientation_str == 'landscape' or orientation_str == 'portrait': if orientation_str == 'portrait': turtle.right(90) else: print('***Invalid orientation. Please try again.***') return if country_str == 'denmark': draw_denmark(flag_width_float) elif country_str == 'sweden': draw_sweden(flag_width_float) elif country_str == 'faroe islands': draw_faroe_island(flag_width_float) elif country_str == 'norway': draw_norway(flag_width_float) elif country_str == 'iceland': draw_iceland(flag_width_float) elif country_str == 'finland': draw_finland(flag_width_float) go_to_pos(initial_pos_list) turtle.fillcolor('black')
def checkpos(turtlelist): screen.tracer(0) for turtle in turtlelist: x = turtle.xcor() y = turtle.ycor() if x > 200: turtle.setx(-200) elif x < -200: turtle.setx(200) if y > 200: turtle.sety(-200) elif y < -200: turtle.sety(200) screen.tracer(1) return
def random_location(turtle, x, y, relative=False): ''' Moves a turtle to a random location within x,y bounds takes turtle, x bound, y bound, uselrelative location (boolean) ''' if relative is False: random_x = random.randint(-x, x) random_y = random.randint(-y, y) turtle.setpos(random_x, random_y) if relative is True: random_x = turtle.xcor() + random.randint(-x, x) random_y = turtle.ycor() + random.randint(-y, y) turtle.setpos(random_x, random_y) else: raise Exception("expected boolean")
import turtle NUM_CIRCLES = 100 STARTING_RADIUS = 20 OFFSET = 10 ANIMATION_SPEED = 1000 turtle.speed(ANIMATION_SPEED) turtle.hideturtle() radius = STARTING_RADIUS for count in range(NUM_CIRCLES): turtle.circle(radius) x = turtle.xcor() y = turtle.ycor() - OFFSET radius = radius + OFFSET turtle.penup() turtle.goto(x, y) turtle.pendown()
#t.setheading(45) #t.fd(50) t.pd() t.speed(10) wind = r.choice((-1, 1)) * round(r.random(), 4) e.msgbox("wind is : {}".format(wind)) #print("wind is : {}".format(wind)) #heading = float(input("please enter angle (e.g. 45.0)")) #speed = float(input("please enter speed (e.g. 10.0)")) heading = float( e.enterbox("please enter angle (e.g. 45.0)", default="45.0")) speed = float(e.enterbox("please enter speed (e.g. 10.0)", default="10.0")) t.setheading(180 - heading) dx = math.cos(t.heading() * math.pi / 180) * speed dy = math.sin(t.heading() * math.pi / 180) * speed #for step in range(200): y = ground while y >= ground: x = t.xcor() y = t.ycor() dy -= 0.1 x += dx y += dy t.goto(x, y) play = e.boolbox("play again?") t.exitonclick()
turtle.showturtle() #Calculate window width and height WindowHeight = turtle.Screen().window_height() WindowWidth = turtle.Screen().window_width() for i in range(1, 500): Forward = random.randint(25, 150) Angle = random.randint(10, 100) #In next lesson, use this as demo of the use of an "or" with if/then if (abs(turtle.xcor()) + Forward) > (WindowWidth / 2): #Note: In later lessons, use this as a function demo. RandomX = random.randint(-50, 50) RandomY = random.randint(-50, 50) turtle.width(7) turtle.color("blue") turtle.goto(RandomX, RandomY) elif (abs(turtle.ycor()) + Forward) > (WindowHeight / 2): #Note: In later lessons, use this as a function demo. RandomX = random.randint(-50, 50) RandomY = random.randint(-50, 50) turtle.width(7) turtle.color("purple") turtle.goto(RandomX, RandomY) else: turtle.width(1) turtle.color("black") turtle.forward(Forward) turtle.left(Angle)
def atTopEdge(turtle, screen_height): if turtle.ycor() > screen_height / 2: return True else: return False
turtle.forward(TARGET_WIDTH) turtle.penup() # Центрировать черепаху. turtle.goto(0, 0) turtle.setheading(EAST) turtle.showturtle() turtle.speed(PROJECTILE_SPEED) # Получить угол и силу от пользователя. angle = float(input("Введите угол снаряда: ")) force = float(input("Введите пусковую силу (1-10): ")) # Расчитать растояние. distance = force * FORCE_FACTOR # Задать направление turtle.setheading(angle) # Запустить снаряд turtle.pendown() turtle.forward(distance) # Снаряд поразил цель? if (turtle.xcor() >= TARGET_LLEFT_X and turtle.xcor() <= (TARGET_LLEFT_X + TARGET_WIDTH) and turtle.ycor() >= TARGET_LLEFT_Y and turtle.ycor() <= (TARGET_LLEFT_Y + TARGET_WIDTH)): print("Цель поражена!") else: print("Вы промохнулись.") input("Enter для завершения!")
def up(): turtle.onkeypress("w") turtle.pos() turtle.goto(turtle.xcor(), turtle.ycor() + 10)
def move_up(): canvas.yview_scroll(-1, "units") turtle.sety(turtle.ycor() + MAGNIFICATION)
def get_dist(turtle, turtle_to): return math.sqrt(((turtle.xcor() - turtle_to.xcor())**2 + (turtle.ycor() - turtle_to.ycor())**2))
t.left(180 - 2 * t.heading()) #계산값 만큼 왼쪽으로 회전 elif 270 <= t.heading() <= 360 : #거북이가 오른쪽 아래 방향으로 향하고 있을 때 t.right(2 * t.heading() - 540) #계산값만큼 오른쪽으로 회전 if t.xcor() <= -250 : #왼쪽 벽에 부딪혔을 때도 같은 방식으로 코딩한다 if 90 <= t.heading() <= 180 : t.right(2 * t.heading() - 180) elif 180 <= t.heading() <= 270 : t.left(540 - 2 * t.heading()) if t.ycor() >= 250 : #위쪽 벽에 부딪혔을때도 같은 방식으로 코딩한다 if 0 <= t.heading() <= 90 : t.right( 2 * t.heading() ) elif 90 <= t.heading() <= 180 : t.left( 360 - 2 * t.heading() ) if t.ycor() <= -250 : #아래쪽 벽에 부딪혔을 때도 같은 방식으로 코딩한다 if 270 <= t.heading() <= 360 : t.left( 720 - 2 * t.heading() ) elif 180 <= t.heading() <= 270 : t.right( 2 * t.heading() - 360 )
def condition(turtle): turtle.setheading(-90) if turtle.ycor() > -10: turtle.fd(5) if turtle.ycor() < -10: turtle.fd(0)
t.goto(0, 0) t.down t.color("black") #random a = random.randint(1, 360) t.setheading(a) t.speed(10) #1000 repeating for x in range(1000): while True: t.fd(5) a = t.xcor() b = t.ycor() t.goto(a, b) if a >= 250: break if b >= 250: break if a <= -250: break if b <= -250: break #obstacle a
# (Turtle: display a STOP sign) Write a program that displays a STOP sign, as # shown in Figure 3.5b. The hexagon is in red and the text is in white import turtle turtle.begin_fill() turtle.left(90) turtle.circle(100, steps=6) turtle.color("red") turtle.end_fill() turtle.color("white") turtle.penup() turtle.goto(turtle.xcor() - 140, turtle.ycor() - 15) turtle.pendown() turtle.write("STOP", font=("Arial", 20, "normal")) turtle.hideturtle() turtle.done()
black = False for i in range(1, 9): for j in range(1, 9): turtle.begin_fill() turtle.circle(30, steps=4) if black: turtle.color("black") black = not black else: turtle.color("white") black = not black turtle.end_fill() turtle.penup() turtle.goto(turtle.xcor() + 42, turtle.ycor()) turtle.pendown() turtle.penup() turtle.goto(-150, turtle.ycor() - 42) turtle.pendown() black = not black turtle.penup() turtle.left(180) turtle.goto(-192, 161) turtle.color("gray") turtle.pensize(6) turtle.pendown() turtle.circle(240, steps=4) turtle.done()
def move_down(): canvas.yview_scroll(1, "units") turtle.sety(turtle.ycor() - MAGNIFICATION)
turtle.speed(0) turtle.penup() turtle.goto(LOWER, LOWER) turtle.pendown() for i in range(LOWER, UPPER + 10, 10): turtle.goto(turtle.xcor(), UPPER) turtle.penup() turtle.goto(turtle.xcor() + 10, LOWER) turtle.pendown() turtle.penup() turtle.goto(LOWER, LOWER) turtle.pendown() for i in range(LOWER, UPPER + 10, 10): turtle.pendown() turtle.goto(UPPER, turtle.ycor()) turtle.penup() turtle.goto(LOWER, turtle.ycor() + 10) turtle.penup() turtle.speed(6) turtle.goto(0, 0) turtle.pendown() turtle.width(2) while True: dir = random.randint(1, 4) if dir == 1: turtle.goto(turtle.xcor() + 10, turtle.ycor()) if dir == 2: turtle.goto(turtle.xcor() - 10, turtle.ycor()) if dir == 3:
wn.title("Space Invaders") wn.setup(width=1200, height=800) wn.bgpic("spacebg.png") #os.system("afplay space_invaders.wav&") #stop(os.system("afplay space_invaders.wav&")) FONTSIZE = 12 FONT = ('Outer Space', FONTSIZE, 'normal') turtle.penup() turtle.setx(-520) turtle.sety(280) with open("spaceinvaders_score.txt") as file: for line in file: turtle.write(line.strip(), font=FONT) turtle.goto(turtle.xcor(), turtle.ycor() - FONTSIZE) turtle.color("green") from Game_Borders import ladder_border_pen, ladder_pen, game_border_pen, space_name_pen, invader_name_pen, si2d_name_pen, score, game_score_pen, credits_border_pen, credits_pen, score #SCORE BORDER #SCORE IN SCORE BORDER #GAME BORDER #NAME ABOVE GAME BORDER #SET SCORE TO 0 BEFORE DRAWING IT #DRAW THE SCORE IN GAME #PLAYER from Player_Resources import player from Enemy_Resources import number_of_enemies, enemy_images, enemies, enemy, enemyspeed, number_of_enemies2, enemy2_images, image2, enemies2, enemy2
t.forward(500) #500만큼 이동 t.left(360 / n) #왼쪽방향으로 360/n만큼 회전 #거북이 튕기기위한 준비 t.speed(0) #스피드 최대로 t.up() #꼬리 올림 t.home() #각도와 좌표를 초기화 함 t.down() #꼬리 내림 t.color("red") #색상 red a = random.randint(1, 360) #각도를 1부터 360도로 랜덤 저장 t.seth(a) #거북이 랜덤 지정 #반복을 통한 거북이 튕기기 while -250 <= t.xcor() <= 250 and -250 <= t.ycor() <= 250: n = t.heading() t.forward(1) if 250 <= t.ycor(): # 위벽 입사각에 대한 반사각 if 0 <= n <= 180: t.seth(360 - n) t.forward(1) if t.ycor() <= -250: # 밑벽 입사각에 대한 반사각 if 180 <= n <= 360: t.seth(360 - n) t.forward(1) if t.xcor() <= -250: # 왼쪽벽의 입사각에 대한 반사각 if 180 <= n <= 270:
t.goto(-350,-50) t.down() polygon(4,100) t.up() import random # random 모듈을 쓰겠다. a=random.randint(1,360) # 1부터 360까지의 수를 랜덤추출해서 a에 저장 t.speed(0) # 거북이를 최고 속도로 한다 t.goto(-430,100) # 거북이를 중앙에 놓는다 t.setheading(a) # 거북이가 바라보는 각도를 a도로 한다. while True: # 무한반복 a = t.xcor() # x좌표를 a에 저장 b = t.ycor() # y좌표를 b에 저장 ang=t.heading() # 거북이가 바라보는 각도를 ang에 저장 t.fd(2) # 앞으로 2만큼 이동한다 if b < -150: # 만약 y좌표가 -150보다 작다면 t.seth(360-ang) # 반사각 계산 t.fd(5) # 5씩 앞으로 이동한다 if b > 350: # 만약 y좌표가 350보다 크다면 t.seth(360-ang) # 반사각 계산 t.fd(5) # 5씩 앞으로 이동 if a > -180: # 만약 x좌표가 -180보다 작다면 t.seth(180-ang) # 반사각 계산
def draw(x): if x == 0: y = t.pos() t.seth(70) t.fd(100) y1 = t.pos() t.seth(0) t.lt(290) t.fd(100) y2 = t.pos() d1 = t.distance(y1) t.bk(d1 / 2) t.seth(180) t.fd(50) t.pu() t.goto(y2) t.pd() t.seth(0) if x == 1: t.seth(0) t.pu() t.fd(10) t.pd() t.lt(90) t.fd(86) t.seth(0) t.circle(-21.5, 180) t.seth(0) t.circle(-21.5, 180) t.seth(0) t.pu() t.fd(25) t.pd() if x == 2: t.seth(0) t.pu() t.fd(48) y = t.pos() t.pd() t.circle(43.3, -180) t.pu() t.seth(0) t.goto(y) t.fd(10) t.pd() if x == 3: t.seth(0) t.lt(90) t.fd(86) t.seth(0) t.circle(-43, 180) t.seth(0) t.pu() t.fd(50) t.pd() if x == 4: t.fd(60) y = t.pos() t.bk(50) y1 = t.pos() t.lt(90) t.fd(43.3) y2 = t.pos() t.dot(2, "blue") t.fd(43.3) t.rt(90) t.fd(50) t.pu() t.goto(y2) t.pd() t.seth(0) t.fd(30) t.pu() t.goto(y) t.seth(0) if x == 5: y = t.ycor() t.lt(90) t.fd(43.3) y2 = t.pos() t.dot(2, "blue") t.fd(43.3) t.rt(90) t.fd(50) x = t.xcor() t.pu() t.goto(y2) t.pd() t.seth(0) t.fd(30) t.pu() t.goto(x, y) t.seth(0) if x == 6: t.pu() t.seth(0) t.fd(48) t.lt(90) t.fd(86) t.seth(0) t.pd() t.circle(-43.3, -180) t.seth(0) t.lt(90) t.fd(40) t.seth(0) t.bk(10) t.fd(35) t.seth(0) t.rt(90) t.fd(15) t.pu() t.fd(15) t.seth(0) t.fd(15) t.pd() if x == 7: t.lt(90) t.fd(43.3) y2 = t.pos() t.dot(2, "blue") t.fd(43.3) t.goto(y2) t.seth(0) t.fd(50) t.lt(90) t.fd(43.3) t.bk(86.6) t.seth(0) if x == 8: t.pu() t.fd(15) t.pd() y = t.pos() t.lt(90) t.fd(86.6) t.goto(y) t.seth(0) if x == 9: t.seth(10) t.lt(90) t.fd(10) t.seth(90) t.circle(-25, -180) y = t.pos() t.bk(70) t.lt(90) t.fd(10) t.bk(20) t.pu() t.goto(y) t.seth(0) t.lt(-90) t.fd(15) t.seth(0) t.fd(10) if x == 10: t.lt(90) t.fd(43.3) y2 = t.pos() t.dot(2, "blue") t.fd(43.3) t.goto(y2) t.seth(52) t.fd(47) t.goto(y2) t.seth(-50) t.fd(58) t.seth(0) if x == 11: t.lt(90) t.fd(86.6) t.bk(86.6) t.rt(90) t.fd(50) t.seth(0) if x == 12: t.lt(90) t.fd(86.6) t.seth(0) t.seth(-45) t.fd(60) t.seth(0) t.seth(45) t.fd(60) t.seth(0) t.seth(-90) t.fd(86.6) t.seth(0) if x == 13: t.lt(90) t.fd(86.6) t.seth(0) t.seth(-55) t.fd(106) t.seth(0) y = t.pos() t.lt(90) t.fd(86.6) t.goto(y) t.seth(0) if x == 14: t.pu() t.fd(60) y = t.pos() t.lt(90) t.fd(43.3) t.pd() t.circle(43.3) t.pu() t.goto(y) t.fd(43.3) t.seth(0) if x == 15: y = t.pos() t.lt(90) t.fd(35) t.dot(3, "blue") y1 = t.pos() t.fd(35) t.goto(y1) t.seth(0) t.circle(35, 180) t.goto(y) t.seth(0) t.pu() t.fd(35) t.pd() if x == 16: t.pu() t.fd(60) y = t.pos() t.lt(90) y1 = t.pos() t.fd(43.3) t.pd() t.circle(43.3) t.seth(180) t.pu() t.fd(43.3) t.pd() t.seth(0) t.seth(-50) t.fd(60) t.seth(0) if x == 17: y = t.pos() t.lt(90) t.fd(43.3) t.dot(3, "blue") y1 = t.pos() t.fd(43.3) t.goto(y1) t.seth(0) t.circle(30, 180) t.goto(y1) t.seth(0) t.seth(-45) t.fd(60) t.seth(0) if x == 18: t.pu() t.fd(50) t.lt(90) t.fd(30) t.seth(0) y = t.pos() t.pd() t.circle(21.6, -210) t.pu() t.goto(y) t.pd() t.seth(0) t.bk(10) t.circle(-21.6, 230) t.seth(0) t.pu() t.fd(45) t.rt(90) t.fd(10) t.seth(0) if x == 19: t.pu() t.fd(35) t.pd() y = t.pos() t.lt(90) t.fd(86.6) t.lt(90) t.fd(30) t.bk(60) t.lt(90) t.pu() t.fd(86.6) t.seth(0) if x == 20: t.lt(90) t.pu() t.fd(25) t.pd() t.fd(61) t.bk(61) t.seth(0) t.seth(-90) t.circle(25, 180) t.fd(61) t.pu() t.bk(86) t.seth(0) t.pd() if x == 21: t.seth(0) t.pu() t.fd(20) t.pd() y = t.pos() t.seth(65) t.fd(94) t.goto(y) t.seth(0) t.seth(115) t.fd(94) t.goto(y) if x == 22: t.seth(0) t.lt(90) t.fd(86.6) t.bk(86.6) t.seth(0) t.seth(54) t.fd(68) t.seth(0) t.seth(-54) t.fd(68) t.seth(0) t.lt(90) t.fd(86.6) t.bk(86.6) t.seth(0) if x == 23: t.seth(0) t.pu() t.fd(10) t.pd() t.seth(45) t.fd(90) t.bk(45) t.seth(0) t.seth(130) t.fd(45) t.bk(90) t.seth(0) if x == 24: t.seth(0) t.pu() t.fd(10) t.pd() t.seth(45) t.pu() t.fd(90) t.pd() t.bk(45) t.seth(0) t.seth(130) t.fd(45) t.bk(45) t.seth(0) t.seth(-90) t.fd(60) t.seth(0) t.pu() t.fd(30) t.pd() if x == 25: t.fd(65) y = t.pos() t.bk(65) t.seth(0) t.seth(45) t.fd(90) t.seth(0) t.seth(180) t.fd(65) t.pu() t.goto(y) t.seth(0) if x == 26: t.seth(0) t.pu() t.fd(25) t.pd() if x == 27: t.pu() t.seth(0) t.fd(10) y = t.pos() t.lt(90) t.fd(25) t.pd() t.dot(12, "blue") t.pu() t.goto(y) t.seth(0) t.fd(10) t.seth(0) t.pd()
def turtle_pos(turtle): return (round(turtle.xcor()), round(turtle.ycor()))
for i in range(5): turtle.fd(50) turtle.lt(72) for i in range(10): turtle.undo() # 回退,返回到之前的操作 turtle.speed(6) turtle.circle(40) print '--------------------------------------' print '--------------------------------------' # 2、Tell Turtle's state turtle.home() print turtle.position() turtle.goto(10, 10) # 直接去某一点 print turtle.position() print turtle.towards(0, 0) # (10,10)到(0,0)的角度为225度 turtle.goto(0, 0) print turtle.towards(10,10) # (0,0)到(10,10)的角度为45度 print '-------------------------------------' turtle.home() turtle.left(50) turtle.forward(100) print turtle.pos() print turtle.xcor() print turtle.ycor() # my_win.exitonclick()
#The Turtle's Postions # Returns the current location of the turtle as coordinates. # Either method works turtle.position() turtle.pos() # Returns the angle of line between the turtle's postion and the position specified by coordinates of another turtle # You can either use an x and y value, or your x value can be a pair of coordinates turtle.towards(0,0) # Returns the turtle's x coord. turtle.xcor() # Returns the turtle's y coord. turtle.ycor() # Returns the turtle's current orientation or heading turtle.heading() # Returns the distance from the turtle to a given coordinate or other turtle # You can either give an x and y value, or your x value can be a pair of coordinates turtle.distance(50,50) # -------------------------------------- #Measurement # Set angle measurement units (set numbr of "degree" for a full circle) # Default value is 360 degrees turtle.degrees(360)
t.home() t.seth(0) t.pd() t.color('black') t.circle(20, 80) # 0 t.circle(200, 30) # 1 t.circle(30, 60) # 2 t.circle(200, 29.5) # 3 t.color('black') t.circle(20, 60) # 4 t.circle(-150, 22) # 5 t.circle(-50, 10) # 6 t.circle(50, 70) # 7 # 确定鼻头大概位置 x_nose = t.xcor() y_nose = t.ycor() t.circle(30, 62) # 8 t.circle(200, 15) # 9 # 【鼻子】 t.pu() t.goto(x_nose, y_nose + 25) t.seth(90) t.pd() t.begin_fill() t.circle(8) t.end_fill() # 【眼睛】 t.pu() t.goto(x_nose + 48, y_nose + 55) t.seth(90) t.pd()
import turtle num_circle = 20 starting_radius = 20 offset = 10 animation_speed = 5 turtle.speed(animation_speed) radius = starting_radius for count in range(num_circle): turtle.circle(radius) x = turtle.xcor() y = turtle.ycor() - offset radius += offset turtle.penup turtle.goto(x, y) turtle.pendown() turtle.exitonclick()
def atBottomEdge(turtle, screen_height): if turtle.ycor() < -screen_height / 2: return True else: return False
def draw_distributed_load(self, sxcoor, sycoor, excoor, eycoor, py1, py2, orientation): loadarrow = 50. # # Draw the line at the base, turn to the starting position turtle.penup() turtle.setposition(sxcoor, sycoor) turtle.setheading(orientation) turtle.backward(10) # Note original coordinates xso = turtle.xcor() yso = turtle.ycor() turtle.setposition(excoor, eycoor) turtle.backward(10) xfo = turtle.xcor() yfo = turtle.ycor() turtle.pendown() turtle.setposition(xso, yso) # Get local coordinate along member axis, decide if horiz. or vertic. if sxcoor == excoor: # Vertical member xs = yso xf = yfo ys = xso yf = xfo alignment = 'v' elif sycoor == eycoor: # Horizontal member xs = xso xf = xfo ys = yso yf = yfo alignment = 'h' xdiff = xf - xs narrow = 11. x = 0. step = xdiff / narrow # # Make distinctions between different load cases # # Uniform loading if py1 == py2: loadtext = ''.join([str(py1), ' kN/m']) turtle.backward(loadarrow) turtle.forward(loadarrow) self.draw_arrow(arrowsize=5) turtle.backward(loadarrow) while x < xdiff: turtle.left(90) turtle.forward(step) turtle.right(90) turtle.forward(loadarrow) self.draw_arrow(arrowsize=5) turtle.backward(loadarrow) x = x + step turtle.penup() # go to midpoint of the load to write the label if alignment == 'h': turtle.setx(turtle.xcor() - xdiff / 2) turtle.write(loadtext, align='center', font=("Times New Roman", 18, "")) elif alignment == 'v': turtle.sety(turtle.ycor() - xdiff / 2) turtle.write(loadtext, align='right', font=("Times New Roman", 18, "")) # Triangle starting from 0 ending at Py2 if (py1 == 0) or (py2 == 0): if py1 == 0: sgn = 1. loadtext = ''.join([str(py2), ' kN/m']) phase = 0. yp1 = 0. yp2 = loadarrow * 2 slope = np.arctan(yp2 / xdiff) slopedeg = slope * 180 / np.pi x = xs + step y = ys + np.tan(slope) * step xs = xs yco = 0 elif py2 == 0: sgn = -1. loadtext = ''.join([str(py1), ' kN/m']) turtle.penup() turtle.setposition(xfo, yfo) turtle.pendown() yp1 = loadarrow * 2 yp2 = 0. slope = np.arctan(yp1 / xdiff) slopedeg = slope * 180 / np.pi phase = (180 - 2 * slopedeg) x = xf - step y = yf + np.tan(slope) * step xs = xf # Drawing from left to right yco = 0 while abs(x - xs) <= xdiff: turtle.left(90 + slopedeg + phase) dy = step * np.tan(slope) yco += dy dist = np.sqrt(dy**2 + step**2) turtle.forward(dist) turtle.right(90 + slopedeg + phase) turtle.forward(yco) self.draw_arrow(arrowsize=5) turtle.backward(yco) x = x + step * sgn turtle.write(loadtext, align='center', font=("Times New Roman", 18, "")) return
# Set up the screen wn = turtle.Screen() wn.title("Snake Game by Almeida") wn.bgcolor("blue") wn.setup(width=600, height=600) wn.tracer(0) #when 0, screen updates turn off #Snake Head head = turtle.Turtle() head.speed(0) head.shape("square") head.color("white") head.penup() head.goto(0,0) head.direction = "left" head.onscreenclick(lambda x, y: turtle.goto(x, y) or print(turtle.xcor(), turtle.ycor()) # Snake food food = turtle.Turtle() food.speed(0) food.shape("circle") food.color("red") food.penup() food.goto(0, 100) # Needs to be corrected. Initial postiion should be random and not (0, 100) segments = [] #Functions def move(): if head.direction == "up":
turtle.pensize(pSize) turtle.setup(width=swidth + 30, height=sheight + 30) turtle.screensize(swidth, sheight) while True: r = random.random() g = random.random() b = random.random() turtle.pencolor((r, g, b)) angle = random.randrange(0, 360) dist = random.randrange(1, 100) turtle.left(angle) turtle.forward(dist) curX = turtle.xcor() curY = turtle.ycor() if (-swidth / 2 <= curX and curX <= swidth / 2) and (-sheight / 2 <= curY and curY <= sheight / 2): pass else: turtle.penup() turtle.goto(0, 0) turtle.pendown() exitCount += 1 if exitCount >= 5: break turtle.done()
def ㄴ(): t.pendown() t.setheading(180) t.forward(100) t.setheading(90) t.forward(45) t.penup() t.penup() t.goto(-250, 150) ㅎ() t.forward(100) t.goto(t.xcor() - 50, t.ycor()) ㅗ() t.goto(t.xcor(), t.ycor() - 45) t.setheading(180) ㅇ(28) t.goto(0, 150) ㄷ() t.goto(t.xcor() - 50, t.ycor() - 55) ㅗ() t.goto(t.xcor(), t.ycor() - 45) t.setheading(180) ㅇ(30) t.goto(150, 150) ㅎ() t.goto(t.xcor() + 80, t.ycor() + 30) ㅕ()
def right(): turtle.onkeypress("d") turtle.pos() turtle.goto(turtle.xcor() + 10, turtle.ycor())