I'm trying to achieve the pattern below.
Got as far as doing the first line, then I have no clue how to code the rest of the pattern.
Here's what I've done so far:
#Timothy Shek
from graphics import*
#open Graph Window
def main():
win = GraphWin("Example",100,100)
x = 7
y = 7
radius = 5
while x<=30 :
centre = Point(x,y)
circle1 = Circle(centre,radius)
circle1.setFill("red")
circle1.draw(win)
x = x+10
while x>=35 and x<=65 :
centre = Point(x+5,y)
circle2 = Circle(centre,radius)
circle2.setFill("red")
circle2.draw(win)
x = x+10
print(x)
while x>=67:
centre = Point(x+10,y)
circle1 = Circle(centre,radius)
circle1.setFill("red")
circle1.draw(win)
x = x+10
main()
I got it guys, thanks
Heres the solution
#Timothy Shek
from graphics import*
#open Graph Window
def main():
win = GraphWin("Patch2" ,100,100)
for x in (5, 15, 25, 40,50,60,75,85,95):
for y in (5, 15, 25, 40,50,60,75,85,95):
c = Circle(Point(x+2,y), 5)
d = Circle(Point(x+2,y), 5)
c.draw(win)
d.draw(win)
c.setFill("Red")
d.setFill("Red")
if x==15 or x==50 or x== 85:
if y==15 or y==50 or y== 85:
c2 = Circle(Point(x+2,y),5)
c2.draw(win)
c2.setFill("White")
main()
While there is nothing wrong with your solution, this is a bit more performant
from graphics import *
def main():
win = GraphWin("Patch2" ,100,100)
coords = [5, 15, 25, 40, 50, 60, 75, 85, 95]
centers = set([coords[i] for i in range(1, len(coords), 3)])
for i in xrange(len(coords)):
for j in xrange(i+1):
x, y = (coords[i], coords[j])
c1 = Circle(Point(x+2,y), 5)
c2 = Circle(Point(y+2,x), 5)
c1.draw(win)
c2.draw(win)
if x in centers and y in centers:
c1.setFill("White")
c2.setFill("White")
else:
c1.setFill("Red")
c2.setFill("Red")
main()
Update: "Better" version
And since I got bored and I liked this problem (yes, I program when I'm bored) I made a fully parameter-ized version which you can do some fun stuff with, like.
Probably over your head :) But maybe you learn something from it, so I'm posting it.
from graphics import *
def drawPattern(scale):
# Inner method: Draw a square of circles given the top-left point
def drawSquare(win, xCoord, yCoord, squareSize=30, numCircles=3, scale=1, scaleCircles=False, outer_color="Red", inner_color="White"):
# Overwrite the default scaling
if scale > 1:
squareSize *= scale
if scaleCircles:
numCircles *= scale
radius = squareSize/(numCircles*2) # Divide by 2 since it's the radius
from math import sqrt, floor
centerDiff = (2*radius) * floor(sqrt(numCircles)) # Used for drawing off-color circles
# xrange uses an exclusive stop value, so go one value past to make inclusive
for x in xrange(radius, squareSize+radius, radius*2):
for y in xrange(squareSize-radius, x-radius, -radius*2):
c1 = Circle(Point(x+xCoord+2,y+yCoord), radius)
c2 = Circle(Point(y+yCoord+2,x+xCoord), radius)
c1.draw(win)
c2.draw(win)
if (centerDiff < x < squareSize - centerDiff) and (centerDiff < y < squareSize - centerDiff):
c1.setFill(inner_color)
c2.setFill(inner_color)
else:
c1.setFill(outer_color)
c2.setFill(outer_color)
win = GraphWin("Patch2 (x{})".format(scale), 100*scale,100*scale)
coords = [0, 35, 70]
for x in coords:
for y in coords:
drawSquare(win, x*scale, y*scale, scale=scale) # normal (boring) version
# drawSquare(win, x*scale, y*scale, scale=scale, scaleCircles=True, outer_color="Blue") # Picture version
def main():
drawPattern(3)
main()
Related
I need help to make an optimization graph in 3 dimensions with manim. I am having difficulty understanding how to use the projection methods and to represent the axes and data in three-dimensional space. If anyone has experience with manim and can help me understand how to do it, I would greatly appreciate it. Thank you
Note: I am trying to graph the schewefel function below I attach part of the code that I have been working on
%%manim -qm -v WARNING AckleyAnimation
class Schewefel(ThreeDScene):
def func(self,u,v):
return x * np.sin(np.sqrt(np.abs(x))) + y * np.sin(np.sqrt(np.abs(y)))
def construct(self):
cielo = '#C4DDFF'
azul = '#001D6E'
rojo = "#B20600"
axes = ThreeDAxes()
self.set_camera_orientation(phi=65*DEGREES,theta=60*DEGREES)
# self.add(axes,x,y)
name_function = Tex(r"Schwefel function." ,font_size=38).to_corner(UL)
self.add_fixed_in_frame_mobjects(name_function)
funcion = MathTex(r"f(x) = 418.9829d - \sum_{i=1}^{d} x_i \sin \sqrt{|x_i|}", font_size=30).to_corner(UL)
self.play(Write(name_function))
self.play(FadeOut(name_function))
self.add_fixed_in_frame_mobjects(funcion)
self.play(Write(funcion))
surface_plane = Surface(
lambda u, v: np.array([u, v, self.func(u, v)]),
u_range=[-100,100],
v_range=[-100,100],
resolution=(50, 50))
self.play(Write(surface_plane))
Graphics
function Schewefel
Correction:
So far I modified the script and I have the following
%%manim -qm -v WARNING PlotSurfaceExample
class PlotSurfaceExample(ThreeDScene):
def construct(self):
resolution_fa = 16
self.set_camera_orientation(phi=75 * DEGREES, theta=-60 * DEGREES)
axes = ThreeDAxes(x_range=(-500, 500, 1800), y_range=(-500, 500, 1800), z_range=(-500, 500, 1800))
def param_trig(u, v):
x = u
y = v
z = x * np.sin(np.sqrt(np.abs(x))) + y * np.sin(np.sqrt(np.abs(y)))
return z
trig_plane = axes.plot_surface(
param_trig,
resolution=(resolution_fa, resolution_fa),
u_range = (-500, 500),
v_range = (-500, 500),
colorscale = [BLUE, GREEN, YELLOW, ORANGE, RED],
)
self.add(axes)
self.play(Write(trig_plane))
but it gives me this result
but nevertheless I hope this
I am trying to draw a rectangle which would have an edge next to each of its sides (it should represent a building with a fence) for one building it goes quite well, but when I am trying to add a new building it messes itself up completely.
I have this code to create buildings:
class Building():
def __init__(self, Box_2_World,shape, position, sensor= None):
self.Box_2_World = Box_2_World
self.shape = shape
self.position = position
if sensor == None:
sensor = False
self.sensor = sensor
self.footprint = self.Box_2_World.CreateStaticBody(position = position,
angle = 0.0,
fixtures = b2FixtureDef(
shape = b2PolygonShape(box=(self.shape)),
density = 1000,
friction = 1000))
self.Lower_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0],self.footprint.position[1] -1.75*self.shape[1]))
self.Lower_Fence.CreateEdgeChain([(self.Lower_Fence.position[0]-4.25*self.shape[0],self.Lower_Fence.position[1]),
(self.Lower_Fence.position[0]-2.25*self.shape[0],self.Lower_Fence.position[1]),
])
self.Right_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0]-1*self.shape[0],self.footprint.position[1]))
self.Right_Fence.CreateEdgeChain([(self.Right_Fence.position[0],self.Right_Fence.position[1] - 1.25*self.shape[1]),
(self.Right_Fence.position[0],self.Right_Fence.position[1]-3.25*self.shape[1]),
])
self.Upper_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0],self.footprint.position[1] -0.45* self.shape[1]))
self.Upper_Fence.CreateEdgeChain([(self.Upper_Fence.position[0] - 4.25* self.shape[0],self.Upper_Fence.position[1]),
(self.Upper_Fence.position[0]- 3.25* self.shape[0]+ self.shape[0],self.Upper_Fence.position[1]),
])
self.Left_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0]-2.25*self.shape[0],self.footprint.position[1]))
self.Left_Fence.CreateEdgeChain([(self.Left_Fence.position[0],self.Left_Fence.position[1] - 1.25*self.shape[1]),
(self.Left_Fence.position[0],self.Left_Fence.position[1]-3*self.shape[1]),
])
Skyscrapers = []
Rectangles = [(pos_X-5, pos_Y-5),(pos_X+15, pos_Y -5),(pos_X - 5,pos_Y + 15),(pos_X+15, pos_Y + 15)]
for i in range(4):
Skyscrapers.append(Building(Box_2_World,shape = (5,5), position = Rectangles[i]))
and these functions to draw it using PyGame:
SCREEN_OFFSETX, SCREEN_OFFSETY = SCREEN_WIDTH/16, SCREEN_HEIGHT
def fix_vertices(vertices):
return [(int(SCREEN_OFFSETX + v[0]), int(SCREEN_OFFSETY - v[1])) for v in vertices]
def _draw_polygon(polygon, screen, body, fixture):
transform = body.transform
vertices = fix_vertices([transform * v * PPM for v in polygon.vertices])
pygame.draw.polygon(
screen, [c / 2.0 for c in colors[body.type]], vertices, 0)
pygame.draw.polygon(screen, colors[body.type], vertices, 1)
polygonShape.draw = _draw_polygon
def _draw_edge(edge, screen, body, fixture):
vertices = fix_vertices(
[body.transform * edge.vertex1 * PPM, body.transform * edge.vertex2 * PPM])
pygame.draw.line(screen, colors[body.type], vertices[0], vertices[1])
edgeShape.draw = _draw_edge
And the output is this: Blue rectangles represent buildings, blue lines are fences, first building fits quite nice, but the others are for some reason out of desired positions
Also, if you find out a way how to create the fences using for loop, it would be great (that's the reason why I put for-loop tag into this question)
Any help appreciated
The coordinates which are passed to CreateEdgeChain have to be relative to the body.
The position of the body is set when the object is constructed e.g:
self.Lower_Fence = self.Box_2_World.CreateStaticBody(
position=(self.footprint.position[0], self.footprint.position[1] -1.75*self.shape[1]))
And the edges have to be relative to this position rather than an absolute position.e.g:
self.Lower_Fence.CreateEdgeChain([(-4.25*self.shape[0], 0), (-2.25*self.shape[0], 0)])
To create the fences in a for-loop, you've to define a list of the edges. With the list of the edges you can create a list of fences:
fence_edges = [
[(-4.25, -1.75), (-2.25, -1.75)],
[(-1.00, -1.25), (-1.00, -3.25)],
[(-4.25, -0.45), (-2.25, -0.45)],
[(-2.25, -1.25), (-2.25, -3.25)]
]
self.Fences = []
for edge in fence_edges:
p1, p2 = edge
fence = self.Box_2_World.CreateStaticBody(position=self.footprint.position[:])
fence.CreateEdgeChain(
[(p1[0] * self.shape[0], p1[1] * self.shape[1]),
(p2[0] * self.shape[0], p2[1] * self.shape[1])])
self.Fences.append(fence)
self.Lower_Fence, self.Right_Fence, self.Upper_Fence, self.Left_Fence = self.Fences
I am trying to draw a rectangle which would have an edge next to each of its sides (it should represent a building with a fence) for one building it goes quite well, but when I am trying to add a new building it messes itself up completely.
I have this code to create buildings:
class Building():
def __init__(self, Box_2_World,shape, position, sensor= None):
self.Box_2_World = Box_2_World
self.shape = shape
self.position = position
if sensor == None:
sensor = False
self.sensor = sensor
self.footprint = self.Box_2_World.CreateStaticBody(position = position,
angle = 0.0,
fixtures = b2FixtureDef(
shape = b2PolygonShape(box=(self.shape)),
density = 1000,
friction = 1000))
self.Lower_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0],self.footprint.position[1] -1.75*self.shape[1]))
self.Lower_Fence.CreateEdgeChain([(self.Lower_Fence.position[0]-4.25*self.shape[0],self.Lower_Fence.position[1]),
(self.Lower_Fence.position[0]-2.25*self.shape[0],self.Lower_Fence.position[1]),
])
self.Right_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0]-1*self.shape[0],self.footprint.position[1]))
self.Right_Fence.CreateEdgeChain([(self.Right_Fence.position[0],self.Right_Fence.position[1] - 1.25*self.shape[1]),
(self.Right_Fence.position[0],self.Right_Fence.position[1]-3.25*self.shape[1]),
])
self.Upper_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0],self.footprint.position[1] -0.45* self.shape[1]))
self.Upper_Fence.CreateEdgeChain([(self.Upper_Fence.position[0] - 4.25* self.shape[0],self.Upper_Fence.position[1]),
(self.Upper_Fence.position[0]- 3.25* self.shape[0]+ self.shape[0],self.Upper_Fence.position[1]),
])
self.Left_Fence = self.Box_2_World.CreateStaticBody(position=(self.footprint.position[0]-2.25*self.shape[0],self.footprint.position[1]))
self.Left_Fence.CreateEdgeChain([(self.Left_Fence.position[0],self.Left_Fence.position[1] - 1.25*self.shape[1]),
(self.Left_Fence.position[0],self.Left_Fence.position[1]-3*self.shape[1]),
])
Skyscrapers = []
Rectangles = [(pos_X-5, pos_Y-5),(pos_X+15, pos_Y -5),(pos_X - 5,pos_Y + 15),(pos_X+15, pos_Y + 15)]
for i in range(4):
Skyscrapers.append(Building(Box_2_World,shape = (5,5), position = Rectangles[i]))
and these functions to draw it using PyGame:
SCREEN_OFFSETX, SCREEN_OFFSETY = SCREEN_WIDTH/16, SCREEN_HEIGHT
def fix_vertices(vertices):
return [(int(SCREEN_OFFSETX + v[0]), int(SCREEN_OFFSETY - v[1])) for v in vertices]
def _draw_polygon(polygon, screen, body, fixture):
transform = body.transform
vertices = fix_vertices([transform * v * PPM for v in polygon.vertices])
pygame.draw.polygon(
screen, [c / 2.0 for c in colors[body.type]], vertices, 0)
pygame.draw.polygon(screen, colors[body.type], vertices, 1)
polygonShape.draw = _draw_polygon
def _draw_edge(edge, screen, body, fixture):
vertices = fix_vertices(
[body.transform * edge.vertex1 * PPM, body.transform * edge.vertex2 * PPM])
pygame.draw.line(screen, colors[body.type], vertices[0], vertices[1])
edgeShape.draw = _draw_edge
And the output is this: Blue rectangles represent buildings, blue lines are fences, first building fits quite nice, but the others are for some reason out of desired positions
Also, if you find out a way how to create the fences using for loop, it would be great (that's the reason why I put for-loop tag into this question)
Any help appreciated
The coordinates which are passed to CreateEdgeChain have to be relative to the body.
The position of the body is set when the object is constructed e.g:
self.Lower_Fence = self.Box_2_World.CreateStaticBody(
position=(self.footprint.position[0], self.footprint.position[1] -1.75*self.shape[1]))
And the edges have to be relative to this position rather than an absolute position.e.g:
self.Lower_Fence.CreateEdgeChain([(-4.25*self.shape[0], 0), (-2.25*self.shape[0], 0)])
To create the fences in a for-loop, you've to define a list of the edges. With the list of the edges you can create a list of fences:
fence_edges = [
[(-4.25, -1.75), (-2.25, -1.75)],
[(-1.00, -1.25), (-1.00, -3.25)],
[(-4.25, -0.45), (-2.25, -0.45)],
[(-2.25, -1.25), (-2.25, -3.25)]
]
self.Fences = []
for edge in fence_edges:
p1, p2 = edge
fence = self.Box_2_World.CreateStaticBody(position=self.footprint.position[:])
fence.CreateEdgeChain(
[(p1[0] * self.shape[0], p1[1] * self.shape[1]),
(p2[0] * self.shape[0], p2[1] * self.shape[1])])
self.Fences.append(fence)
self.Lower_Fence, self.Right_Fence, self.Upper_Fence, self.Left_Fence = self.Fences
I need to add up the score in a multiple choice quiz.
This is my code:
from tkinter import *
import time, os, random
global questions
questions = []
questions = ['''
What does ? equal to:
43+(5x(6)**8)/8-8+8 = ?
1) 10356
2) 1049803
3) 202367
4) 12742130
5) 343321
''',
'''
Find the range, the median, the mode and the mean:
>>> 232, 4343, 434, 232.4, 43, 5453, 434, 232, 645, 23.3, 53453.3, 434 <<<
1) 53410.3, 2943.5, 434, 5496.58
2) 53410.3, 5956, 434, 5453.28
3) 232, 43, 3452, 421, 642
4) 232, 43, 43, 434
5) 232, 5453, 645, 53453.3
''',
'''
In 2004, the minimum wage in Ontario was $7.15.
In 2008, it was $8.15. What is the rate of change?
1) $0.90
2) $3.98
3) $1.54
4) $0.40
5) $1.80
''',
'''
Find the value of n:
--------------------------------------
43n/2n x (99.99/9)x7 = 99.99n
--------------------------------------
1) n = 99.92
2) n = 12.43
3) n = 16.73
4) n = 104.4
5) n = 3.98
''',
'''
Which one is NOT a linear equation?
1) y = 54x*3
2) y = 23x*7
3) y = -x
4) All of the Above
5) None of the Above
''',
'''
What is the formula for finding the surface area for a sphere?
1) 4/3πr**3
2) πr**2
3) 2πrh + 2πr**2
4) πd
5) 4πr**2
''',
'''
Which variable represents the slope?
y = mx + c
1) y
2) m
3) x
4) c
5) None of the above
''',
'''
An isosceles triangle has the top angle of 6x
and a supplementary angle of a base angle is 21x. What are the
measures of the angles of isosceles triangle?
1) 22.5, 78.75, 78.75
2) 108.97, 35.52, 35.52
3) 76.8, 51.6, 51.6
4) 20, 20, 140
5) 43.6, 5.5, 98.53
''',
'''
A sphere fits inside a rectangular box of 6cm by 6cm by 7cm.
What is the greatest possible volume of the sphere?
1) 113.04 cm*2
2) 110.46 cm*3
3) 113.04 cm*3
4) 110.46 cm*2
5) 142.9 cm*3
''',
'''
If the area of an isosceles triangle is 196 cm**2
and the height is 19.6 cm, what would it's perimeter be?
1) 53.9 cm
2) 64 cm
3) 76 cm
4) 32.43 cm
5) 32.32 cm
'''
]
global answers
global picked
global userans
global ansRandOrder
global score
answers = ['2', '1', '4', '3', '5', '5', '2', '1', '3', '2']
picked = []
userans = []
ansRandOrder = []
score = 0
def nexT():
global userans
userans.append(e1.get())
print(userans)
print(ansRandOrder)
global score
global i
i = 0
if userans[i] == ansRandOrder[i]:
score += 1
i += 1
print(score)
self.destroy()
ques()
def ques():
global self
global e1
global ansRandOrder
global picked
self = Tk()
w = 500
h = 375
ws = self.winfo_screenwidth()
hs = self.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
self.geometry('%dx%d+%d+%d' % (w, h, x, y))
x = random.randint(0, 9)
while x in picked:
x = random.randint(0, 9)
picked.append(x)
ansRandOrder.append(answers[x])
Label(self, text = '\n').pack()
Label(self, text = questions[x]).pack()
e1 = Entry(self)
e1.pack()
Label(self, text = '\n').pack()
nex = Button(self, text = 'Next Question', command = nexT).pack()
self.mainloop()
ques()
The result is always score = 0.
How can I correctly add the score?
I've experimented a bit with your code and the issue seems to lie elsewhere. For some reason or another the script always compares the wrong answers for the if in nexT. Other times, after restarting the script without clearing old variables, it always thinks the answer is correct.
I think this issue will probably go away if you clean up your code a bit. I'd recommend you rewrite your code as a class, which is a common approach to Tkinter scripts. The main advantages for you would be:
It's a lot more readable (It'll be easier to debug)
No more global variables, instead you just refer to the variables as part of the class (self.variable)
When the program exits (which it doesn't seem to do properly at the moment) you can just finish with something like del MyClass to get rid of the variable clutter. That clutter is probably why the behaviour of this bug changes from time to time.
Have a look at this thread for some good examples and explanations about building a tkinter class-based application:
Best way to structure a tkinter application
As an example for your quiz, it might look something like this: (Non-functional)
class Quiz():
def __init__(self):
self.questions = []
self.WriteQuestions()
self.answers = ['2', '1', '4', '3', '5', '5', '2', '1', '3', '2']
self.picked = []
self.userans = []
self.ansRandOrder = []
self.score = 0
#"self." instead of "global"
# Any def inside this class can refer to self."variable" and use it or update it.
self.Question()
def WriteQuestions(self):
# All your questions here, just so they're out of the way.
def NextQuestion(self):
self.userans.append(e1.get())
self.i = 0
if self.userans[i] == ansRandOrder[i]:
self.score += 1
i += 1
print(self.score)
root.destroy() # You'll need to pick a name other than "self" for your tk window
self.Question()
# self is a reserved keyword for classes and shouldn't be used for anything other
# than telling a class that you're referring to one of its own variables or functions.
def Question(self):
# etc...
if __name__ == 'main':
# set up tkloop here
# create an instance of the Quiz class, e.g.
Qz = Quiz()
# finally, after the loop finishes:
del Qz # To get rid of the old variables
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to draw a triangle like this:
I have tried different ways of solving it, but I have not done it correctly. How to add median lines in the triangle? Could someone please help and explain this to me?
from turtle import *
import random
def allTriMedian (w=300):
speed (0)
vertices = []
point = turtle.Point(x,y)
for i in range (3):
x = random.randint(0,300)
y = random.randint(0,300)
vertices.append(trutle.Point(x,y))
point = turtle.Point(x,y)
triangle = turtle.Polygon(vertices)
a = triangle.side()
b = triangle.side()
c = triangle.side()
m1 = tirangle.median
m2 = triangle.median
m3 = triangle.median
I tried to put the equation directly
def Median (a, b, c):
m1 = sqrt((((2b^2)+(2c^2)-(a^2))))
m2 = sqrt((((2a^2)+(2c^2)-(b^2))))
m3 = sqrt((((2a^2)+(2b^2)-(c^2))))
triangle.setFill("yellow")
triangle.draw(allTriMedian)
Or I thought to find a midpoint and draw a line segment to connect the vertices and midpoints.
def getMid(p1,p2):
return ( (p1[0]+p2[0]) / 2, (p1[1] + p2[1]))
mid1 = Line((point(p1[0]+p2[0]) / 2),point(x))
mid2 = Line((point(p2[1]+p3[1]) / 2),point(y))
I hate doing math. Let's see if we can solve this by throwing turtles at the problem. Lots of turtles.
We'll randomly generate the verticies of the triangle. Taking pairs of verticies in turn, we'll start a turtle at each heading toward the other. When the turtles collide (at the midpoint), we'll eliminate one turtle and send the other toward the vertex not in the pair. Once we've done this three times (with six turtles), we should have the drawing in question. Well, mostly (no fill in my solution):
from turtle import Turtle, Screen
from random import seed, randint
WIDTH, HEIGHT = 640, 480
def meet_in_the_middle(turtle_1, turtle_2):
position_2 = turtle_2.position()
while True:
turtle_1.setheading(turtle_1.towards(turtle_2))
turtle_1.forward(1)
position_1 = turtle_1.position()
if int(position_1[0]) == int(position_2[0]) and int(position_1[1]) == int(position_2[1]):
break
turtle_2.setheading(turtle_2.towards(turtle_1))
turtle_2.forward(1)
position_2 = turtle_2.position()
if int(position_2[0]) == int(position_1[0]) and int(position_2[1]) == int(position_1[1]):
break
seed()
screen = Screen()
screen.setup(WIDTH * 1.25, HEIGHT * 1.25)
vertices = []
for _ in range(3):
x = randint(-WIDTH//2, WIDTH//2)
y = randint(-HEIGHT//2, HEIGHT//2)
vertices.append((x, y))
A, B, C = vertices
turtle_AtoB = Turtle(shape='turtle')
turtle_AtoB.penup()
turtle_AtoB.goto(A)
turtle_AtoB.pendown()
turtle_BtoA = Turtle(shape='turtle')
turtle_BtoA.penup()
turtle_BtoA.goto(B)
turtle_BtoA.pendown()
meet_in_the_middle(turtle_AtoB, turtle_BtoA)
turtle_BtoA.hideturtle()
turtle_AtoB.setheading(turtle_AtoB.towards(C))
turtle_AtoB.goto(C)
turtle_AtoB.hideturtle()
turtle_BtoC = Turtle(shape='turtle')
turtle_BtoC.penup()
turtle_BtoC.goto(B)
turtle_BtoC.pendown()
turtle_CtoB = Turtle(shape='turtle')
turtle_CtoB.penup()
turtle_CtoB.goto(C)
turtle_CtoB.pendown()
meet_in_the_middle(turtle_BtoC, turtle_CtoB)
turtle_CtoB.hideturtle()
turtle_BtoC.setheading(turtle_BtoC.towards(A))
turtle_BtoC.goto(A)
turtle_BtoC.hideturtle()
turtle_CtoA = Turtle(shape='turtle')
turtle_CtoA.penup()
turtle_CtoA.goto(C)
turtle_CtoA.pendown()
turtle_AtoC = Turtle(shape='turtle')
turtle_AtoC.penup()
turtle_AtoC.goto(A)
turtle_AtoC.pendown()
meet_in_the_middle(turtle_CtoA, turtle_AtoC)
turtle_AtoC.hideturtle()
turtle_CtoA.setheading(turtle_CtoA.towards(B))
turtle_CtoA.goto(B)
turtle_CtoA.hideturtle()
screen.exitonclick()
Turtles at work:
Finished drawing:
thanks to cdlane, I took his code and put some functionality into functions to make it a Little clearer (at least for me)
# -*- coding: cp1252 -*-
import turtle
from turtle import Turtle, Screen
from random import seed, randint
WIDTH, HEIGHT = 640, 480
def create_screen(width, height):
screen = Screen()
screen.setup(width * 1.25, height * 1.25)
return screen
def create_points(count,width = WIDTH, height = HEIGHT):
vertices = []
for _ in range(count):
x = randint(-width//2, width//2)
y = randint(-height//2, height//2)
vertices.append((x, y))
return vertices
def create_turtle_at_position(position):
turtle = Turtle(shape='turtle')
turtle.hideturtle()
turtle.penup()
turtle.goto(position)
turtle.showturtle()
turtle.pendown()
return turtle
def meet_in_the_middle(turtle_1, turtle_2):
position_2 = turtle_2.position()
while True:
turtle_1.setheading(turtle_1.towards(turtle_2))
turtle_1.forward(1)
position_1 = turtle_1.position()
if int(position_1[0]) == int(position_2[0]) and int(position_1[1]) == int(position_2[1]):
break
turtle_2.setheading(turtle_2.towards(turtle_1))
turtle_2.forward(1)
position_2 = turtle_2.position()
if int(position_2[0]) == int(position_1[0]) and int(position_2[1]) == int(position_1[1]):
break
turtle_1.hideturtle()
turtle_2.hideturtle()
return create_turtle_at_position(position_2)
def draw_median(P1st, P2nd, POpposite):
turtle_AtoB = create_turtle_at_position(P1st)
turtle_BtoA = create_turtle_at_position(P2nd)
turtle_AandBmiddle = meet_in_the_middle(turtle_AtoB, turtle_BtoA)
turtle_AandBmiddle.setheading(turtle_AandBmiddle.towards(POpposite))
turtle_AandBmiddle.goto(POpposite)
return turtle_AandBmiddle
seed()
sc = create_screen(WIDTH, HEIGHT)
for _ in range(5):
sc = create_screen(WIDTH, HEIGHT)
A, B, C = create_points(3)
draw_median(A,B,C)
draw_median(B,C,A)
draw_median(C,A,B)
sc.exitonclick()
mathematical it is the easiest way to calculate this by vector. Let me say you have a triangle ABC and want to draw a line from A to the middle of BC so your vector starts at A and ends on A + AB + 1/2 BC or A + AC + 1/2 CB (vectorial)
(ax) + (bx - ax) + 0.5 (cx - bx)
(ay) (by - ay) (cy - by)
that results in the coordinates for the opposite Point of
x = 0.5(cx + bx)
y = 0.5(cy + by)