def display(self): turtle.clear() # draws all live cells from grid.state for i in range(self.xspan): for j in range(self.yspan): self.draw(i, j) turtle.update()
def show_robot(self, robot): turtle.color("blue") turtle.shape('square') turtle.setposition(*robot.xy) turtle.setheading(math.degrees(robot.h)) turtle.stamp() turtle.update()
def show_robot(self, robot): turtle.color("green") turtle.shape('turtle') turtle.setposition(*robot.xy) turtle.setheading(robot.h) turtle.stamp() turtle.update()
def show_shark(self, shark): turtle.color(shark.color) turtle.shape('turtle') turtle.setposition(*shark.xy) turtle.setheading(math.degrees(shark.h)) turtle.stamp() turtle.update()
def draw(cmds, size=2): #output tree stack = [] for cmd in cmds: if cmd=='F': turtle.forward(size) elif cmd=='-': t = random.randrange(0,7,1) p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] turtle.color(p[t]) turtle.left(15) #slope left elif cmd=='+': turtle.right(15) #slope right t = random.randrange(0,7,1) #рандомная пер. для цвета p = ["Red","Green","Blue","Grey","Yellow","Pink","Brown"] #ряд цветов turtle.color(p[t]) #выбор цвета из ряда elif cmd=='X': pass elif cmd=='[': stack.append((turtle.position(), turtle.heading())) elif cmd==']': position, heading = stack.pop() turtle.penup() turtle.setposition(position) turtle.setheading(heading) turtle.pendown() turtle.update()
def tree1(argv, x, y): lsys_filename1 = argv[1] lsys1 = ls.createLsystemFromFile( lsys_filename1 ) print lsys1 num_iter1 = int( 3 ) dist = float( 5 ) angle1 = float( 22 ) s1 = ls.buildString( lsys1, num_iter1 ) #draw lsystem1 '''this is my first lsystem with filename mysystem1.txt with 3 iterations and with angle = 45 dist = 10''' turtle.tracer(False) turtle.speed(50000000) turtle.up() turtle.goto(0,0) turtle.goto(x, y) turtle.down() turtle.pencolor('White') it.drawString( s1, dist, angle1 ) # wait and update turtle.update()
def draw(self, x, y, width, height, max_length=None, force_fields=None): """Draw the string. The grammar-system axiom is extended to the specified depth""" self.reset() turtle.setup(width,height,None,None) turtle.tracer(200,0) self.penup() self.setposition(x,y) self.origin = x, y self.max_length = max_length while not self.grammar_system.done and \ self.grammar_system.generation < self.depth: self.grammar_system.step() if (self.max_length is not None and len(self.grammar_system.string) > self.max_length): self.hideturtle() print("Drawing exceeded maximum length") return False print(self.grammar_system.string) if force_fields: for force_field in force_fields: self.force_fields.append(Attractor(force_field['type'], force_field['effect'], force_field['x'], force_field['y'], force_field['size'])) non_null = self._draw(self.grammar_system.string, self._rules) self.hideturtle() turtle.update() return non_null
def calculatePoints(center, radius, intPoints, t, dots, update, angle): global differAngle fullCircle = 360 differAngle = float(fullCircle) / float(pointsInt) currDegree = angle # sett til 90 for aa starte fra toppen for i in xrange(pointsInt): t.setx(0) t.sety(0) t.setheading(currDegree) # t.pendown() t.forward(radiusInt) # t.penup() currDegree = currDegree - differAngle if dots: t.dot() if update: turtle.update() if debug: print t.pos() pointsArray[i][0] = t.pos()[0] pointsArray[i][1] = t.pos()[1]
def rysuj(): turtle.tracer(0, 0) # wylaczenie animacji co KROK, w celu przyspieszenia turtle.hideturtle() # ukrycie glowki zolwika turtle.penup() # podnosimy zolwia, zeby nie mazal nam linii podczas ruchu ostatnie_rysowanie = 0 # ile kropek temu zostal odrysowany rysunek for i in xrange(ILE_KROPEK): # losujemy wierzcholek do ktorego bedziemy zmierzac do = random.choice(WIERZCHOLKI) # bierzemy nasza aktualna pozycje teraz = turtle.position() # ustawiamy sie w polowie drogi do wierzcholka, ktorego wczesniej obralismy turtle.setpos(w_polowie_drogi(teraz, do)) # stawiamy kropke w nowym miejscu turtle.dot(1) ostatnie_rysowanie += 1 if ostatnie_rysowanie == OKRES_ODSWIEZENIA: # postawilismy na tyle duzo kropek, zeby odswiezyc rysunek turtle.update() ostatnie_rysowanie = 0 pozdrowienia() turtle.update()
def tree2(argv, x, y): lsys_filename2 = argv[2] lsys2 = ls.createLsystemFromFile( lsys_filename2 ) print lsys2 num_iter2 = int( 3 ) dist = float( 5 ) angle2 = float( 30 ) s2 = ls.buildString( lsys2, num_iter2 ) #draw lsystem2 '''this is my second lsystem with filename mysystem2.txt with 5 iterations and with angle = 120 dist = 10''' turtle.up() turtle.goto(0,0) turtle.goto(x,y) turtle.down() turtle.setheading(0) turtle.left(90) turtle.pencolor('White') it.drawString( s2, dist, angle2 ) # wait and update turtle.update()
def sun(argv): lsys_filename3 = argv[3] lsys3 = ls.createLsystemFromFile( lsys_filename3 ) print lsys3 num_iter3 = int( 3 ) dist = 5 angle3 = float( 120 ) s3 = ls.buildString( lsys3, num_iter3 ) #draw lsystem3 '''this is my third lsystem with filename mysystem3.txt with 3 iterations and with angle = 45 dist = 10''' turtle.up() turtle.goto(0,0) turtle.goto(300, 200) turtle.down() turtle.setheading(0) turtle.left(90) turtle.pencolor('Red') it.drawString( s3, dist, angle3 ) # wait and update turtle.update()
def s(n, l): if n == 0: # stop conditions # draw filled rectangle turtle.color('black') turtle.begin_fill() for _ in range (4): turtle.forward(l) turtle.left(90) turtle.end_fill() else: # recursion # around center point create 8 smalles rectangles. # create two rectangles on every side # so you have to repeat it four times for _ in range(4): # first rectangle s(n-1, l/3) turtle.forward(l/3) # second rectangle s(n-1, l/3) turtle.forward(l/3) # go to next corner turtle.forward(l/3) turtle.left(90) # update screen turtle.update()
def show_robot(self, robot): turtle.color("green") turtle.shape('turtle') turtle.setposition([robot.x + self.width / 2, robot.y + self.height / 2]) turtle.setheading(robot.theta / pi * 180.0) turtle.stamp() turtle.update()
def show_goal_posts(self, goal_posts): for p in goal_posts: turtle.color("#FFFF00") turtle.setposition(p[0], p[1]) turtle.shape("circle") turtle.stamp() turtle.update()
def draw(self, size, step, colors = 0, so_fast = False, turtl = None): if not turtl: turtl = franklinBegin() base = self.get_step(step, colors = colors) angle = self.angle ls = [] turtl.setheading(self.head) for char in base: if char in self.fd: turtl.forward(size) elif char == '+': turtl.left(angle) elif char == '-': turtl.right(angle) elif char == '[': ls.append(turtl.clone()) elif char == ']': turtl = ls.pop() elif char == 'R': turtl.right(360*random.random()) elif char == 'c': newcolor = (0.3 + 0.7*random.random(), 0.3 + 0.7*random.random(), 0.3 + 0.7*random.random()) turtl.color(newcolor, newcolor) if not so_fast: turtle.update() turtle.update()
def drawString( dstring, distance, angle ): """ Interpret the characters in string dstring as a series of turtle commands. Distance specifies the distance to travel for each forward command. Angle specifies the angle (in degrees) for each right or left command. The list of turtle supported turtle commands is: F : forward - : turn right + : turn left [ : save position, heading ] : restore position, heading """ stack = [] for c in dstring: if c == 'F': turtle.forward(distance) elif c == '-': turtle.right(angle) elif c == '+': turtle.left(angle) elif c == '[': stack.append(turtle.position()) stack.append(turtle.heading()) elif c == ']': turtle.up() turtle.setheading(stack.pop()) turtle.goto(stack.pop()) turtle.down() turtle.update()
def display(self): """Draw the whole board""" turtle.clear() for i in range(self.xsize): for j in range(self.ysize): self.draw(i, j) turtle.update()
def draw(self, w, h, dot = False): norm = CoordinateNormalizer(self, w, h) window = turtle.Screen() cursor = turtle.Turtle() window.setup(w, h) window.setworldcoordinates(0, 0, w, h) window.delay(0) cursor.ht() turtle.tracer(0) cursor.up() for way in self.getWays(): tags = self.ways[way].tags line = self.getPolyline(way) for (x, y) in line: cursor.pencolor('black') x, y = norm(x, y) cursor.setpos(x, y) if dot: cursor.dot() if not cursor.isdown(): cursor.down() cursor.up() turtle.update() window.exitonclick()
def drawPattern(turt, offx, offy, radius, step): # Points is the number of points per side, NOT including the corner points # Draw lines between the points around teh box in the given pattern # drawRect(turt, offx, offy, sizex, sizey) # Basic rectangle to outline the shape pointsl = drawCricle(turt, offx, offy, radius, step) turtle.tracer(1) for p in range(len(pointsl)): turt.color(getRandColor(cols)) for p2 in range(len(pointsl)-3): if not p+p2+2 > len(pointsl)-1: drawLine(turt, pointsl[p][0], pointsl[p][1], pointsl[p+p2+2][0], pointsl[p+p2+2][1]) else: drawLine(turt, pointsl[p][0], pointsl[p][1], pointsl[p+p2+2 - len(pointsl)][0], pointsl[p+p2+2 - len(pointsl)][1]) turtle.update() # Draw a nice looking border around the rectangle # turt.pensize(10) # Make it thick # drawRect(turt, offx, offy, sizex, sizey) # turt.pensize(1) # Reset pen size turt.penup() turt.setpos(offx, offy) #Sit in the centre of the circle at the end turtle.update()
def Run(): #bounds nearRange = [0, 50] farRange = [50, 200] frusHL = 100 #Logic nearDist = random.uniform(nearRange[0], nearRange[1]) farDist = random.uniform(farRange[0], farRange[1]) d = frusHL * 2 an = nearDist af = farDist b = (d*d + af*af - an*an) / (2 * d) radius = math.sqrt(b*b + an*an) originY = -frusHL + b #text.insert('end', 'Origin: %d\n' % originY) #Render turtle.clear() turtle.hideturtle() turtle.tracer(0, 0) turtle.penup() turtle.goto(-farDist, frusHL) turtle.pendown() turtle.goto(-nearDist, -frusHL) turtle.goto(nearDist, -frusHL) turtle.goto(farDist, frusHL) turtle.goto(-farDist, frusHL) turtle.penup() DrawCircle(0, originY, radius); turtle.update()
def animate_fw(slide1, slide2): for i in range(100): turtle.clear() draw_slide(slide1[0],slide1[1],-885+(i*8.85),0) draw_slide(slide2[0],slide2[1],i*8.85,0) turtle.update() return
def draw_pattern(pattern): n = len(pattern) // 4 for i in range(n): s, e = i * 4, i * 4 + 4 start, end, p1, p2 = pattern[s:e] draw_bezier(t, bezier_steps, start, end, p1, p2) turtle.update()
def drawTrig(size): ragolo.forward(size) ragolo.right(120) ragolo.forward(size) ragolo.right(120) ragolo.forward(size) ragolo.right(120) turtle.update()
def drawRect(t, x1, y1, sizex, sizey): # Simply draws a rectangle turtle.tracer(0) # If this is 0, the rectangle is drawn instantly drawLine(t, x1 - sizex/2, y1 - sizey/2, x1 + sizex/2, y1 - sizey/2) # Up drawLine(t, x1 - sizex/2, y1 + sizey/2, x1 + sizex/2, y1 + sizey/2) # Down drawLine(t, x1 - sizex/2, y1 - sizey/2, x1 - sizex/2, y1 + sizey/2) # Left drawLine(t, x1 + sizex/2, y1 - sizey/2, x1 + sizex/2, y1 + sizey/2) # Right turtle.update()
def gameover(message): # Part 5.3 - Improving the gameover() function goturtle = turtle.Turtle() goturtle.hideturtle() goturtle.pencolor("yellow") goturtle.write(message, align="center", font=("System", 30, "bold")) turtle.update()
def show_particles(self, particles): turtle.clearstamps() for p in particles: turtle.setposition(*p.xy) turtle.setheading(p.h) turtle.color(self.weight_to_color(p.w)) turtle.stamp() turtle.update()
def draw_board_1(x, y): #drawing the board by drawing each cell in a loop for i in range(BOARD_WIDTH): for j in range(BOARD_HIEGHT): draw_cell(x,y) y -= CELL_SIZE y += CELL_SIZE*BOARD_HIEGHT x += CELL_SIZE turtle.update()
def draw(self): for (ax, ay), (bx, by) in self.maze: turtle.up() turtle.setposition(ax, ay) turtle.down() turtle.setposition(bx, by) turtle.up() turtle.color("#00ffff") turtle.update()
def drawLine(turt, x1, y1, x2, y2): # draw line from point (x1, y1) to (x2, y2) turtle.tracer(0) # If this line is 0, each line will be drawn instantly turt.setheading(turt.towards(x1, y1)) turt.penup() turt.setpos(x1, y1) turt.setheading(turt.towards(x2, y2)) turt.pendown() turt.setpos(x2, y2) turtle.update() # Will be called unnecessarily if tracer is set to 1
def drawChord(t, update, animation, color): global currentHeading currentPoint = 1 t.setheading(0) currentHeading = 0 if animation: t.tracer(True) else: t.tracer(False) for i in pointsArray: if color == "random": r = lambda: random.randint(0,255) randColor = ('#%02X%02X%02X' % (r(),r(),r())) wheel.color(randColor) else: wheel.color(color) nextPoint = currentPoint*multiplier while True: if nextPoint <= pointsInt: break if nextPoint >= (pointsInt): nextPoint = nextPoint - pointsInt x = nextPoint-currentPoint angleMultiplier = differAngle*x chordLengthOne = (radiusInt**2+radiusInt**2-2*radiusInt*radiusInt*math.cos(math.radians(angleMultiplier))) # a = radius^2 + radius^2 - 2 * radius * radius * cosVinkel chordLengthOne = math.sqrt(chordLengthOne) t.setx(i[0]) t.sety(i[1]) nextPointHeading = t.towards(pointsArray[nextPoint-1][0], pointsArray[nextPoint-1][1]) t.setheading(nextPointHeading) t.setx(i[0]) t.sety(i[1]) if update: turtle.update() t.pendown() t.forward(chordLengthOne) t.penup() currentPoint = currentPoint + 1 if currentPoint > (pointsInt): break t.tracer(False)
def Game(): turtle.onkey(fire_tank_shot, "space") # Again, I plan on getting rid of all the global variables, but I'm new to python so I'm accepting these call blocks global death_index global tank_shot_state global invader_shot_two_dy global Vaderdx global invader_shot_one_state global invader_shot_one_dy global Score global invader_shot_two_state global game_pen global temphitcount global last_score global tank_dx global lives global life_three global life_two global life_one global level invader_kills = 0 death_list = [] landing = False isBreak = False temp_level = level initial_Vaderdx = Vaderdx while True: # To prevent the screen from refreshing after every turtle operation. turtle.tracer(False) # Loop for all invader functionality for k, invader in enumerate(invaders): x = invader.xcor() x += Vaderdx # Preventing dead invaders from moving left and right. for i in death_list: if i == k: x = invader.xcor() invader.setx(x) # Moving the invaders back and down after hitting a wall if (invader.xcor() > 230 and invader.xcor() < 250 and invader.ycor() < 250) or (invader.xcor() < -230 and invader.xcor() > -250 and invader.ycor() < 250): Vaderdx *= -1 for w, i in enumerate(invaders): y = i.ycor() y -= 10 # Preventing dead invaders from traveling down. for z in death_list: if z == w: y = i.ycor() i.sety(y) # Firing the invader projectiles q = random.randrange(10) if (invader.xcor() <= tank.xcor() + 70 and invader.xcor() >= tank.xcor() - 70) and islowest( invader.ycor(), invader.xcor()) and invader.xcor() > -250: fire_invader_shot_one(invader) elif q <= 2 and islowest(invader.ycor(), invader.xcor()) and invader.xcor() > -250: fire_invader_shot_two(invader) # Collision Detection for the player projectile and the invaders if isHit(tank_shot, invader): # Moving dead invaders off screen Score += 5 temphitcount += 1 invader_kills += 1 if temphitcount > 3: death_index -= 25 temphitcount = 1 if temphitcount == 1: invader.setposition(-320, death_index) if temphitcount == 2: invader.setposition(-295, death_index) if temphitcount == 3: invader.setposition(-270, death_index) # Removing turtles from their lists, turning them off #del invaders[k] # Instead I added the invaders to a death list, and checked, using enumerate, to prevent them from moving. death_list.append(k) # Reset the player projectile tank_shot_state = "ready" tank_shot.hideturtle() tank_shot.setposition(0, -400) # Increasing the horizontal speed of the invaders based on the number killed. if invader_kills == 20: Vaderdx *= 1 if invader_kills == 42: Vaderdx *= 1 if invader_kills == 49: Vaderdx *= 1.5 if invader_kills == 52: Vaderdx *= 1.25 if invader_kills == 53: Vaderdx *= 1.25 if invader_kills == 54: Vaderdx *= 1.5 if invader_kills == 55: global first_level first_level = False level += 1 if level > 3: level = 1 if lives < 3: lives += 1 isBreak = True break # Hit detection for the invaders landing, or for a player/invader collision, GAME OVER if (isHit(tank, invader) or invader.ycor() < -220) and landing == False: landing = True Vaderdx = 0 isBreak = True break # Collision detection for the invader projectile hits on the player if isHit3(tank, invader_shot_two): # Reseting the projectile invader_shot_two_state = "ready" invader_shot_two.sety(700) invader_shot_two.hideturtle() # Death animation x = tank.xcor() y = tank.ycor() turtle.tracer(True) vdx = Vaderdx Vaderdx = 0 invader_shot_one_dy = 0 invader_shot_two_dy = 0 tank_dx = 0 game_pen.penup() game_pen.setposition(x, y) game_pen.speed(1) game_pen.color("black") flash(game_pen) lives -= 1 if lives == 2: tank.clearstamp(life_three) elif lives == 1: tank.clearstamp(life_two) elif lives == 0: tank.clearstamp(life_one) Vaderdx = vdx invader_shot_one_dy = -1 invader_shot_two_dy = -1 tank_dx = 16 turtle.tracer(False) if isHit3(tank, invader_shot_one): # Reseting the projectile invader_shot_one_state = "ready" invader_shot_one.sety(700) invader_shot_one.hideturtle() # Death animation x = tank.xcor() y = tank.ycor() turtle.tracer(True) vdx = Vaderdx Vaderdx = 0 invader_shot_one_dy = 0 invader_shot_two_dy = 0 tank_dx = 0 game_pen.penup() game_pen.setposition(x, y) game_pen.speed(1) game_pen.color("black") flash(game_pen) lives -= 1 if lives == 2: tank.clearstamp(life_three) elif lives == 1: tank.clearstamp(life_two) elif lives == 0: tank.clearstamp(life_one) Vaderdx = vdx invader_shot_one_dy = -1 invader_shot_two_dy = -1 tank_dx = 16 turtle.tracer(False) # Collision detection for opposing projectiles if isHit2(tank_shot, invader_shot_one): tank_shot_state = "ready" invader_shot_one_state = "ready" tank_shot.hideturtle() invader_shot_one.hideturtle() tank_shot.sety(-400) invader_shot_one.sety(400) if isHit2(tank_shot, invader_shot_two): tank_shot_state = "ready" invader_shot_two_state = "ready" tank_shot.hideturtle() invader_shot_two.hideturtle() tank_shot.sety(-400) invader_shot_two.sety(400) if isBreak or lives == -1: death_list.clear() Vaderdx = initial_Vaderdx ReDrawGame(temp_level) break # Projectile Motion if tank_shot_state == "fire": y = tank_shot.ycor() y += tank_shot_dy tank_shot.sety(y) if tank_shot.ycor() > 220: tank_shot_state = "ready" tank_shot.hideturtle() if invader_shot_one_state == "fire": y = invader_shot_one.ycor() y += invader_shot_one_dy invader_shot_one.sety(y) if invader_shot_one.ycor() < -220: invader_shot_one_state = "ready" invader_shot_one.sety(-400) invader_shot_one.hideturtle() if invader_shot_two_state == "fire": y = invader_shot_two.ycor() y += invader_shot_two_dy invader_shot_two.sety(y) if invader_shot_two.ycor() < -220: invader_shot_two_state = "ready" invader_shot_two.sety(-400) invader_shot_two.hideturtle() if Score > last_score: updateScore() last_score = Score # To refresh the screen at the end of each loop. turtle.update()
import turtle import random # Draws a burst of straight rays, uses a nested loop to make small # scribbles at the end of each ray turtle.tracer(0, 0) wn = turtle.Screen() wn.colormode(255) turtle.bgcolor("black") alex = turtle.Turtle() alex.speed(10) alex.goto(0, 0) alex.pensize(0) alex.ht() for i in range(400): alex.color(random.randrange(256), random.randrange(256), random.randrange(256)) alex.goto(round(random.gauss(0, 100), 0), round(random.gauss(0, 100), 0)) x = alex.xcor() y = alex.ycor() for j in range(25): s = round(random.gauss(0, 5), 0) t = round(random.gauss(0, 5), 0) alex.color(random.randrange(256), random.randrange(256), random.randrange(256)) alex.pensize(0) alex.goto(x + s, y + t) alex.goto(s, t) turtle.update() wn.exitonclick()
def update_screen(self): while time.time() < self.time + (1.0 / self.FPS): pass turtle.update() self.time = time.time()
appelle niter fois regleKoch pour créer la courbe de Koch """ courbe = motifInitial # on part du motif initial donné par l'utilisateur en paramètres for i in range(niter): nouveauMotif = regleKoch( courbe) # on trouve le nouveau Motif à partir du motif de départ courbe = nouveauMotif # on dit que le nouveau Motif est maintenant le motif de départ return courbe #courbe = courbeKoch('F',3) #dessiner(courbe,50, 60) def triangle(motifInitial, niter): courbe = courbeKoch(motifInitial, niter) carre = '' for _ in range(3): triangle += courbe triangle += '--' return triangle longueur = 2 angle = 60 niter = 6 dessiner(courbeKoch('F-G-G', 3), 40, 120) turtle.update() # accélération du tracé turtle.exitonclick() # permet la fermeture de la fenêtre graphique
def draw(self, exp_rate=None): turtle.tracer(0, 0) self.__draw_dungeon() self.__draw_agent(exp_rate) turtle.update() turtle.clearscreen()
def drawGrid(): """ Sig: NoneType -> NoneType Call grid and draw the 9x9 grid in turtle. Print out all the instructions. """ # Turn turlte animation off an set delay for update drawings. turtle.tracer(0, 0) # Make the turtle invisible and speed up the drawing. turtle.hideturtle() turtle.clear() turtle.setup(700, 580) turtle.penup() turtle.goto(-135, -135) turtle.pendown() # Call grid. grid(n, length) # Print instructions for the game. turtle.penup() turtle.goto(-80, 215) turtle.color("black") turtle.write("SUDOKU", True, font=("New York", 40, "bold")) turtle.goto(-200, 190) turtle.color("#255359") turtle.write("Click on empty squares and enter digits 1 to 9!", True, font=("Lucida Sans Unicode", 17, "bold")) turtle.goto(-200, 172) turtle.color("#0089A7") turtle.write("- You have a total of 20 minutes", True, font=("Lucida Sans Unicode", 15, "normal")) turtle.goto(-230, -170) turtle.write("Instructions:", True, font=("Lucida Sans Unicode", 15, "bold")) turtle.goto(-230, -188) turtle.color("#255359") turtle.write( "1. Fill the grid so that each column, each row, and each of the nine", True, font=("Lucida Sans Unicode", 15, "normal")) turtle.goto(-212, -205) turtle.write("3x3 boxes contains digits from 1 to 9.", True, font=("Lucida Sans Unicode", 15, "normal")) turtle.goto(-230, -222) turtle.write( "2. To rewrite a square, just reclick on the square and enter the new", True, font=("Lucida Sans Unicode", 15, "normal")) turtle.goto(-212, -239) turtle.write("digit you wish to add.", True, font=("Lucida Sans Unicode", 15, "normal")) turtle.goto(170, 77) turtle.color("#AB3B3A") turtle.write("Click and ", True, font=("New York", 17, "normal")) turtle.goto(170, 60) turtle.write("press space", True, font=("New York", 17, "normal")) turtle.goto(170, 42) turtle.write("for hints!", True, font=("New York", 17, "normal")) # Draw a box for hints instruction. turtle.goto(163, 100) turtle.color("#AB3B3A") turtle.pendown() turtle.left(90) for l in range(2): turtle.forward(60) turtle.left(90) turtle.forward(86) turtle.left(90) turtle.update()
def test(filepath): import turtle window_width = 1600 window_height = 1200 turtle.setup(window_width, window_height) wn = turtle.Screen() # Get a reference to the window wn.title("spatial hash") # Change the window title ctx = turtle.Turtle() # Create our favorite turtle ctx.speed(0) turtle.tracer(0, 0) state = {"zoom": 0.25} def draw_line(start, end): ctx.penup() ctx.goto(start.x * state["zoom"], start.y * state["zoom"]) ctx.pendown() ctx.goto(end.x * state["zoom"], end.y * state["zoom"]) ctx.penup() with open(filepath) as json_file: triangles = json.load(json_file) # triangles = [triangles[64]] sh = create_spatial_hash(triangles, 120) bucket_sizes = [len(bucket) for bucket in sh.buckets if bucket is not None] print(sh) print( "minBucket", min(bucket_sizes), "maxBucket", max(bucket_sizes), "avgBucket", sum(bucket_sizes) / len(bucket_sizes), ) def vert_to_vec2d(vert): # x,-z to x,y return Vec2d(x=vert[0], y=-vert[2]) def draw_triangle(tri): edges = [ [tri[0], tri[1]], [tri[1], tri[2]], [tri[2], tri[0]], ] for edge in edges: draw_line(vert_to_vec2d(edge[0]), vert_to_vec2d(edge[1])) def draw_triangles(): for tri in triangles: draw_triangle(tri) def randcolor(): return random.randint(0, 255) def rectangle(x, y, width, height): ctx.penup() ctx.begin_fill() ctx.goto(x * state["zoom"], y * state["zoom"]) ctx.pendown() ctx.goto((x + width) * state["zoom"], y * state["zoom"]) ctx.goto((x + width) * state["zoom"], (y + height) * state["zoom"]) ctx.goto(x * state["zoom"], (y + height) * state["zoom"]) ctx.goto(x * state["zoom"], y * state["zoom"]) ctx.end_fill() ctx.penup() def highlight_bucket(x, y): render() print("highlight_bucket", x, y) gridX = int(sh.unitsToGrid(x / state["zoom"])) gridY = int(sh.unitsToGrid(y / state["zoom"])) print("gridX, gridY", gridX, gridY) bucket_index = sh.get_bucket_index(gridX, gridY) print("bucket_index", bucket_index) bucket = sh.buckets[bucket_index] ctx.fillcolor("blue") ctx.pensize(3) rectangle( sh.gridToUnits(gridX), sh.gridToUnits(gridY), sh.cell_width, sh.cell_width, ) turtle.colormode(255) if bucket: for tri_index in bucket: ctx.pencolor((randcolor(), randcolor(), randcolor())) draw_triangle(triangles[tri_index]) ctx.pencolor("black") for tri_index in bucket: draw_label(triangles[tri_index], tri_index) ctx.goto(window_width / 2 - 130, window_height / 2 - 30) style = ("Courier", 20) ctx.write("x=%d y=%d" % (gridX, gridY), font=style, align="center") turtle.update() def draw_grid(): half_width = window_width / 2 half_height = window_height / 2 top = -half_height / state["zoom"] bottom = half_height / state["zoom"] left = -half_width / state["zoom"] right = half_width / state["zoom"] for gridX in range( sh.unitsToGrid(left), sh.unitsToGrid(right), ): draw_line( Vec2d(x=sh.gridToUnits(gridX), y=top), Vec2d(x=sh.gridToUnits(gridX), y=bottom), ) for gridY in range( sh.unitsToGrid(top), sh.unitsToGrid(bottom), ): draw_line( Vec2d(y=sh.gridToUnits(gridY), x=left), Vec2d(y=sh.gridToUnits(gridY), x=right), ) def triangle_center(tri): return tri[0].add(tri[1]).add(tri[2]).divScalar(3) def draw_label(tri, tri_index): center = triangle_center([vert_to_vec2d(vert) for vert in tri]) ctx.penup() ctx.goto(center.x * state["zoom"], center.y * state["zoom"]) style = ("Lucida Grande", 11) ctx.write(str(tri_index), font=style, align="center") def zoomIn(): state["zoom"] *= 2 render() def zoomOut(): state["zoom"] /= 2 render() def render(): ctx.clear() ctx.pensize(1) ctx.pencolor("lightgrey") draw_grid() ctx.pencolor("black") draw_triangles() turtle.update() render() wn.listen() wn.onclick(highlight_bucket) wn.onkey(zoomIn, "e") wn.onkey(zoomOut, "q") wn.mainloop() # This will make sure the program continues to run
def move_ring(PP, QQ): if PP == "A": x = -250 P = A elif PP == "B": x = 0 P = B else: x = 250 P = C if QQ == "A": x2 = -250 Q = A elif QQ == "B": x2 = 0 Q = B else: x2 = 250 Q = C for extra in range(1, 250 - (-95 + ring_height * (len(P) - 1)), animation_step): T[P[len(P) - 1]].clear() draw_single_ring(P[len(P) - 1], x, len(P) - 1, extra) turtle.update() T[P[len(P) - 1]].clear() draw_single_ring(P[len(P) - 1], x, len(P) - 1, extra) turtle.update() tp = x if x2 > x: step = animation_step else: step = -animation_step for tp in range(x, x2, step): T[P[len(P) - 1]].clear() draw_single_ring(P[len(P) - 1], tp, len(P) - 1, extra) turtle.update() T[P[len(P) - 1]].clear() draw_single_ring(P[len(P) - 1], x2, len(P) - 1, extra) turtle.update() Q.append(P[len(P) - 1]) del P[-1] for extra in range(250 - (-95 + ring_height * (len(Q) - 1)), 0, -animation_step): T[Q[len(Q) - 1]].clear() draw_single_ring(Q[len(Q) - 1], x2, len(Q) - 1, extra) turtle.update() T[Q[len(Q) - 1]].clear() draw_single_ring(Q[len(Q) - 1], x2, len(Q) - 1) turtle.update() return
def circle(self, center, radius): center = self.coordConversion(center) self.move([center[0], center[1] - radius]) tl.circle(radius) tl.update()
rating = 0 tt.tracer(False) tt.hideturtle() while True: tt.penup() tt.clear() tt.goto(0, 0) tt.pendown() tt.seth(heading) #drawHelix(144, heading) # 转动五角星 drawHelix(240, rating) tt.update() #time.sleep(0.001) heading += velocity rating += 0.4 if __name__ == '__main__': tt.setup(0.5, 0.8, 0, 0) tt.speed(0) tt.bgcolor("green") tt.penup() tt.goto(0, 0) tt.pendown() tt.tracer() drawGalaxy2() #drawHelix(89, 0.5) #animateHelix(1) tt.update() tt.done()
def draw(): """ To draw all tiles. """ for mark in tiles: square(mark, tiles[mark]) t.update()
def __exit__(self, exc_type, exc_value, traceback): update() tracer(self.n, self.delay)
import turtle toplevel = 6 # 一共递归6层 angle = 30 def drawTree(length, level): turtle.left(angle) # 绘制左枝 turtle.forward(length) if level < toplevel: # 在左枝退回去之前递归 drawTree(length - 10, level + 1) turtle.back(length) turtle.right(angle * 2) # 绘制右枝 turtle.forward(length) if level < toplevel: # 在右枝退回去之前递归 drawTree(length - 10, level + 1) turtle.back(length) turtle.left(angle) turtle.speed(1) turtle.tracer(0) # 不刷新 turtle.left(90) drawTree(80, 1) turtle.update() # 刷新,和上面的tracer(0)配合,直接出图形,忽略过程 turtle.done()
def playGame(gameState, algo): '''Game Play with the algo for AI given as input by the user''' while (True): global r1 global r2 global r3 global r4 global r5 global r6 global r7 global r8 global r9 global r10 global r11 global r12 global averageTimeAlphaBeta global timeMinimax global alphaBetaNodes global sizeOfAlphaBetaNode global timeAlphaBeta global analysisFlag global restartFlag global exitFlag global humanMoveFlag global humanMove # AI's Turn to play the move bestMove = findMove(gameState, algo) gameState = successor(gameState, bestMove) row = findRow(gameState.board, bestMove) if (row != -1): gui.placeCoin(row, bestMove, gameState.typeOfNode) if (checkEnded(gameState)): '''If game has ended update data for analysis''' if (algo == 1): r1 = getNoOfNodes() r2 = sys.getsizeof(gameState) r3 = 16 r4 = time() - timeMinimax r5 = float(r1) / (r4 * 1000000) r9 = ((r1 * r2), (alphaBetaNodes * sizeOfAlphaBetaNode)) r10 += float(r4) / 10 elif (algo == 2): r6 = getNoOfNodes() if (r1 != 0): r7 = float(r1 - r6) / r1 r8 = time() - timeAlphaBeta alphaBetaNodes = getNoOfNodes() sizeOfAlphaBetaNode = sys.getsizeof(gameState) r9 = ((r1 * r2), (alphaBetaNodes * sizeOfAlphaBetaNode)) r10 += float(r8) / 10 r11 += 1 r12 = float(r11) / 20 t.onscreenclick(setAnalysisRestartExitFlag) while (analysisFlag == 0 and exitFlag == 0 and restartFlag == 0): # Waits for User to click Analysis Button or Restart Button or Exit Button t.update() if (analysisFlag == 1): # Actions to be taken if Analysis button is clicked gui.showAnalysis(R1=r1, R2=r2, R3=r3, R4=r4, R5=r5, R6=r6, R7=r7, R8=r8, R9=r9, R10=r10, R11=r11, R12=r12) analysisFlag = 0 else: if (exitFlag == 1): # Actions to be taken if EXIT Button was clicked exitFlag = 0 exit() elif (restartFlag == 1): # Actions to be taken if Restart Button was clicked restartFlag = 0 main() t.onscreenclick(setRestartExitFlag) while (restartFlag == 0 and exitFlag == 0): # Waits for user to click Restart Button or EXIT Button t.update() if (exitFlag == 1): # Actions to be taken if EXIT Button was clicked exitFlag = 0 exit() elif (restartFlag == 1): # Actions to be taken if Restart Button was clicked restartFlag = 0 main() # USER's Turn to Play the move while (True): while (humanMove is None): t.onscreenclick(setHumanMove) while (humanMoveFlag == 0): # Waits for User to select a column t.update() humanMoveFlag = 0 tempState = successor(gameState, humanMove) if (tempState is False): '''If User selects an invalid column then successor function returns False instead of the Child. This process continues until the User selects a valid column''' humanMove = None continue else: decrementNoOfNodes() gameState = tempState row = findRow(gameState.board, humanMove) gui.placeCoin(row, humanMove, gameState.typeOfNode) break humanMove = None if (checkEnded(gameState)): '''If game has ended update data for analysis''' if (algo == 1): r1 = getNoOfNodes() r2 = sys.getsizeof(gameState) r3 = 16 r4 = time() - timeMinimax r5 = float(r1) / (r4 * 1000000) r9 = ((r1 * r2), (alphaBetaNodes * sizeOfAlphaBetaNode)) r10 += float(r4) / 10 elif (algo == 2): r6 = getNoOfNodes() if (r1 != 0): r7 = float(r1 - r6) / r1 r8 = time() - timeAlphaBeta alphaBetaNodes = getNoOfNodes() sizeOfAlphaBetaNode = sys.getsizeof(gameState) r9 = ((r1 * r2), (alphaBetaNodes * sizeOfAlphaBetaNode)) r10 += float(r8) / 10 # r9 = r1/r6 r11 += 1 r12 = float(r11) / 20 t.onscreenclick(setAnalysisRestartExitFlag) while (analysisFlag == 0 and exitFlag == 0 and restartFlag == 0): # Waits for User to click Analysis Button or Restart Button or Exit Button t.update() if (analysisFlag == 1): # Actions to be taken if Analysis button is clicked gui.showAnalysis(R1=r1, R2=r2, R3=r3, R4=r4, R5=r5, R6=r6, R7=r7, R8=r8, R9=r9, R10=r10, R11=r11, R12=r12) analysisFlag = 0 else: if (exitFlag == 1): # Actions to be taken if EXIT Button was clicked exitFlag = 0 exit() elif (restartFlag == 1): # Actions to be taken if Restart Button was clicked restartFlag = 0 main() t.onscreenclick(setRestartExitFlag) while (restartFlag == 0 and exitFlag == 0): # Waits for user to click Restart Button or EXIT Button t.update() if (exitFlag == 1): # Actions to be taken if EXIT Button was clicked exitFlag = 0 exit() elif (restartFlag == 1): # Actions to be taken if Restart Button was clicked restartFlag = 0 main()
def frame(): """ signature: () -> NoneType Given the current state of the game in the global variables, draw all visual elements on the screen: the paddles, the ball, and the current score. Please note that this is your only function where drawing should happen (i.e. the only function where you call functions in the turtle module). Other functions in this program merely update the state of global variables. This function also should not modify any global variables. Hint: write this function first! """ global tamx, tamy, foodx, foody, waterx, watery, lovex, lovey, lose # Panel turtle.bgcolor("darkslategray1") turtle.color("cornsilk1") turtle.penup() turtle.goto(window_width*.25, window_height*.25) turtle.setheading(0) turtle.pendown() turtle.begin_fill() i=0 while i<2: turtle.forward(100) turtle.right(90) turtle.forward(200) turtle.right(90) i+=1 turtle.end_fill() turtle.penup() meter(0, foodpoints, "FOOD") meter(-75, waterpoints, "WATER") meter(-150, lovepoints, "LOVE") # Widget Food turtle.goto(foodx, foody) turtle.color("darkolivegreen") turtle.write("FOOD") turtle.penup() #Widget Water turtle.goto(waterx, watery) turtle.color("darkolivegreen") turtle.write("WATER") turtle.penup() #Widget Love turtle.goto(lovex, lovey) turtle.color("darkolivegreen") turtle.write("LOVE") turtle.penup() #Money turtle.goto(window_width*-.4, window_height*-.4) turtle.pendown() turtle.begin_fill() turtle.color("gold") turtle.circle(20) turtle.end_fill() turtle.color("black") turtle.penup() turtle.goto(window_width*-.407, window_height*-.3985) turtle.write("$", font=("Arial",20, "normal")) turtle.penup() turtle.goto(window_width*-.35, window_height*-.40) turtle.write("= "+str(money), font=("Arial", 25, "normal")) #Pet if tamx>=window_width*.1: tamx-=random.randint(0,15) if tamx<=window_width*-.3: tamx+=random.randint(0,15) if tamy>=window_height*.08: tamy-=random.randint(0,15) if tamy<=window_height*-.08: tamy+=random.randint(0,15) else: tamx += random.randint(-30,30) tamy += random.randint(-30,30) turtle.penup() turtle.goto(window_width*.26,0) turtle.pendown() turtle.color("pink") turtle.write(pet_name,font = ("Arial",16, "normal")) turtle.up() turtle.goto(tamx,tamy) turtle.down() turtle.color(pet_color) turtle.circle(35) turtle.up() turtle.forward(20) turtle.left(90) turtle.forward(30) turtle.down() turtle.begin_fill() turtle.circle(5) turtle.up() turtle.left(80) turtle.forward(30) turtle.down() turtle.circle(5) turtle.end_fill() turtle.up() college() poop() turtle.update()
def create(): import turtle import random size_of_matrix = 200 maxdistance = 0 turtle.getscreen() particles = int(turtle.textinput('Particle count', 'How Many Particles?')) R = 0 #Cluster Radius particle_count = 0 #this iterates through the number of particles entered by textinput origin = size_of_matrix / 2 #a variable to designate the origin turtle.setworldcoordinates(0, 0, (199), (199)) p1 = turtle.Turtle() p1.penup() p1.speed(0) p1.goto(origin, origin) p1.hideturtle() p1.dot(5) #the initial 'seed' A = [[[] for i in range(200)] for j in range(200)] #create the matrix for i in range(200): for j in range(200): number = 0 A[i][j] = number A[(199) - int(origin)][int( origin)] = True #designate the origin as "True" in the matrix #I set the matrix to look like the turtle display, so the Y axis is inverted while particle_count < particles: #create particles t = turtle.Turtle() t.speed(0) t.penup() x = random.randint( origin - (R + 1), origin + (R + 1)) #get two numbers that are within the the cluster radius y = random.randint(origin - (R + 1), origin + (R + 1)) x1 = ((origin - x)**2) y1 = ((origin - y)**2) turtle.tracer( False ) #hide the turtle and turn off the screen updates, which speeds up the program t.hideturtle() if round( (x1 + y1)**(.5) ) == R + 1: #i just used the pythagorean theroem to determine if the randomly selected x and y values are at location 'R+1' #if not, the program just picks two new variables. random_walk = 0 while random_walk < 200: neighbor = hasNeighbor( A, x, y ) #checks to see if the surrounding spots in the matrix are True if neighbor == True: #If they are occupied random_walk = 200 #ends the while loop A[(199) - y][x] = True #sets that location to True t.goto(x, y) turtle.colormode(255) #some fun color stuff if R <= 24: t.pencolor(255, 14 + 10 * R, 0) if 24 < R < 51: t.pencolor(279 - 5 * R, 255, 0) if 51 <= R < 99: t.pencolor(0, 255, -52 + R) t.dot(5) if abs( origin - x ) > maxdistance: #updates R if the distance from the new particle is greater than the previous farthest one maxdistance = abs(origin - x) R = R + 1 if abs(origin - y) > maxdistance: maxdistance = abs(origin - y) R = R + 1 particle_count += 1 #the particle counter increments only if the the particle sticks turtle.update() else: direction = random.randint( 1, 4 ) #if not, a random direction is chosen and a step is taken if direction == 1: #and the x and y values checked reflect it y = y + 1 if direction == 2: x = x + 1 if direction == 3: y = y - 1 if direction == 4: x = x - 1 random_walk += 1 #The random walk counter increments until 200 t.hideturtle() turtle.update()
curveto_r(4, 14, 18, 24, 22, -3) te.pensize(2) line(240.5, 207.5, 227.5, 211.5) line(245.5, 209.5, 227.5, 214.5) line(247.5, 211.5, 227.5, 217.5) line(247.5, 214.5, 229.5, 220.5) line(247.5, 218.5, 230.5, 223.5) line(246.5, 222.5, 232.5, 226.5) line(244.5, 225.5, 234.5, 228.5) line(377.5, 207.5, 367.5, 210.5) line(384.5, 207.5, 366.5, 212.5) line(385.5, 210.5, 366.5, 215.5) line(384.5, 213.5, 366.5, 218.5) line(384.5, 215.5, 367.5, 220.5) line(384.5, 218.5, 368.5, 223.5) # line(383.5,220.5,368.5,225.5) line(382.5, 223.5, 370.5, 227.5) # line(381.5,226.5,373.5,229.5) # 图层_20 te.pencolor("black") Moveto(309, 270) # 鼻子、嘴 curveto_r(0, 0, 4, 7, 1, 9) line(296.5, 307.5, 303.5, 307.5) Moveto(315, 307) smooth_r(10, -1, 10, 2) te.penup() te.hideturtle() te.update() te.done()
def show_maze(self): turtle.setworldcoordinates(0, 0, self.width, self.height) wally = turtle.Turtle() wally.speed(0) wally.width(1.5) wally.hideturtle() turtle.tracer(0, 0) #print('heer') for i in range(self.num_rows): for j in range(self.num_cols): permissibilities = self.permissibilities(cell=(i, j)) turtle.up() wally.setposition((j * self.grid_width, i * self.grid_height)) # Set turtle heading orientation # 0 - east, 90 - north, 180 - west, 270 - south wally.setheading(0) if not permissibilities[0]: wally.down() else: wally.up() wally.pencolor('black') if (i == 3 and (j == 21 or j == 20)): wally.pencolor('yellow') if (i == 0 and (j == 6 or j == 7)): wally.pencolor('yellow') wally.forward(self.grid_width) wally.setheading(90) wally.up() if not permissibilities[1]: wally.down() else: wally.up() wally.pencolor('black') if ((i == 11 or i == 12) and j == 26): wally.pencolor('yellow') wally.forward(self.grid_height) wally.setheading(180) wally.up() if not permissibilities[2]: wally.down() else: wally.up() wally.pencolor('black') if (i == 32 and (j == 25 or j == 26)): wally.pencolor('yellow') if (i == 2 and (j == 21 or j == 20)): wally.pencolor('yellow') wally.forward(self.grid_width) wally.setheading(270) wally.up() if not permissibilities[3]: wally.down() else: wally.up() wally.pencolor('black') if ((i == 25 or i == 26) and j == 0): wally.pencolor('yellow') wally.forward(self.grid_height) wally.up() turtle.update()
def drawGrid(self): turtle.clear() for i in range(self.width): for j in range(self.height): self.draw(i, j) turtle.update()
import rainbow as rb def drawRing(accuracy, width): hue = 0.0 tt.pensize(width+1) for i in range(20): radius = 300-i*width # 每次画圆的半径都减小width个象素, for j in range(int(360/accuracy)): hue += accuracy RGB = rb.HSB2RGB(hue, 1.0, 1.0) #print(str(hue)+"->"+str(RGB)) tt.color(RGB[0], RGB[1], RGB[2]) tt.circle(radius, accuracy) tt.penup() x,y=tt.pos() tt.sety(y+width) # 画下一个圆时上移 width 象素 tt.pendown() if __name__ == '__main__': tt.screensize(400, 300) tt.speed(0) # 作图速度 0-10, 10最快,0不限速 tt.delay(0) # 内部延迟, 置0可以加速 tt.hideturtle() tt.tracer(True) # 作图过程(轨迹)不显示 tt.penup() tt.setpos(0,-300) tt.pendown() drawRing(1,10) # 第一参数色环精度, 第二参数色环宽度 tt.update() # 刷新画面 tt.done()
p.pd() def entpent(n): a = bok / (n * 9) bok2 = bok / n p.pu() p.rt(90) p.fd(bok / 2) p.rt(90) p.fd(bok / 2) p.lt(180) p.pd() for i in range(n): for m in range(n): pentlik(a, bok2) p.pu() p.fd(bok2) p.pd() p.pu() p.bk(n * bok2) p.lt(90) p.fd(bok2) p.rt(90) p.pd() tracer(0) entpent(3) update() mainloop()
def draw(): for mark in tiles: square(mark, tiles[mark]) t.update()
import turtle as tu import time tu.tracer(0) tu.circle(90) tu.penup() tu.sety(90) tu.pendown() tu.dot() tu.setheading(90) for i in range(60): tu.forward(90) time.sleep(0.5) #tu.undo() tu.setposition(0, 90) tu.right(6) tu.update() tu.done()
def turtle_interpretation(instructions, delta = 90, initialAngle = 90, distance = 1, width = 1): """Interprets a list of modules as a set of instructions for a turtle to draw a tree. """ ############ INITIALIZATION ############# turtle.TurtleScreen._RUNNING = True turtle.tracer(0,0) #only display the result turtle.setup(1000,1000) #make the result a square with 1:1 ratios turtle.down() #set the pen to drawing ("pen up" vs. "pen down") turtle.mode("world") turtle.setheading(initialAngle) turtle.width(width) turtleXmax = 0 turtleXmin = 0 turtleYmax = 0 turtleYmin = 0 turtlePosStack = [] turtleHeadStack = [] ######### MAIN FUNCTION ############## for mod in instructions: if mod.symbol[0] == "F": if mod.param == []: turtle.forward(distance) else: turtle.forward(float(mod.param[0])) elif mod.symbol == "f": turtle.up() if mod.param == []: turtle.forward(distance) else: turtle.forward(float(mod.param[0])) turtle.down() elif mod.symbol == "+": if mod.param == []: turtle.left(delta) else: turtle.left(mod.param[0]) elif mod.symbol == "-": if mod.param == []: turtle.right(delta) else: turtle.right(mod.param[0]) elif mod.symbol == "[": turtlePosStack.insert(0,turtle.pos()) turtleHeadStack.insert(0,turtle.heading()) elif mod.symbol == "]": turtle.up() turtle.goto(turtlePosStack.pop(0)) turtle.setheading(turtleHeadStack.pop(0)) turtle.down() turtleXmax = max(turtleXmax, turtle.xcor()) turtleXmin = min(turtleXmin, turtle.xcor()) turtleYmax = max(turtleYmax, turtle.ycor()) turtleYmin = min(turtleYmin, turtle.ycor()) # update screen and display size turtle.hideturtle() turtle.update() # make sure the ratio of the picture is 1:1 if (turtleXmax-turtleXmin) > (turtleYmax-turtleYmin): turtleYmax = turtleYmin + (turtleXmax-turtleXmin) else: turtleXmax = turtleXmin + (turtleYmax-turtleYmin) margin = (turtleYmax-turtleYmin)*0.02 #margin is always 2 percent of picture width turtle.setworldcoordinates(turtleXmin-margin, turtleYmin-margin, turtleXmax+margin, turtleYmax+margin) ####### CLEANUP ########### # print("Press a key to continue:") # input() # turtle.bye() turtle.exitonclick() return 0
def line(self, startCoords, endCoords): self.move(startCoords) tl.goto(endCoords[0], endCoords[1]) tl.update()
def play_reaction(): global player global additions global good, bad global RUNNING global win global players headline1 = turtle.clone() turtle.hideturtle() headline1.hideturtle() headline1.penup() headline1.goto(0, 350) headline1.color("black") headline1.write("REACTION - press ONLY when there is a panda!", align="center", font=("Comic Sans MS", 50, "bold")) class player(Turtle): def __init__(self, color, x, y, condition, index): Turtle.__init__(self) self.penup() self.color(color) self.shape('square') self.speed(0) self.goto(x, y) self.index = index self.shapesize(1) self.condition = condition def press(self): global RUNNING for i in players: if (i.condition == 2): return 0 if win == 1 and self.condition != 1: self.shapesize(2) self.sety(-110) self.condition = 2 additions[self.index] += 25 RUNNING = False else: self.color('black') self.condition = 1 good = turtle.Turtle() bad = turtle.Turtle() TURTLES = [good, bad] for i in TURTLES: i.hideturtle() i.goto(0, 0) i.left(90) turtle.shape("triangle") i.shapesize(10) if i == bad: i.shape("snake.gif") else: i.shape('uri.gif') RUNNING = True player_1 = player('red', -150, -125, 0, 0) player_2 = player('blue', -50, -125, 0, 1) player_3 = player('yellow', 50, -125, 0, 2) player_4 = player('green', 150, -125, 0, 3) players = [player_1, player_2, player_3, player_4] turtle.onkeypress(player_1.press, 'q') turtle.onkeypress(player_2.press, 'c') turtle.onkeypress(player_3.press, 'm') turtle.onkeypress(player_4.press, 'p') turtle.listen() win = 0 start = time.time() + random.randint(3, 5) while RUNNING: turtle.update() if time.time() > start: RUNNING = False #time.sleep(random.randint(5, 8)) while random.randint(0, 1): RUNNING = True win = 0 bad.showturtle() start = time.time() + 4 while RUNNING: turtle.update() if time.time() > start: RUNNING = False bad.hideturtle() RUNNING = True start = random.randint(3, 5) + time.time() while RUNNING: turtle.update() if time.time() > start: RUNNING = False win = 0 win = 1 bad.hideturtle() good.showturtle() #wait random time RUNNING = True start = time.time() + 4 while RUNNING: turtle.update() if time.time() > start: RUNNING = False
def show_splash(self): turtle.bgpic("my-splash-screen.gif") turtle.update() time.sleep(6) turtle.bgpic("newbackground.gif") self.state = "setup"
import turtle as t import time t.hideturtle(); t.tracer(False) while True: now = time.localtime() time_str = "%02d:%02d:%02d" % (now.tm_hour, now.tm_min, now.tm_sec) t.clear() t.write(time_str, align="center", font=("Arial", 100, "normal")) t.update() time.sleep(0.1)
turtle.right(120) turtle.forward(BASE_SIZE) # Draw second side. turtle.right(120) turtle.forward(BASE_SIZE) # Draw third side. def drawSierpinski(x, y, level, color): if level == 0: # The base case, where triangles are too small to draw more. drawTriangle(x, y, color) drawTriangle(x + (BASE_SIZE * 0.5), y + BASE_HEIGHT, color) drawTriangle(x + BASE_SIZE, y, color) else: # The recursive case, where three more triangles are drawn. drawSierpinski(x, y, level - 1, color) drawSierpinski(x + (BASE_SIZE * 0.5 * (2**level)), y + (BASE_HEIGHT * (2**level)), level - 1, color) drawSierpinski(x + (BASE_SIZE * (2**level)), y, level - 1, color) # Loop from 5 to 0, drawing 5 levels of triangles with different colors: for i in range(5, -1, -1): red = 1 - (0.2 * i) green = 0.1 * i blue = 0.1 * i drawSierpinski(START_X, START_Y, i, (red, green, blue)) turtle.hideturtle() turtle.update() # Finish drawing the screen. turtle.exitonclick() # When user clicks on the window, close it.
def play(): global running running = True while running == True: screen_width = turtle.getcanvas().winfo_width() / 2 screen_height = turtle.getcanvas().winfo_height() / 2 movearound() move_all_balls() check_all_balls_collision() turtle.update() time.sleep(.1) if my_ball.r >= 150: turtle.color('blue') turtle.write('you won!', move=False, align='center', font=('Ariel', 60, 'normal')) running == False break if Collide(my_ball, ball) and my_ball.r < ball.r: turtle.color('red') turtle.write('you failed!', move=False, align='center', font=('Ariel', 60, 'normal')) running == False break if ball.r >= 150: turtle.color('red') turtle.write('you failed!', move=False, align='center', font=('Ariel', 60, 'normal')) running == False break answer = input('would you like to restart?') if answer == 'yes': running = True for i in BALLS: x = random.randint(-screen_width + maximum_ball_radius, screen_width - maximum_ball_radius) y = random.randint(-screen_height + maximum_ball_radius, screen_height - maximum_ball_radius) dx = random.randint(minimum_ball_dx, maximum_ball_dx) while (dx == 0): dx = random.randint(minimum_ball_dx, maximum_ball_dx) dy = random.randint(minimum_ball_dy, maximum_ball_dy) while (dy == 0): dy = random.randint(minimum_ball_dy, maximum_ball_dy) r = random.randint(minimum_ball_radius, maximum_ball_radius) color = (random.random(), random.random(), random.random()) i.new_ball(x, y, dx, dy, r, color) my_ball.new_ball(x, y, dx, dy, r, color) turtle.clear() play() else: quit()