Sarah
Sarah

Reputation: 21

Produce Overlapping Triangles Using Python Turtle

I'm trying to produce a particular pattern using Python Turtle but I am having problems. I've created the first triangle but I am not sure how I go by adding the second one in it and coloring it.

What I need it to be: http://gyazo.com/5abdd3bc05a44945f1a74286e2ad43c6

What I currently have: http://gyazo.com/65357ea5d43a7dc49e89879a27e980b4

Code so far:

forward(200)
left(120)
forward(200)
left(120)
forward(200)
right(120)
done()

Upvotes: 1

Views: 2158

Answers (2)

cdlane
cdlane

Reputation: 41872

Below is a complete solution based on stamping instead of drawing which can be the better way to go with some turtle problems:

import turtle
from operator import add

RED = (1.0, 0.0, 0.0)
GREEN = (0.0, 1.0, 0.0)
SUM = map(add, RED, GREEN)

TRIANGLE_SIZE = 200
BORDER_SIZE = 5

STAMP_UNIT = 20
SQRT_3 = 3 ** 0.5

turtle.shape("triangle")
turtle.hideturtle()
turtle.penup()
turtle.right(30)  # realign triangle
turtle.fillcolor(RED)
turtle.shapesize(TRIANGLE_SIZE / STAMP_UNIT, TRIANGLE_SIZE / STAMP_UNIT, BORDER_SIZE)
turtle.stamp()

turtle.fillcolor(GREEN)
y_offset = TRIANGLE_SIZE * SQRT_3 / 4
turtle.goto(TRIANGLE_SIZE / 4, -y_offset)
turtle.stamp()

turtle.shapesize(TRIANGLE_SIZE / STAMP_UNIT / 2, TRIANGLE_SIZE / STAMP_UNIT / 2, BORDER_SIZE)
turtle.fillcolor(SUM)
turtle.sety(turtle.ycor() + 2 * y_offset / 3)
turtle.stamp()

turtle.exitonclick()

I'll discuss the color mixing in answer to the followup question to this question.

OUTPUT

enter image description here

Upvotes: 0

Avinash Ranjan
Avinash Ranjan

Reputation: 611

Here is an example

import turtle
def draw_square(turtle, length):
    for i in range(4):
        turtle.forward(length)
        turtle.right(90)

def Retat_square(turtle, length,nbr):
    for i in range(nbr):
        draw_square(turtle, length) 
        turtle.right(360/nbr)

def main():
    window = turtle.Screen()
    window.bgcolor("blue")

above is a method which will draw a square and below calling that method with turtle class

s = turtle.Turtle()
s.shape("turtle")
s.color("yellow")
s.speed()

Retat_square(s,100,30)

I hope this will help you

Upvotes: 1

Related Questions