user14299410
user14299410

Reputation:

Turtle drawing a hexagon and hexagon grid

current code

#import the turtle modules  
import turtle 
  
#Start a work Screen 
ws=turtle.Screen() 
  
#Define a Turtle Instance 
geekyTurtle=turtle.Turtle() 
  
#executing loop 6 times for 6 sides 
for i in range(6): 
    
  #Move forward by 90 units  
  geekyTurtle.forward(90) 
    
  #Turn left the turtle by 300 degrees 
  geekyTurtle.left(300)

My goal is to make a hexagon grid pattern and I am failing to do it properly. My first issue is if you run the code you get a hexagon but the top is flat, I can't get it to get the pointy corners to get on top. Second I tried to make the grid and it failed and I am not sure why I am unable to copy the same hexagon and clone it next to the other. I will or should have a file of the image that I am going for below.

The output I am getting:

The output I am trying to get:

Upvotes: 1

Views: 4436

Answers (2)

cdlane
cdlane

Reputation: 41895

It seems like this is a problem that recursion could simplify in a fractal-like way. Each side of the initial hexagon is itself a hexagon, and so forth, filling the available space:

from turtle import Screen, Turtle

SIDE = 75  # pixels

def hexagon(side, depth):
    if depth > 0:
        for _ in range(6):
            turtle.forward(side)
            turtle.right(60)
            hexagon(side, depth - 1)
            turtle.left(120)

screen = Screen()
screen.tracer(False)  # because I have no patience

turtle = Turtle()
turtle.penup()
turtle.width(2)
turtle.sety(-SIDE)  # center hexagons on window
turtle.pendown()
turtle.left(30)  # optional, orient hexagons

hexagon(SIDE, depth=6)  # depth depends on coverage area

turtle.hideturtle()
screen.tracer(True)
screen.exitonclick()

enter image description here

Upvotes: -1

F.NiX
F.NiX

Reputation: 1505

  1. Before going into loop, turn 30 degrees.

geekyTurtle.right(30)

  1. In order to have its clone beside, just put the turtle to the new place and draw the shape again:

    for i in range(6):
      geekyTurtle.forward(90)
      geekyTurtle.left(300)
    geekyTurtle.up()
    geekyTurtle.goto(90 * 3 ** .5, 0)
    geekyTurtle.down()
    for i in range(6):
      geekyTurtle.forward(90)
      geekyTurtle.left(300)
    

Put it in a loop to have it for more than two times

  1. You can use the idea of .up() and .goto(x, y) and .down() to draw grids.

Upvotes: 2

Related Questions