im trying to get my turtle to draw a spiralling spiderweb but i just cant get the spiral to spiral or to loop until it hits the edge. ive tried several different things but i cant work it out. im pretty new to coding :)
from turtle import *
from math import sin, cos, pi
from random import randint
shape("circle")
turtlesize(0.3)
speed(5)
n=int(input("give number of main lines: "))
r=int(input("give length of main lines: "))
spiraldistance=r/10
angle=360/n
rad=(pi*angle)/180
for i in range(n):
forward(r)
backward(r)
right(hoek)
x=cos(rad*0)*spiraldistance
y=sin(rad*0)*spiraldistance
goto(x,y)
integers = []
for j in range(0, r):
p = 10/n
integers.append(j)
integers.append(p)
x=cos(rad*j)*(spiraldistance+p)
y=sin(rad*j)*(spiraldistance+p)
goto(x,y)
input("Press enter to finish")
i need it to spiral this way look at the screenshots
https://gyazo.com/028228823b7aab611db144436cf93868
https://gyazo.com/5c9ca19cfa34be5559bdbc3365f65f0d
pls help :(
Inside loop you have to change p but you always use the same value
p = 10/n
If you use += instead of =
p += 10/n
then you can get spiral
Example code:
from turtle import *
from math import sin, cos, pi
shape("circle")
turtlesize(0.3)
speed(0)
#---
#n = int(input("give number of main lines: "))
n = 5
#r = int(input("give length of main lines: "))
r = 200
#---
angle = 360/n
for i in range(n):
forward(r)
backward(r)
right(angle)
#---
spiraldistance = r/10
rad = (pi*angle)/180
p = 0
for j in range(r):
x = cos(rad*j) * (spiraldistance+p)
y = sin(rad*j) * (spiraldistance+p)
goto(x, y)
p += 10/n
exitonclick()
Result for n = 5:
Result for n = 15:
EDIT: To stop spiral before end of lines which have leght r you would have to compare spiraldistance+p with r` - ie
if spiraldistance+p >= r:
break
Or better use while loop for this
spiraldistance = r/10
rad = (pi*angle)/180
p = 0
j = 0
while spiraldistance+p < r:
x = cos(rad*j) * (spiraldistance+p)
y = sin(rad*j) * (spiraldistance+p)
goto(x, y)
p += 10/n
j += 1
EDIT: I added steps to choose how many times spiral "cross" every line.
from turtle import *
from math import sin, cos, pi
shape("circle")
turtlesize(0.3)
speed(0)
#--- settings ---
# number of main lines
#n = int(input("give number of main lines: "))
n = 15
# length of main lines
#r = int(input("give length of main lines: "))
length = 200
# number of steps on every main line
steps = 15
#--- main lines ---
angle = 360/n
for i in range(n):
forward(length)
backward(length)
right(angle)
#--- spiral ---
p = (length/n)/steps
rad = (pi*angle)/180
spiraldistance = 0
j = 0
while spiraldistance < length:
spiraldistance += p
x = cos(j) * spiraldistance
y = sin(j) * spiraldistance
goto(x, y)
j += rad
#--- keep open ---
#mainloop()
exitonclick()
Steps 5 and 15:
Related
I am having an issue with my code. The increment in the last if statement doesn't properly increment. My main issue is that for frac and dfrac, I receive a value of zero, which I assume is because hit is being read as zero.
import LT.box as B
import numpy as np
import matplotlib.pyplot as plt
import sys
import math
#width (cm)
w = 15
#length (cm)
l = 20
#distance between panels (cm)
d = 80
#number of events
n = 10000
print('Width cm:', w)
print('Length cm:', l)
print('Distance cm:', d)
print('Number of events:', n)
hit = 0
for i in range(n):
if i % 5000 == 0:
print("Event %6d out of %d\r" % (i, n))
sys.stdout.flush()
# accepted number of rays
cost = np.random.random()**(1/3)
phi = np.random.random()*2.0*np.pi
xtop =np.random.random()*w
ytop = np.random.random()*l
sinp = np.sin(phi)
cosp = np.cos(phi)
sint = np.sqrt(1.0 - cost*cost)
tant = sint/cost
tantx = tant*sinp
tanty = tant*cosp
xbot = xtop-tantx*d
ybot = ytop-tanty*d
# check if event goes through both panels
if (0 <= xbot <= w) and (0 <= ybot <= l):
if (w <= xbot+d <= 2*w) and (0 <= ybot <= l):
hit +=1
frac = hit / n
dfrac = math.sqrt(hit) / n
I tried making an increment function and other methods of incrementation, but I wasn't able to implement it. I either got the same value of zero in frac or I received a syntax error.
As you can see below, I have a Monte Carlo calculation using M = 1000 so printing whether a step was left or right results in a very long list. Instead I’d like to print “Right = x” and “Left = y ” x and y being the amount of times the Walker stepped left and right.
I do not know how to go about that. Some help would be appreciated, Thank you!!
Here’s what i have so far
def Random_Walker(N, p, s):
x = 0 # Walker starts from rest
for i in range(N):
if(np.random.rand() < p):
print("right", count)
x = x + s
else:
print("left")
x = x - s
return(x)
# Defining the main part of the code
def main():
import numpy as np
# Defining variables
N = 50 # Number of steps before stopping
p = 0.66 # Probability of stepping right
s = 0.75 # Length of a step in meters
M = 1000 # Number of walks
X = np.zeros(M)
for i in range(M):
X[i] = Random_Walker(N, p, s)
print(X)
print("Mean = ", np.mean(X))
print("Standard Deviation = ", np.std(X))
main()
Here's an attempt. I haven't tried to run it:
def Random_Walker(N, p, s):
x = 0 # Walker starts from rest
lcount = 0
rcount = 0
for i in range(N):
if(np.random.rand() < p):
print("right", count)
rcount += 1
x = x + s
else:
print("left")
lcount += 1
x = x - s
return (x, lcount, rcount)
# Defining the main part of the code
def main():
import numpy as np
# Defining variables
N = 50 # Number of steps before stopping
p = 0.66 # Probability of stepping right
s = 0.75 # Length of a step in meters
M = 1000 # Number of walks
X = np.zeros(M)
for i in range(M):
X[i], lcount, rcount = Random_Walker(N, p, s)
print (f"Walker {i} L/R ratio: {lcount}/{rcount}")
print(X)
print("Mean = ", np.mean(X))
print("Standard Deviation = ", np.std(X))
main()
I have created a random walk scenario where it takes one step in a random direction for a specific number of times. The one thing that I have run in to is that sometimes it will go off of the graphics window that I have set up and I can no longer see where it is at.
Here is the code:
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
for i in range(steps):
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
walker()
My question is, Is there a way that I can set parameters on the graphics window so that the walker can not go outside the window? And if it tries to, it would just turn around and try another direction?
Try defining upper and lower bounds for x and y. Then use a while loop that keeps trying random points until the next one is in bounds.
from random import *
from graphics import *
from math import *
def walker():
win = GraphWin('Random Walk', 800, 800)
win.setCoords(-50, -50, 50, 50)
center = Point(0, 0)
x = center.getX()
y = center.getY()
while True:
try:
steps = int(input('How many steps do you want to take? (Positive integer only) '))
if steps > 0:
break
else:
print('Please enter a positive number')
except ValueError:
print('ERROR... Try again')
# set upper and lower bounds for next point
upper_X_bound = 50.0
lower_X_bound = -50.0
upper_Y_bound = 50.0
lower_Y_bound = -50.0
for i in range(steps):
point_drawn = 0 # initialize point not drawn yet
while point_drawn == 0: # do until point is drawn
drawpoint = 1 # assume in bounds
angle = random() * 2 * pi
newX = x + cos(angle)
newY = y + sin(angle)
if newX > upper_X_bound or newX < lower_X_bound:
drawpoint = 0 # do not draw, x out of bounds
if newY > upper_Y_bound or newY < lower_Y_bound:
drawpoint = 0 # do not draw, y out of bounds
if drawpoint == 1: # only draw points that are in bounds
newpoint = Point(newX, newY).draw(win)
Line(Point(x, y), newpoint).draw(win)
x = newX
y = newY
point_drawn = 1 # set this to exit while loop
walker()
I am trying to use Turtle to print 30 hexagons that are spiralling and have a gradient color change from red to black.
I am multiplying my for loop i in order to change the set values in (r, b, g) so, at some point, it will exceed r=255. I include an if statement to have it not exceed this, but it's giving me the error:
File "<ipython-input-4-35d45ac44fdd>", line 20
if r > '255'
^
SyntaxError: invalid syntax
What is causing this error?
FYI I am using Anaconda and a Jupyter notebook.
Here is my code:
import turtle
def draw_hexagon (t, size):
n=6
angle= 360/n
for i in range(n):
t.forward(size)
t.left(angle)
turtle.colormode(255)
mega=turtle.Turtle()
mega.speed(1000)
leng = 100
for i in range(30):
r = 5+(i*10)
g = 0
b = 0
color = (r, b, g)
if r > 255
print color(r,b,g)
mega.fillcolor(color)
mega.begin_fill()
draw_hexagon(mega, leng)
mega.end_fill()
leng = leng + 5
mega.left(5)
turtle.exitonclick()
My advice is to not use the if statement to get around the error but rather fix your math to avoid it in the first place. Plus some code cleanup:
from turtle import Turtle, Screen
MIN_COLOR = 5
MAX_COLOR = 255
COUNT = 30
ANGLE = 5
STARTING_LENGTH = 100
LENGTH_INCREMENT = 5
N = 6
def draw_polygon(turtle, size):
angle = 360 / N
for _ in range(N):
turtle.forward(size)
turtle.left(angle)
screen = Screen()
screen.colormode(255)
mega = Turtle()
mega.speed('fastest')
length = STARTING_LENGTH
for r in range(COUNT):
red = round(r * ((MAX_COLOR - MIN_COLOR) / (COUNT - 1))) + MIN_COLOR
color = (red, 0, 0)
mega.fillcolor(color)
mega.begin_fill()
draw_polygon(mega, length)
mega.end_fill()
length += LENGTH_INCREMENT
mega.left(ANGLE)
mega.hideturtle()
screen.exitonclick()
How I can make my Python program faster? This program calculates the Mandelbrot set and draws it with turtle. I think the problem is in the for loop. Maybe the steps are taking too much time.
import numpy as np
import turtle
turtle.ht()
turtle.pu()
turtle.speed(0)
turtle.delay(0) turtle.colormode(255)
i= int(input("iteration = "))
g = int(input("accuracy = "))
xmin = float(input("X-min: "))
xmax = float(input("X-max: "))
ymin = float(input("Y-min: "))
ymax = float(input("Y-max: "))
cmode = int(255/i)
input("PRESS TO START")
for x in np.arange(xmin,xmax,1/g):
for y in np.arange(ymin,ymax,1/g):
c = x + y * 1j
z = 0
t = 1
for e in range(i):
z = z * z + c
if abs(z) > 3:
turtle.setx(g*c.real)
turtle.sety(g*c.imag)
turtle.dot(2,e*cmode,e*cmode,e*cmode)
t = 0
if t == 1:
turtle.setx(g*c.real)
turtle.sety(g*c.imag)
turtle.dot(2,"black")
input("Calculated!")
turtle.mainloop()
Here is an example
The following rework should be a hundred times faster than your original:
import numpy as np
import turtle
i = int(input("iteration = "))
g = int(input("accuracy = "))
xmin = float(input("X-min: "))
xmax = float(input("X-max: "))
ymin = float(input("Y-min: "))
ymax = float(input("Y-max: "))
cmode = int(255 / i)
input("PRESS TO START")
turtle.hideturtle()
turtle.penup()
turtle.speed('fastest')
turtle.colormode(255)
turtle.setundobuffer(None) # turn off saving undo information
turtle.tracer(0, 0)
for x in np.arange(xmin, xmax, 1 / g):
for y in np.arange(ymin, ymax, 1 / g):
c = x + y * 1j
z = 0
t = True
for e in range(i):
z = z * z + c
if abs(z) > 3.0:
turtle.setposition(g * c.real, g * c.imag)
rgb = e * cmode
turtle.dot(2, rgb, rgb, rgb)
t = False
break
if t:
turtle.setposition(g * c.real, g * c.imag)
turtle.dot(2, "black")
turtle.update()
print("Calculated!")
turtle.mainloop()
The significant change is the use of the combination of tracer() and update() to avoid visually plotting every dot for the user and just drawing as each vertical column completes.