logo
down
shadow

Using turtle in Python to draw six-pointed stars with different side lengths


Using turtle in Python to draw six-pointed stars with different side lengths

By : Ashok Arjunan
Date : November 21 2020, 11:01 PM
it helps some times Hopefully I'll be able to explain this well. I'm currently using helper functions to draw a six-pointed star in the turtle graphics window of python. First, we had to create a function to draw a triangle. Here is my code: , Anywhere you use a unit that has a dimension:
code :
tess.fd(80)
tess.fd(120) # probably should be tess.fd(sz)
tess.fd(80)
from turtle import Turtle, Screen

WIDTH_RATIO = 2 * 3**0.5 / 3  # ratio of widest point in star to edge of triangle 

def triangle(size):
    for i in range(3):
        tess.fd(size)
        tess.lt(120)

def sixPtdStar(size):
    triangle(size)
    tess.lt(30)
    tess.pu()
    tess.fd(size * WIDTH_RATIO)
    tess.lt(150)
    tess.pd()
    triangle(size)

def rowOfStars(numInRow, size):
    for i in range(numInRow):
        sixPtdStar(size)
        tess.pu()
        tess.lt(90)
        tess.fd(size * WIDTH_RATIO / 2)
        tess.lt(90)
        tess.pd()

def sqrOfRows(numInRow, size):
    tess.pu()
    halfSize = numInRow * size / 2
    tess.goto(-halfSize, halfSize)  # center on screen
    tess.pd()

    for i in range(4):
        rowOfStars(numInRow, size)
        tess.rt(90)

screen = Screen()
tess = Turtle()
tess.speed("fastest")  # numbers > 10 are all equivalent, safer to use symbols 

sqrOfRows(6, 36)

screen.exitonclick()


Share : facebook icon twitter icon
Drawing Stars with turtle in python

Drawing Stars with turtle in python


By : Soufiane
Date : March 29 2020, 07:55 AM
Any of those help I need to write a function that draws random stars based upon the question of how many stars the person wants. a=color,b=length and c,d are the starting coordinates. I am not really sure where I am going wrong any tips,hints or help would be appreciated. , To call a function, put parentheses after the function name:
code :
   a=random_color()
   b=length()
   c=x()
   d=y()
star('red',100,0,0)
def length():
    return randrange(5,71)

def x():
    return randrange(-280,281)

def y():
    return randrange(-200,201)
   for i in range(z):
       a=random_color()
       b=length()
       c=x()
       d=y()
       star(a,b,c,d)
def star(color, side_length, x, y):
    print(color, side_length, x, y)
    turtle.color(color)
    turtle.begin_fill()
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    for i in range(5):
        turtle.forward(side_length)
        turtle.right(144)
        turtle.forward(side_length)
    turtle.end_fill()
import turtle
import random

def star(color, side_length, x, y):
    print(color, side_length, x, y)
    turtle.color(color)
    turtle.begin_fill()
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()
    for i in range(5):
        turtle.forward(side_length)
        turtle.right(144)
        turtle.forward(side_length)
    turtle.end_fill()


def random_color():
    randvar = randrange(0, 5)
    if randvar == 0:
        return ('red')
    elif randvar == 1:
        return ('blue')
    elif randvar == 2:
        return ('green')
    elif randvar == 3:
        return ('yellow')
    else:
        return ('black')


def length():
    return random.randrange(5, 71)


def xcoord():
    return random.randrange(-280, 281)


def ycoord():
    return random.randrange(-200, 201)


def night_sky():
    z = int(input('How many stars do you want?'))
    for i in range(z):
        color = random_color()
        side_length = length()
        x = xcoord()
        y = ycoord()
        star(color, side_length, x, y)

night_sky()
How to draw sine in Python turtle?

How to draw sine in Python turtle?


By : Maya Technology
Date : March 29 2020, 07:55 AM
I wish this help you In the text book, the code can draw sin(x). , Work out the y-coordinates of the points that are being drawn:
code :
50 * sin((-175/100) * 2π)
50 * sin((-174/100) * 2π)
50 * sin((-173/100) * 2π)
...
50 * sin((175/100) * 2π)
50 * sin((176/100) * 2π)
Draw a square in Python Turtle

Draw a square in Python Turtle


By : Emir Bečić
Date : March 29 2020, 07:55 AM
I hope this helps . I am following a tutorial for Python learning and I can't get the screen to open to draw. I don't get an error, it just shows that the program finish running. Maybe I missed something, can someone point it out? , Your primary error is these two lines are in the wrong order:
code :
window.exitonclick() #click the screen to close it
draw_square()
import turtle

# to draw a square, or eventually a turtle, you need to do the things below

def draw_square():
    """ draw square for turtles """

    # to draw a square you want to : move forward, turn right,
    #  move forward, turn right,move forward turn right

    brad = turtle.Turtle()
    brad.forward(100)  # forward takes a number which is the distance to move
    brad.right(90)  # turn right
    brad.forward(100)
    brad.right(90)
    brad.forward(100)
    brad.right(90)
    brad.forward(100)
    brad.right(90)

window = turtle.Screen()
# this is the background where the turtle will move
window.bgcolor("red") # the color of the window

draw_square()

window.exitonclick()  # click the screen to close it
How can I create five pointed stars in canvas using function?

How can I create five pointed stars in canvas using function?


