I am trying to make my circle bounce off of my rectangle using Zelle graphics.py. Once the circle bounces off of the rectangle I wanted it to keep moving randomly. Here is my code so far, and it's working!
Also I know that each circle graphics technically can use the points of the smallest possible square that would fit around the circle to do the collision but I'm having trouble with doing that.
from graphics import *
import random
def delay(d):
for i in range(d):
for i in range(50):
pass
#-------------------------------------------------
def main():
win=GraphWin("Moving Circle",500,400)
win.setBackground('white')
pt= Point(100,200)
cir=Circle(pt,30)
#changes the color of the circle for each game
r = random.randrange(256)
b = random.randrange(256)
g = random.randrange(256)
color = color_rgb(r, g, b)
cir.setFill(color)
cir.draw(win)
#rectangle
rec = Rectangle(Point(450,450), Point(275, 425))
rec.draw(win)
rec.setFill('black')
#-------------------------------------------------
pt5 = Point(250,30)
instruct1=Text(pt5, "click multiple times to start(rectangle can take multiple clicks to move)")
instruct1.setTextColor('black')
instruct1.draw(win)
#-------------------------------------------------
p=cir.getCenter()
p2=win.getMouse()
dx=1
dy=1
keepGoing=True
while keepGoing:
d = 100
delay(d)
cir.move(dx,dy)
p=cir.getCenter()
p2=win.checkMouse()
instruct1.setText("")
#rectanlge
isClicked= win.checkMouse()
if isClicked:
rp = isClicked
rc = rec.getCenter()
rdx = rp.getX() - rc.getX()
rdy = rp.getY() - rc.getY()
rec.move(rdx,rdy)
#circle
if((p.getX()-30)<=0.0) or ((p.getX()+30)>=500):
dx= -dx
if((p.getY()-30)<=0.0) or ((p.getY()+30)>=400):
dy=-dy
p3=win.checkMouse()
main()
I know that each circle graphics technically can use the points of the
smallest possible square that would fir around the circle to do the
collision
I'm playing with an alternate idea -- we could consider a circle around the rectangle instead of a square around the circle. The issue for me is that we not only need to detect collision, but come out with a sense of which way to move away from the other object. It's not just True and False but rather a (dx, dy) type of result.
Obviously, a circle around the rectangle is too crude, but suppose it were lots of smaller circles making up the rectangle and we measure circle center to center distance to detect a hit:
A hit on just a central (green) rectangle circle means reverse the vertical direction of the big circle. A hit on just the end (red) circle means reverse the horizontal direction of the big circle. And we can detect both kinds of hits and reverse the big circle completely.
Here's my rework of your code with the above in mind -- I also fixed your multiple clicking issue and made lots of style changes:
from random import randrange
from graphics import *
WIDTH, HEIGHT = 500, 400
RADIUS = 30
def delay(d):
for _ in range(d):
for _ in range(50):
pass
def distance(p1, p2):
return ((p2.getX() - p1.getX()) ** 2 + (p2.getY() - p1.getY()) ** 2) ** 0.5
def intersects(circle, rectangle):
dx, dy = 1, 1 # no change
center = circle.getCenter()
rectangle_radius = (rectangle.p2.getY() - rectangle.p1.getY()) / 2
rectangle_width = rectangle.p2.getX() - rectangle.p1.getX()
y = rectangle.getCenter().getY()
for x in range(int(rectangle_radius * 2), int(rectangle_width - rectangle_radius * 2) + 1, int(rectangle_radius)):
if distance(center, Point(rectangle.p1.getX() + x, y)) <= rectangle_radius + RADIUS:
dy = -dy # reverse vertical
break
if distance(center, Point(rectangle.p1.getX() + rectangle_radius, y)) <= rectangle_radius + RADIUS:
dx = -dx # reverse horizontal
elif distance(center, Point(rectangle.p2.getX() - rectangle_radius, y)) <= rectangle_radius + RADIUS:
dx = -dx # reverse horizontal
return (dx, dy)
def main():
win = GraphWin("Moving Circle", WIDTH, HEIGHT)
circle = Circle(Point(WIDTH / 5, HEIGHT / 2), RADIUS)
# change the color of the circle for each game
color = color_rgb(randrange(256), randrange(256), randrange(256))
circle.setFill(color)
circle.draw(win)
# rectangle
rectangle = Rectangle(Point(275, 425), Point(450, 450)) # off screen
rectangle.setFill('black')
rectangle.draw(win)
dx, dy = 1, 1
while True:
delay(100)
circle.move(dx, dy)
# rectangle
isClicked = win.checkMouse()
if isClicked:
point = isClicked
center = rectangle.getCenter()
rectangle.move(point.getX() - center.getX(), point.getY() - center.getY())
# circle
center = circle.getCenter()
if (center.getX() - RADIUS) <= 0.0 or (center.getX() + RADIUS) >= WIDTH:
dx = -dx
if (center.getY() - RADIUS) <= 0.0 or (center.getY() + RADIUS) >= HEIGHT:
dy = -dy
# collision bounce
x, y = intersects(circle, rectangle)
dx *= x
dy *= y
main()
Not perfect, but something to play around with, possibly plugging in a better intersects() implementation.
Related
I am making a little game with matplotlib (I know, terrible tool for the job but its a meme). I have a polygon that I am trying to translate around the screen, and also let you rotate it. However, I think there is a mix up between pixel coordinates and data coordinates, because once I move the polygon, the center of rotation is very wrong. Here is the code I have so far:
TLDR: Graph is 40x40 in size. I initialize my Polygon at 20,20. Before I move, rotation works fine, once I thrust, the rotation center point is no longer correct and I can see the polygon rotating around some other point
def thrust():
dx = math.cos(self.angle)
dy = math.sin(self.angle)
self.vx += self.acceleration * dx
self.vy += self.acceleration * dy
def update(ax):
self.cx += self.vx # update data coordinates
self.cy += self.vy
ts = ax.transData
coords = ts.transform([self.cx, self.cy])
t = mpl.transforms.Affine2D().translate(self.cx, self.cy)
r = mpl.transforms.Affine2D().rotate_deg_around(coords[0], coords[1], self.angle)
te = t + r
self.shape.set_transform(ts + te)
return self.shape
I am using Zelle graphics, but I suppose it is the same for any graphics program. From what I can tell, Zelle graphics does not have a "setheading" or "rotate" command for the rectangle (this is probably because the bounding box is created with two points). In turtle graphics it is easy with setheading(). So presently, I have a class that creates a polygon. I have a draw method and a rotate method. In the rotate method I am changing the Point(x1,y1) for each corner in a FOR LOOP. I broke out some graph paper to get the initial first few points to rotate, there is complex math I believe that would make this more palatable.
Presently this is my init method with these attributes, but I am sure there is a better way:
class create():
def __init__(self, p1x,p1y,p2x,p2y,p3x,p3y,p4x,p4y):
self.p1x = p1x
self.p2x = p2x
self.p3x = p3x
self.p4x = p4x
self.p1y = p1y
self.p2y = p2y
self.p3y = p3y
self.p4y = p4y
NOTE : this is not the entirety of my code. This is just the INIT method. I don't want anyone to think I have not tried this. I have with working code to rotate a polygon to the left about 5 points, but this is just using self.p1x=self.p1x+1 - I know this is not the correct way to rotate a rectangle. But at present I have a working model for rotating it slightly.
EDIT :
Here is the new work I have tried. I am still trying to understand this :
I need the midpoint, because the equation is derived from it. That is after I get the rotation correct. I am going to assume a midpoint in a 10x10 starting from the origin is going to be 5,5 for this example.
Does this code look ok so far? I am going to assume a rotation angle of 10 degrees for this example.
import math
#assume a 10 x 10 rectangle top left corner 0,0
#top left coords
x=0
y=0
#midpoints
midx = 5
midy = 5
#degrees to radians???????
angle=math.radians(10)
#new top left x
newx1 = x - midx * math.cos(angle) - (y-midy)*math.sin(angle)+ midx
#new top left y
newy1 = y - midy * math.sin(angle) + (x-midx)*math.cos(angle)+ midy
print(newx1, newy1)
The output is : 0.9442021232736115 -0.7922796533956911
This is version which works for me - it rotates Point around midx, midy with angle.
First it has to move middle to (0,0) and get current angle.
def rotate_point(point, angle, midx, midy):
old_x = point.x
old_y = point.y
old_cx = old_x - midx # move middle to (0,0)
old_cy = old_y - midy # move middle to (0,0)
angle_radians = math.radians(angle)
angle_sin = math.sin(angle_radians)
angle_cos = math.cos(angle_radians)
new_cx = old_cx * angle_cos - old_cy * angle_sin
new_cy = old_cx * angle_sin + old_cy * angle_cos
new_x = new_cx + midx # move back
new_y = new_cy + midy # move back
point = Point(new_x, new_y)
return point
And next I can use it to rotate Polygon
def rotate_polygon(polygon, angle, midx, midy):
new_points = []
for p in polygon.getPoints():
new_p = rotate_point(p, angle, midx, midy)
new_points.append(new_p)
return Polygon(*new_points)
Here full code which rotates
rectangle around middle point (angles: 30, 60),
triangle around one of corners (angles: 90, 180, 270).
import math
from graphics import *
def rotate_point(point, angle, midx, midy):
old_x = point.x
old_y = point.y
old_cx = old_x - midx # move middle to (0,0)
old_cy = old_y - midy # move middle to (0,0)
angle_radians = math.radians(angle)
angle_sin = math.sin(angle_radians)
angle_cos = math.cos(angle_radians)
new_cx = old_cx * angle_cos - old_cy * angle_sin
new_cy = old_cx * angle_sin + old_cy * angle_cos
new_x = new_cx + midx # move back
new_y = new_cy + midy # move back
point = Point(new_x, new_y)
return point
def rotate_polygon(polygon, angle, midx, midy):
new_points = []
for p in polygon.getPoints():
new_p = rotate_point(p, angle, midx, midy)
new_points.append(new_p)
return Polygon(*new_points)
# --- main ---
win = GraphWin()
# --- rectangle ---
x = 100
y = 100
w = 50
h = 50
midx = x + w//2 # rectangle middle
midy = y + h//2 # rectangle middle
p1 = Polygon(Point(x, y), Point(x+w, y), Point(x+w, y+h), Point(x, y+h), Point(x, y))
p1.draw(win)
p2 = rotate_polygon(p1, 30, midx, midy)
p2.draw(win)
p3 = rotate_polygon(p1, 60, midx, midy)
p3.draw(win)
# --- triangle ---
x = 60
y = 60
w = 50
h = 50
midx = x #+5 # triangle corner
midy = y #+5 # triangle corner
t1 = Polygon(Point(x, y), Point(x+w, y), Point(x+w//2, y+h), Point(x, y))
t1.draw(win)
t2 = rotate_polygon(t1, 90, midx, midy)
t2.draw(win)
t3 = rotate_polygon(t1, 180, midx, midy)
t3.draw(win)
t4 = rotate_polygon(t1, 270, midx, midy)
t4.draw(win)
# ---
win.getMouse()
win.close()
I'm new to OpenGL and I try to use the following code (GL_POLYGON) to draw a circle using python. But it seems like it only draws it when the points are added in a clockwise manner, otherwise, it just draws nothing
This successfully draws a circle
p = self.pos + Y_VEC * self.height # center of the circle
dv = self.dir_vec * self.radius # vector point forward
rv = self.right_vec * self.radius # vector point to right
sides = 20 # sides of the circle (circle is in fact polygon)
angle = 0
inc = 2 * math.pi / sides
glColor3f(0, 1, 0)
glPointSize(10.0)
glBegin(GL_POLYGON) # GL_POLYGON drawn but not shown in top view? GL_LINE_LOOP works
# glVertex3f(*p) # used for TRIANGLE_FAN
for i in range(sides+1):
pc = p + dv * math.cos(angle) + rv * math.sin(angle)
glVertex3f(*pc)
angle -= inc
glEnd()
Nothing rendered (only change is "-=" to "+=")
angle = 0
inc = 2 * math.pi / sides
glColor3f(0, 1, 0)
glPointSize(10.0)
glBegin(GL_POLYGON) # GL_POLYGON drawn but not shown in top view? GL_LINE_LOOP works
# glVertex3f(*p) # used for TRIANGLE_FAN
for i in range(sides+1):
pc = p + dv * math.cos(angle) + rv * math.sin(angle)
glVertex3f(*pc)
angle += inc # change here
glEnd()
Is this normal? What am I doing wrong?
Make sure face culling is disabled with glDisable(GL_CULL_FACE).
I need to make a circle by adjusting conditions on the heights, this program using a lot of random circles but I am unsure where to go from here? I am trying to use the following equation d = (sqrt)((x1 –x2)^2 +(y1 – y2)^2). Right now the program draws many random circles, so adjusting the formula i should be able to manipulate it so that certain circles are red in the centre (like the japan flag).
# using the SimpleGraphics library
from SimpleGraphics import *
# use the random library to generate random numbers
import random
diameter = 15
##
# returns a valid colour based on the input coordinates
#
# #param x is an x-coordinate
# #param y is a y-coordinate
# #return a colour based on the input x,y values for the given flag
##
def define_colour(x,y):
##
if y < (((2.5 - 0)**2) + ((-0.5 - 0)**2)**(1/2)):
c = 'red'
else:
c = 'white'
return c
return None
# repeat until window is closed
while not closed():
# generate random x and y values
x = random.randint(0, getWidth())
y = random.randint(0, getHeight())
# set colour for current circle
setFill( define_colour(x,y) )
# draw the current circle
ellipse(x, y, diameter, diameter)
Here's some code that endlessly draws circles. Circles that are close to the centre of the screen will be drawn in red, all other circles will be drawn in white. Eventually, this will create an image similar to the flag of Japan, although the edge of the inner red "circle" will not be smooth.
I have not tested this code because I don't have the SimpleGraphics module, and I'm not having much success locating it via Google or pip.
from SimpleGraphics import *
import random
diameter = 15
width, height = getWidth(), getHeight()
cx, cy = width // 2, height // 2
# Adjust the multiplier (10) to control the size of the central red portion
min_dist_squared = (10 * diameter) ** 2
def define_colour(x, y):
#Calculate distance squared from screen centre
r2 = (x - cx) ** 2 + (y - cy) ** 2
if r2 <= min_dist_squared:
return 'red'
else:
return 'white'
# repeat until window is closed
while not closed():
# generate random x and y values
x = random.randrange(0, width)
y = random.randrange(0, height)
# set colour for current circle
setFill(define_colour(x, y))
# draw the current circle
ellipse(x, y, diameter, diameter)
I have this assignment for school:
Build a Snowman without turtle circle function
The snowman should be on a blue background, and should be drawn filled with white.
The outline of the snowman should be in black.
The snowman’s body should be made of 3 filled circles.
The outline of each circle should be 3 pixels wide.
The bottom circle should have a radius of 100 pixels.
The middle circle should have a radius of 70 pixels.
The top circle should have a radius of 40 pixels.
Each circle should be centered above the one below it (except the bottom circle, which can be located anywhere).
There should be no gap between the circles.
Give the snowman a mouth, eyes, and a nose (a hat is optional).
Make sure to include two stick-arms and at least two fingers on each hand.
So far I created this, but I can't seem to get the circles right before I move on.
Also, don't know how to color in circles or make dots for eyes. Help me please, first time coding.
import turtle # allows us to use turtle library
wn = turtle.Screen() # allows us to create a graphics window
wn.bgcolor("blue") # sets gtaphics windows background color to blue
import math # allows us to use math functions
quinn = turtle.Turtle() # sets up turtle quinn
quinn.setpos(0,0)
quinn.pensize(3)
quinn.up()
# drawing first circle middle
quinn.forward(70)
quinn.down()
quinn.left(90)
# calculation of cicumference of a circle
a = (math.pi*140.00/360)
#itineration for first circle
for i in range (1,361,1):
quinn.left(a)
quinn.forward (1)
# drawing second circle bottom
quinn.up()
quinn.home()
quinn.right(90)
quinn.forward(70)
quinn.left(90)
quinn.down()
b = (math.pi*200.00/360)
for i in range (1,361,1):
quinn.right(b)
quinn.forward(1)
# drawing third circle head top
quinn.up ()
quinn.goto(0,70)
quinn.right(90)
quinn.down()
c =(math.pi*80/360)
for i in range (1,361,1):
quinn.left(c)
quinn.forward(1)
wn.exitonclick()
The following is an example function to draw a circle filled in blue:
def draw_circle(radius):
turtle.up()
turtle.goto(0,radius) # go to (0, radius)
turtle.begin_fill() # start fill
turtle.down() # pen down
turtle.color('blue')
times_y_crossed = 0
x_sign = 1.0
while times_y_crossed <= 1:
turtle.forward(2*math.pi*radius/360.0) # move by 1/360
turtle.right(1.0)
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_y_crossed += 1
x_sign = x_sign_new
turtle.up() # pen up
turtle.end_fill() # end fill.
return
Then you can modify the above function adding parameters for position (x,y) of the circle center:
def draw_circle(radius, x, y):
turtle.up()
turtle.goto(x,y+radius) # go to (x, y + radius)
turtle.begin_fill() # start fill
turtle.down() # pen down
turtle.color('blue')
times_y_crossed = 0
x_sign = 1.0
while times_y_crossed <= 1:
turtle.forward(2*math.pi*radius/360.0) # move by 1/360
turtle.right(1.0)
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_y_crossed += 1
x_sign = x_sign_new
turtle.up() # pen up
turtle.end_fill() # end fill.
return
You can easily add dots as, for instance,:
turtle.goto(-20,10)
turtle.color('red')
turtle.dot(20)
turtle.goto(40,10)
turtle.dot(20)
Putting together:
import turtle
import math
def draw_circle(radius, x, y):
turtle.up()
turtle.goto(x,y+radius) # go to (0, radius)
turtle.begin_fill() # start fill
turtle.down() # pen down
turtle.color('blue')
times_y_crossed = 0
x_sign = 1.0
while times_y_crossed <= 1:
turtle.forward(2*math.pi*radius/360.0) # move by 1/360
turtle.right(1.0)
x_sign_new = math.copysign(1, turtle.xcor())
if(x_sign_new != x_sign):
times_y_crossed += 1
x_sign = x_sign_new
turtle.up() # pen up
turtle.end_fill() # end fill.
return
draw_circle(100, 10, 10)
turtle.goto(-20,10)
turtle.color('red')
turtle.dot(20)
turtle.goto(40,10)
turtle.dot(20)
turtle.pen(shown=False)
turtle.done()
You should attempt to do by yourself the remaining part of the assignment.. ;)
Sorry for not giving an explanation.
The first part is Ramanujan's aproximation of pi, but not a very good one because it only reaches an aproximation of pi after something like 300,000 iterations of the loop and it is only accurate to 5 decimal places. that would be this part:
r += (1 / k) * (-1)**i
pi = (4 * (1 - r))
Then I use the circumference of a circle:
t.forward(2*5*pi)
Finally I just make the turtle walk clock wise by 20.
import turtle
t = turtle.Turtle()
t.right(90)
t.penup()
t.goto(100, 0)
t.pendown()
i = 0
r = 0
k = 3
while i <= 360:
r += (1 / k) * (-1)**i
pi = (4 * (1 - r))
t.write(pi)
t.forward(2*5*pi)
t.right(20)
i += 1
k += 2
turtle.done()
From a mathematical standpoint, you can use functions sin and cos from the math to plot the circle.
Once the circle is plot, use the turtle.begin_fill() and turtle.end_fill() methods to fill in the circle (though I do agree that in programming, this method is more practical):
from turtle import Turtle
from math import sin, cos, radians
def draw_circle(radius, x, y, color="light blue", line_width=3):
c = Turtle(visible=False)
c.width(3)
c.penup()
c.goto(x + radius, y)
c.pendown()
c.color("black", color)
c.begin_fill()
# Circle drawing starts here
for i in range(1, 361):
c.goto(radius * cos(radians(i)) + x,
radius * sin(radians(i)) + y)
# Circle drawing ends here
c.end_fill()
draw_circle(100, 0, -100)
As pointed out in this answer, you can use the turtle.dot() method to draw a dot on the screen,
and the width of the pen will be the diameter of the dot.
There's another way to do that, but compared to the dot method, it is impractical.
I'll throw it out there anyway, just to show how there are many possibilities in workarounds:
from turtle import Turtle
def draw_circle(radius, x, y, color="light bue", line_width=3):
c = Turtle(visible=False)
c.penup()
c.goto(x, y)
c.pendown()
# Circle drawing starts here
c.width(radius * 2 + line_width)
c.forward(0)
c.color(color)
c.width(radius * 2 - line_width)
c.forward(0)
# Circle drawing ends here
draw_circle(100, 0, -100)
So a turtle.dot() is the equivalent of turtle.forward(0) (and turtle.backward(0), turtle.goto(turtle.pos()), turtle.setpos(turtle.pos()), etc., etc.).
Output:
Most solutions to "without turtle circle function" involve writing your own equivalent to turtle's circle function. But there are already two other ways you can draw outlined, filled circles with turtle.
One is you can use concentric dots:
turtle.color('black')
turtle.dot(200 + 3)
turtle.color('white')
turtle.dot(200 - 3)
Just remember that dot() takes a diameter whereas circle() takes a radius:
However, I prefer to use stamping to solve these sorts of problems:
''' Build a Snowman without turtle circle function '''
from turtle import Turtle, Screen
# The snowman’s body should be made of 3 filled circles.
# The bottom circle should have a radius of 100 pixels.
# The middle circle should have a radius of 70 pixels.
# The top circle should have a radius of 40 pixels.
RADII = (100, 70, 40)
STAMP_SIZE = 20
# The snowman should be on a blue background
screen = Screen()
screen.bgcolor('blue')
quinn = Turtle('circle')
quinn.setheading(90)
quinn.up()
# The outline of the snowman should be in black, and should be drawn filled with white.
quinn.color('black', 'white')
for not_first, radius in enumerate(RADII):
if not_first:
quinn.forward(radius)
# The outline of each circle should be 3 pixels wide.
quinn.shapesize((radius * 2) / STAMP_SIZE, outline=3)
quinn.stamp()
# Each circle should be centered above the one below it
# There should be no gap between the circles.
quinn.forward(radius)
# Give the snowman eyes
quinn.shapesize(15 / STAMP_SIZE)
quinn.color('black')
quinn.backward(3 * RADII[-1] / 4)
for x in (-RADII[-1] / 3, RADII[-1] / 3):
quinn.setx(x)
quinn.stamp()
# Give the snowman a mouth, and a nose (a hat is optional).
pass
# Make sure to include two stick-arms and at least two fingers on each hand.
pass
quinn.hideturtle()
screen.exitonclick()
The idea is you contort the turtle cursor itself to what you need, make a snapshot of it on the screen, and then contort it to the next thing you need to draw.
You can create a function that takes arguments fd, and left.
here is what I created.
from turtle import *
speed(100000)
for i in range(360):
fd(2)
left(1)
Here is the calculation: The iterations in range divided by the fd+left.
That is the approximation I have. SO you should be able to create a function like that.
You could try this, hope this helps!
def polygon(length, sides):
for i in range(sides):
turtle.forward(length)
turtle.left(360.0/sides)
polygon(1, 360)