def drawIt(backAgain): turtle.penup() turtle.setpos(0,vertHeight) turtle.pendown() upDown = True start = turtle.xcor() for i in range(iterLength): randomyUpDownVariance = randint(1,55) randomyBetweenLineVariance = randint(1,25) randPenSize = randint(2,10) randPenColor1 = randint(1,187) randPenColor2 = randint(1,193) randPenColor3 = randint(1,182) turtle.pensize(randPenSize) print turtle.xcor() tup = (randPenColor1, randPenColor2, randPenColor3) turtle.pencolor(tup) if upDown == True: upDown = False turtle.goto(start, (vertHeight + randomyUpDownVariance)) elif upDown == False: upDown = True turtle.goto(start, -(vertHeight + randomyUpDownVariance)) if backAgain == True: start -= randomyBetweenLineVariance elif backAgain == False: start += randomyBetweenLineVariance if (backAgain == True): drawIt(False)
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 checkxbound(): if turtle.xcor() > (wn.screensize()[0]/2): return 1 elif turtle.xcor() < (wn.screensize()[0]/-2): return 2 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 draw_backward_e(x,y,h=100): if x == None: x = turtle.xcor() y = turtle.xcor() go(x,y) turtle.goto(x+h/2 ,y) turtle.goto(x+h/2,h/2+y) turtle.goto(x,h/2+y) turtle.goto(x+h/2,y+h/2) turtle.goto(x+h/2,y+h) turtle.goto(x,y+h) go(x+h,y)
def numberXtickers(): current = xscale*(xmin//xscale) tickerLength = float(ymax-ymin)/40 while current < xmin: current += xscale toXY(current,-2*tickerLength) while current <= xmax: if turtle.xcor() != 0: turtle.write(turtle.xcor(),align="center",font=("Arial",12,"normal")) current += xscale toXY(current,-2*tickerLength)
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 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 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 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 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 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 city_circle(city): turtle.penup() turtle.setx(city.xcoord) turtle.sety(city.ycoord) if city.getpop() > 0 and city.getpop() < 90001: turtle.setx(turtle.xcor() + 2) turtle.pendown() turtle.circle(2) turtle.penup() turtle.setx(turtle.xcor() - 2) if city.getpop() > 90000: turtle.setx(turtle.xcor() + 3) turtle.pendown() turtle.begin_fill() turtle.circle(3) turtle.end_fill() turtle.penup() turtle.setx(turtle.xcor() - 3)
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 space(): """ Adds a space of 25 pixels. This acts as a logical separator between two words. :pre: (relative) pos (0,0), heading (north), up :post: (relative) pos (25,0), heading (north), up :return: None """ turtle.up() turtle.setposition(turtle.xcor() + 25, 0)
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 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 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 hola(): '''draws hola world message in cool green color''' turtle.setheading(0) pu() turtle.setx(-215) pd() draw_letters(True, "green", h, o, l, a) pu() turtle.setx(turtle.xcor() + 30) draw_letters(True, "green", w, o, r, l, d)
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 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 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 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 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 drawPancake(): turtle.pencolor("white") turtle.pensize(3) for i in range(1,20): turtle.left(245) for i in range(1,15): turtle.forward(i) turtle.left(2*i) myNewCoords.append('G00 X'+ str(round(turtle.xcor(),2))+' Y'+str(round(turtle.ycor(),2)))
def move(self, screen_l, screen_w): c_x_pos = turtle.xcor() n_x_pos = c_x_pos + self.dx c_y_pos = turtle.ycor() n_y_pos = c_y_pos + self.dy r_size_ball = n_x_pos + self.r l_size_ball = -n_x_pos - self.r u_size_ball = n_y_pos + self.r d_size_ball = -n_y_pos - self.r turtle.goto(n_x_pos, n_y_pos) while self.status == True: if r_size_ball >= screen_w: turtle.goto(turtle.xcor() - 1, turtle.ycor()) if l_size_ball <= -screen_w: turtle.goto(turtle.xcor() + 1, turtle.ycor()) if u_size_ball >= screen_l: turtle.goto(turtle.xcor(), turtle.ycor() - 1) if d_size_ball <= -screen_l: turtle.goto(turtle.xcor(), turtle.ycor() + 1)
def text(content, size, x3, y3): global current_x, current_y, position turtle.penup() # Raise the pen turtle.goto(x3, y3) turtle.pencolor(colour) # Set the pen color style = ('Courier', size, 'normal') turtle.write(content, font=style, align='center') #Assigning the values of the current turtle x and y coordinates to the #global x and y coordinates current_x = turtle.xcor() current_y = turtle.ycor() position = turtle.pos()
def move(self, screen_width,screen_height): ouo_pos=turtle.xpos() ixs_pos=ouo_pos+dx myo_pos=turtle.ypos() iyo_pos=myo_pos+dy right_size_ball=ixs_pos+self.r left_size_ball=ixs_pos+-self.r up_size_ball=iyo_pos+self.r down_size_ball=iyo_pos-self.r turtle.goto(ixs_pos,iyo_pos) while right_size_ball >= screen_width : turtle.goto(turtle.xcor()-1,turtle.ycor()) while left_size_ball<=screen_width : turtle.goto(turtle.xcor()+1,turtle.ycor()) while up_size_ball>=screen_height : turtle.goto(turtle.xcor(),turtle.ycor()-1) while down_size_ball>=screen_height : turtle.goto(turtle.xcor(),turtle.ycor()+1)
def move(self): while (True): self.fd(1) postx = turtle.xcor() posty = turtle.ycor() if (postx > 50 or postx < -50 or posty > 50 or posty < -50): turtle.left(90) turtle.left(random.randint())
def labelGrid(): rows = ['A', 'B', 'C', 'D'] cols = ['1', '2', '3', '4'] for row_name in rows: turtle.write(row_name, move=False, align='left', font=('Georgia', 40, 'normal')) turtle.sety(turtle.ycor() - 40) turtle.goto(-65, 75) for col_name in cols: turtle.write(col_name, move=False, align='left', font=('Georgia', 40, 'normal')) turtle.setx(turtle.xcor() + 40)
def labelGrid(): rows = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'] cols = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] for row_name in rows: turtle.write(row_name, move=False, align='left', font=('Arial', 20, 'bold')) turtle.sety(turtle.ycor() - 40) turtle.goto(-165, 185) for col_name in cols: turtle.write(col_name, move=False, align='left', font=('Arial', 20, 'bold')) turtle.setx(turtle.xcor() + 40)
def plot(k): numPrimes = 0 turtle.pu() turtle.hideturtle() turtle.speed(10) turtle.pencolor("orange") turtle.write(2, font=stylePrime) spacerValue = 45 #spacerCounter = 10 n = 1 dir = 1 count = 0 for i in range(20): # print("k:", k) for j in range(n): turtle.setx(turtle.xcor() + spacerValue * dir) if pl[k] in fp and pl[k] in l: turtle.pencolor("orange") turtle.write(pl[k], font=stylePrime) elif pl[k] in l: numPrimes += 1 turtle.pencolor("red") turtle.write(pl[k], font=stylePrime) elif pl[k] in fp: numPrimes += 1 turtle.pencolor("green") turtle.write(pl[k], font=stylePrime) else: turtle.pencolor("black") turtle.write(pl[k], font=styleNormal) k += 1 for j in range(n): turtle.sety(turtle.ycor() + spacerValue * dir) if pl[k] in fp and pl[k] in l: turtle.pencolor("orange") turtle.write(pl[k], font=stylePrime) elif pl[k] in l: numPrimes += 1 turtle.pencolor("red") turtle.write(pl[k], font=stylePrime) elif pl[k] in fp: numPrimes += 1 turtle.pencolor("green") turtle.write(pl[k], font=stylePrime) else: turtle.pencolor("black") turtle.write(pl[k], font=styleNormal) k += 1 n += 1 dir = -dir turtle.hideturtle()
def sjekk_landing(): x = turtle.xcor() vinkel = turtle.heading() if x < -200 or x > 0: print('Du landet utenfor basen!') elif abs(vinkel - 90) > 10: print('Du landet skjevt!') elif romskip['fart_y'] < -1: print('Du landet for hardt!') else: print('Perfekt landing!')
def rightWall(grid): drawGrid(grid) turtle.setx(1) turtle.sety(1) turtle.pencolor("blue") turtle.pendown() while int(round(turtle.xcor())) != 8 or int(round(turtle.ycor())) != 8: angle = turtle.heading() right = angle - 90 left = angle + 90 back = angle + 180 forward = angle if back == 360: back = 0 if back == 450: back = 90 if left == 360: left = 0 if right == -90: right = 270 if moveValid(grid, int(round(turtle.xcor())), int(round(turtle.ycor())), right): turtle.setheading(right) turtle.forward(1) elif moveValid(grid, int(round(turtle.xcor())), int(round(turtle.ycor())), forward): turtle.setheading(forward) turtle.forward(1) elif moveValid(grid, int(round(turtle.xcor())), int(round(turtle.ycor())), left): turtle.setheading(left) elif moveValid(grid, int(round(turtle.xcor())), int(round(turtle.ycor())), back): turtle.setheading(back) turtle.forward(1)
def drawboard(board): turtle.setworldcoordinates(-248,-248,0,0) numbers=('1','2','3','4','5','6','7','8') turtle.hideturtle() turtle.speed(0) turtle.penup() turtle.goto(-223,-10) turtle.shape("square") turtle.color("blue") turtle.resizemode("user") turtle.shapesize(25,25,10) for i in range(0,8): turtle.color("black") turtle.write(numbers[i], font=("Arial",15,"normal")) turtle.goto(turtle.xcor()+25, turtle.ycor()) turtle.goto(-240, turtle.ycor()-15) for i, row in enumerate(board): turtle.color("black") turtle.write(numbers[i], font=("Arial",15,"normal")) turtle.goto(turtle.xcor()+19,turtle.ycor()) for column in row: turtle.shape('square') turtle.color("blue") turtle.shapesize(2,2) turtle.stamp() if column==1: turtle.shape("circle") turtle.color("white") turtle.shapesize(1,1) turtle.stamp() turtle.goto(turtle.xcor()+25,turtle.ycor()) elif column==2: turtle.shape("circle") turtle.color("black") turtle.shapesize(1,1) turtle.stamp() turtle.goto(turtle.xcor()+25,turtle.ycor()) else: turtle.goto(turtle.xcor()+25,turtle.ycor()) turtle.goto(-240, turtle.ycor()-25)
def start(x, y): turtle.onscreenclick(None) window() tfood = turtle.Turtle() tfood.hideturtle() tfood.pu() tfood.speed(0) tfood.shape("square") tfood.color("blue") tscore = turtle.Turtle() tscore.hideturtle() tscore.pu() tscore.speed(0) tscore.goto(100, -250) tscore.write("Score:" + str(a[0]), align="center", font=(10)) #height and width while x > -210 and x < 210 and y > -210 and y < 210: if foodcoord[2] == 0: food(tfood) foodcoord[2] = 1 turtle.onkey(u, "Up") turtle.onkey(l, "Left") turtle.onkey(r, "Right") turtle.onkey(d, "Down") turtle.listen() move() x = turtle.xcor() y = turtle.ycor() #within the board if x > foodcoord[0] * 20 - 5 and x < foodcoord[ 0] * 20 + 5 and y > foodcoord[1] * 20 - 5 and y < foodcoord[ 1] * 20 + 5: foodcoord[2] = 0 tfood.clear() #it gets removed a[0] += 1 #score gets added tscore.clear() #score updates tscore.write("Score:" + str(a[0]), align="center", font=(10)) if len(cpos) > 1: for i in range(1, len(cpos)): if x < cpos[i][0] + 5 and x > cpos[i][0] - 5 and y < cpos[i][ 1] + 5 and y > cpos[i][1] - 5: tscore.clear() tfood.clear() gameover() tscore.clear() tfood.clear() gameover()
def printing(ITERATIONS, step, TRANSFORMATION, base_string, **rule): for i in range(ITERATIONS): base_string = TRANSFORMATION(base_string, **rule) turtle.tracer(0, 0) turtle.penup() turtle.setx(0) turtle.sety(-350) turtle.setheading(90) turtle.pensize(12) turtle.pendown() stack = [] for ch in base_string: if ch == '1': turtle.forward(step) elif ch == '2': # эта двойка - вообще колдовство чтобы было красиво # поэтому рандом объяснить никак, так просто красивее :) if random.randint(1, 3) == 1: turtle.forward(step) elif ch == '0': # 0 рисует последние отрезки, т.е. "листики" stack.append(turtle.pensize()) # "листики" должны быть потолще turtle.pensize(turtle.pensize() + 2) # Установим случайным образом какой-нибудь зелёный на листики if random.randint(1, 9) <= 3: turtle.pencolor(0, 1, 0) elif 4 <= random.randint(1, 9) <= 6: turtle.pencolor(0, 0.7, 0) else: turtle.pencolor(0, 0.5, 0) turtle.forward(step) turtle.pensize(stack.pop()) turtle.pencolor(0, 0, 0) elif ch == '-': turtle.left(rule['angle'] - random.randint(0, 10)) elif ch == '+': turtle.right(rule['angle'] - random.randint(0, 10)) elif ch == '[': stack.append(turtle.ycor()) stack.append(turtle.xcor()) stack.append(turtle.heading()) # "веточки" становятся всё тоньше turtle.pensize(0.825 * turtle.pensize()) stack.append(turtle.pensize()) elif ch == ']': turtle.penup() turtle.pensize(stack.pop()) turtle.setheading(stack.pop()) turtle.setx(stack.pop()) turtle.sety(stack.pop()) turtle.pendown() turtle.update() turtle.done()
def move_food(): global TIME_STEP food.penup() food.backward(SQUARE_SIZE) if (food.xcor() - 60 < turtle.xcor() < food.xcor() + 60) and ( food.ycor() - 45 < turtle.ycor() < food.ycor() + 45): print("You ate the jellyfish nice!!!") #score_count += 1 make_food() if food.xcor() <= -410: food.hideturtle() make_food() turtle.ontimer(move_food, TIME_STEP)
def move(directed_tile, diff_x, diff_y): global position global inventory deplacer(turtle.xcor() + diff_x, turtle.ycor() + diff_y) position = directed_tile if check_is_object(directed_tile): stop_movement() inventory.append(add_item_to_inventory(directed_tile)) update_inventory_box(turtle.pos()) start_movement()
def raceTurtleForX2(turtle, startPos): """make turtle move from right to left along top x axis""" #Round end position to avoid working with irrational floating points endPosition = round(startPos[0], 4) #Round x coordinate to avoid working with irrational floating points xPos = round(turtle.xcor(), 4) #if the current position is less then the end position move forward if xPos > endPosition: turtle.forward(random.randint(0, speed)) #if it is greater then move the turtle to the correct position and turn left elif xPos < endPosition: turtle.setx(startPos[0]) turtle.left(90)
def dot(): t.up() x = t.xcor() t.goto(x + 9, 0) t.down() for i in range(2): t.left(90) t.fd(10) t.right(90) t.fd(1) t.right(90) t.fd(10) t.left(90)
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 drawHexagon(numIters, baseStep, x, y): exp = (numIters - 3) / 2 + 1 xDif = baseStep * (3**exp) yDif = 1 / 3 * xDif * math.sin(math.pi / 3) turtle.penup() turtle.setx(x) turtle.sety(y) turtle.pendown for i in range(6): Hoch = HochInit(cx=turtle.xcor(), cy=turtle.ycor(), heading=(60 * i) % 360) draw(Hoch, baseStep=baseStep, numIters=numIters)
def hexagons_tiles(n1, n, x, y, side_len, color, coef2, coef1): if n1 == 1: hexagons_line(n, x, y, side_len, color) else: hexagons_line(n, x, y, side_len, color) if n1 % 2 != 0: t.up() t.backward(((n - 1) * (coef1 * side_len)) + (side_len / 2)) x_new = t.xcor() y_new = y - side_len - (side_len / 2) t.up() hexagons_tiles(n1 - 1, n, x_new, y_new, side_len, color, coef2, coef1) else: t.up() t.backward(((n - 1) * (coef2 * side_len)) - (side_len / 2)) x_new = t.xcor() y_new = y - side_len - (side_len / 2) hexagons_tiles(n1 - 1, n, x_new, y_new, side_len, color, coef2, coef1)
def arc(radius, angle): global current_x,current_y turtle.clear() #Clear the turtle screen turtle.penup() # Raise the pen turtle.goto(current_x, current_y - radius) # Position the turtle turtle.pencolor(colour) # Set the pen color turtle.pensize(thickness) #Set the pen thickness turtle.pendown() # Lower the pen turtle.circle(radius,angle) # Draw an arc with the given radius and angle #Assigning the values of the current turtle x and y coordinates to the #global x and y coordinates current_x=turtle.xcor() current_y=turtle.ycor()
def accelx(a,b,d):#x좌표를 이용해서 가속도를 받을 좌표를 구하는 함수 설정 xacl = t.xcor() #현재 거북이 좌표를 xacl에 저장 xc = float(xacl) #xacl을 실수형으로 변환 if xc+2*d <= 250 or xc+2*d >= -250 :#거북이의 x좌표가 경계에 닿으면 2단계에 걸쳐 가속도가 붙는다 t.speed(a) # 가속도 붙을시 가속도로 인해 경계를 넘어 가는것을 if문으로 방지 t.fd(d) #현재의 x좌표에 가속도를 받았을 때의 좌표를 미리 구해 넘어가지 않을때만 해당 함수를 실행하도록 설정 t.speed(b) # xc+2*d로 2단계 가속도 받을때 넘어가는것 방지 t.fd(d) elif xc+d <= 250 or xc+d >= -250 : #거리로 인해 2단계 가속도 실행이 불가할때 1단계 가속도를 실행하도록 설정 t.speed(a) #xc+d 로 1단계 가속도 받을떄 넘어가는것 방지 t.fd(d)
def draw(cmds, size=2): stack = [] for cmd in cmds: if cmd == 'A': turtle.forward(size) elif cmd == 'B': turtle.penup() turtle.setx(turtle.xcor() + size) turtle.pendown() else: raise ValueError("Unknown Cmd: {}".format(ord(cmd))) turtle.update()
def line(x1, y1, x2, y2): turtle.clear() #Clear the turtle screen turtle.penup() # Raise the pen turtle.goto(x1, y1) # Move to the starting point turtle.pencolor(colour) # Set the pen color turtle.pensize(thickness) #Set the pen thickness turtle.pendown() # Lower the pen turtle.goto(x2, y2) # Draw a line #Assigning the values of the current x and y coordinates to the #global x and y coordinates global current_x,current_y current_x=turtle.xcor() current_y=turtle.ycor()
def c(): turtle.left(90); turtle.forward(50); turtle.right(90); turtle.forward(50); turtle.right(90); turtle.penup(); turtle.setx(turtle.xcor() - 50); turtle.sety(turtle.ycor() - 50); turtle.pendown(); turtle.forward(50); turtle.left(90); turtle.forward(50);
def race(): # MOVE TURTLES win = False while not win: for index, t in enumerate(turtles): t.forward(randint(1, 5)) if t.xcor() >= 200: print('The winner is turtle #', index + 1, "!") win = True t.speed(1) t.right(270) # Victory spin break
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 draw_half_row_grass(row_width, blade_length, direction, ygr_percents): """ Draws a half of one row of grass in a grass patch. :param row_width: width of the row :param blade_length: length of each blade of grass :param direction: 1 if drawing right, -1 if drawing left :param ygr_percents: percents of yellow, green and red in the grass """ # Determine the steps to move from one blade to next step_size = turtle.width() * 3 step_count = row_width // step_size + 1 degree_step = 90 / step_count # Account for drawing direction step_size *= direction degree_step *= direction # Save where the turtle starts so that it can be returned to when finished x_start = turtle.xcor() # Draw the grass blades turtle.down() for i in range(step_count): # Set this blades color randomly based on YGR percents turtle.color(get_rand_leaf_color(ygr_percents)) # Draw one blade of grass turtle.forward(blade_length) turtle.backward(blade_length) # Reposition to draw next one, angling it closer to ground than previous turtle.right(degree_step) turtle.goto(turtle.xcor() + step_size, turtle.ycor()) # Return turtle to starting position turtle.up() turtle.goto(x_start, turtle.ycor()) turtle.left(90 * direction)
def mnogougolnik(a=100, n=3): r = a / (2 * math.sin(2 * math.pi / (2 * n))) angel = 360 / n turtle.penup() turtle.forward(r - turtle.xcor()) turtle.pendown() angel_sdvig = 90 - (180 * (n - 2)) / (n * 2) turtle.left(90 + angel_sdvig) turtle.forward(a) while n > 1: n -= 1 turtle.left(angel) turtle.forward(a) turtle.right(90 - angel_sdvig)
def drawRandomLines(speed, pensize, rrange, ranNumBeg, ranNumEnd): turtle.speed(speed) turtle.pensize(pensize) for step in range(rrange): ranNum = random.randint(ranNumBeg, ranNumEnd) turtleDir = random.randint(1, 5) #decide which direction to move in moveTurtleRandomDirection(turtleDir, ranNum) turtle.pensize(random.randint(1, 4)) if abs(turtle.xcor()) >= 100 or abs(turtle.ycor( )) >= 100: #return to center if moving beyond corners of screen turtle.goto(0, 0) turtle.goto(0, 0)
def move_left(): x = chef.xcor() x -= chef_speed for pancake in game.pancake_list: turtle = pancake.turtle # turtle.hideturtle() turtle.penup() pancake_x = turtle.xcor() if x > -100 and not pancake.on_plate and not game.freeze: chef.setx(x) if x > -100 and pancake.on_plate and not game.freeze: chef.setx(x) pancake_x -= chef_speed turtle.setx(pancake_x)
def move_right(): x = chef.xcor() x += chef_speed for pancake in game.pancake_list: turtle = pancake.turtle turtle.penup() pancake_x = turtle.xcor() # turtle.hideturtle() if x < 290 and not pancake.on_plate and not game.freeze: chef.setx(x) if x < 290 and pancake.on_plate and not game.freeze: chef.setx(x) pancake_x += chef_speed turtle.setx(pancake_x)