By : Mattr
Date : March 29 2020, 07:55 AM
I wish this help you Make a loop of the number of points in the shape. In the case of a 5 pointed star that is 10 points because you have the outer points to make the spikes and the inner points which come back into the shape.
Inside the loop you find each consecutive point (x, y coordinate) to draw a line to e.g. using ctx.lineTo(x, y);.
code :
  const x = xOffset+Math.sin(angle)*radius;
  const y = yOffset+Math.cos(angle)*radius;
for(let i = 0; i < 10; i ++){ ... }
const canv = document.getElementById('c');
const ctx = canv.getContext('2d');
const w = window.innerWidth;
const h = window.innerHeight
canv.width = w;
canv.height = h;
ctx.clearRect(0,0,w,h);
//offset x,y, size, spokes, rotation 0 to 1.
function star(ox, oy, s = 10, n = 5, r = 0.25){
  ctx.beginPath();
  
  for(let i=0;i<n*2;i++){
    let rotation = Math.PI*2*r;
    let angle = (i/(n*2))*Math.PI*2+rotation;
    let dist = s*(i%2)+s;
    let x = ox+Math.cos(angle)*dist;
    let y = oy+Math.sin(angle)*dist;
    if(i === 0) {
      ctx.moveTo(x, y);
      continue; //skip
    }
    ctx.lineTo(x, y);
  }
  ctx.closePath();
}

ctx.fillStyle = 'magenta';
star(w/2, h/2, 10, 4, 0.125);
ctx.fill();

ctx.fillStyle = 'red';
star(w*0.2, h*0.2, 5, 5);
ctx.fill();

ctx.fillStyle = 'orange';
star(w*0.33, h*0.33, 20, 5);
ctx.fill();

ctx.fillStyle = 'yellow';
star(w*0.66, h*0.25, 30, 6);
ctx.fill();

ctx.fillStyle = 'green';
star(w*0.2, h*0.75, 40, 7);
ctx.fill();

ctx.fillStyle = 'cyan';
star(w*0.82, h*0.8, 50, 8, 1/16);
ctx.fill();
canvas {
 position: absolute;
 left: 0;
 top: 0;
 width: 100%;
 height: 100%;
 overflow: hidden;
 background-color: black;
}
<canvas id="c"></canvas>
Python draw n-pointed star with turtle graphics

Python draw n-pointed star with turtle graphics


By : Álvaro Hurtado Moren
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can draw most of the odd and even pointed stars with the same code by using a GCD routine to look for coprimes and treating failures as exceptions:
Related Posts Related Posts :
  • Django Form Based on Variable Attributes
  • Relocate all the evens
  • How to scrap span ids' texts in beautifulsoup in the following html?
  • How to generate random number in a given range as a Tensorflow variable
  • Gradient Descent Variation doesn't work
  • Python 2.7 - search for a particular URL on a webpage with ajax
  • How to configure Luigi task retry correctly?
  • web.py : an urlencoded slash into args
  • Use of pyzmq's logging handler in python
  • How to count the number of a particular entry. python
  • devide int into lower whole ints
  • Access atribute of every object in pandas dataframe column
  • Combine Dataframe rows on conditions
  • Select closest date (or value) in pandas / python
  • Pycharm and remote interpreter (Docker) shows errors but runs fine
  • Get started to launch google-cloud-ml with my own dataset
  • Multiprocessing: use only the physical cores?
  • Django Login Custom Auth works locally but not on production server
  • Python: Invalid HTTP basic authentication header with long base64 string
  • How can I request several pages without wating for the output?
  • Flask Response vs Flask make_response
  • python linear regression predict by date
  • How to get pandas dataframe where columns are the subsequent n-elements from another column dataframe?
  • MYSQL: "Access denied for user 'X'@'localhost' (using password: YES)" PYTHON
  • install scipy package via pycharm in windows 10 64 bit - python 3.5
  • Update time in linux and solaris machines from robot framework
  • Complex pandas isin function
  • Averaging over every n elements of an array without numpy
  • An elegant way of inserting multiple arguments
  • IntegrityError:NOT NULL constraint failed: chatapp_chat.message
  • Indexing of 3d numpy arrays with 2d arrays
  • Creating a mean of columns with csv writer
  • Reading in environment variables from an environment file
  • Collapse duplicate rows with pandas
  • How can I use skyfied to convert SGP4 TEME coordinate to ECEF?
  • How to modify object in Python's Rtree index
  • Create Hexbin plot with pandas dataframe using index and columns names as x and y
  • SQLAlchemy query returns no data if a database field is empty
  • Python pandas column asignment between dataframe and series does not work
  • ValueError: Unknown label type: array while using Decision Tree Classifier and using a custom dataset
  • Trouble accessing exif information with PIL.Image._getexif()
  • Use all coordinates in a grid except with certain value
  • Why for loop is splitting strings of user input?
  • How can I add two variable and assign to result variable in Python?
  • Error when parsing timestamp with pandas read_csv
  • Slicing arrays based on boolean array in python
  • Feeding scipy.sparse() sparse matrices into CVXOPT
  • How to separate a irregularly cased string to get the words? - Python
  • Pandas: replace some values in column if that contain a substring
  • Fabric does not close the ssh connection
  • Python Creating Classes Code
  • When will train() method in easy_seq2seq stop?
  • How to split each element of the RDD in spark with python?
  • Read in csv file in python, round the values and write back to file
  • How to properly close a QWidget-window in an API with PythonQt
  • How to know which segment a value reside in
  • pandas: convert multiple categories to dummies
  • 'Options' object has no attribute 'get_all_field_names'
  • Customize django filter model field
  • NLTK tag Dutch sentence
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com