repl.it
@Charanpreet/

3.07 Examples - Drawing a triangle grid

Python (with Turtle)

No description

fork
loading
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import turtle

def draw_right_triangle(width, height):
  starting_x = turtle.xcor()
  starting_y = turtle.ycor()
  turtle.setheading(0) # Face to the right
  turtle.pendown()
  turtle.forward(width)
  turtle.left(90)
  turtle.forward(height)
  turtle.goto(starting_x, starting_y)
  turtle.penup()

C
def draw_offset_grid_of_triangles(num_columns, num_triangles_per_column, triangle_width, triangle_height):
  starting_x = turtle.xcor()
  starting_y = turtle.ycor()
  for column_index in range(num_columns):
    turtle.setx(starting_x + column_index * triangle_width)
    if column_index % 2 == 0:
      turtle.sety(starting_y + triangle_height / 2)
    else:
      turtle.sety(starting_y)
    draw_column_of_triangles(num_triangles_per_column, triangle_width, triangle_height)
  turtle.setx(starting_x)
  turtle.sety(starting_y)

# Drawing a grid of triangles
turtle.penup()

# You can set the animation speed from 1 (slow) to 10 (fast).
# You can also set the speed to 0 to go as fast as possible.
turtle.speed(0)

turtle.goto(-100, 100)
turtle.color('blue')
draw_column_of_triangles(7, 30, 20)

turtle.goto(-50, 100)
turtle.color('red')
draw_grid_of_triangles(5, 4, 20, 30)

turtle.goto(-100, -100)
turtle.color('green')
draw_offset_grid_of_triangles(9, 7, 20, 20)
result
console