0

How can I create separate coins in a page that are not overlapping or not touching each other. The code below shows overlapping coins if the number is greater than 2.

import turtle

tegan = turtle.Turtle()

turtle.fillcolor('grey')

turtle.begin_fill()


numbers = int(input("How many 50 pence coins you have: "))
print(numbers)

length = 100  
degrees = 51.42857
angle = 40

def draw_heptagon(tegan, length, numbers, angle):

    for i in range(numbers):
        for x in range(7):
            turtle.forward(length)
            turtle.left(degrees)
        turtle.right(angle)

draw_heptagon(tegan, length, numbers, angle)

turtle.end_fill()
turtle.done()
  • 1
    Draw them further apart? – khelwood May 10 '22 at 10:37
  • after drawing an heptagon you jut turn right a certain angle. you can also add a `turtle.forward` that will draw the next heptagons apart as suggested by khelwood. –  May 10 '22 at 10:47
  • You should penup after drawing each coin, move to somewhere, and then pendown for drawing the next one: turtle.penup();turtle.settiltangle(0); turtle.forward(length * 3);turtle.pendown() – Menglong Li May 10 '22 at 11:00

1 Answers1

0

Here's an approximate approach that you can refine. We'll keep track of the centers of the randomly placed heptagons we draw. We'll treat them as circles for purposes of drawing and checking the distances between them:

from turtle import Screen, Turtle
from random import randint

RADIUS = 100
ANGLE = 40

number = int(input("How many 50 pence coins you have: "))

def draw_heptagons(t, number):
    coins = []

    for _ in range(number):
        while True:
            x = randint(RADIUS - width/2, width/2 - RADIUS)
            y = randint(RADIUS - height/2, height/2 - RADIUS)

            t.goto(x, y)
            t.right(ANGLE)

            if coins and any(t.distance(position) < RADIUS * 2 for position in coins):
                continue

            break

        t.right(90)
        t.forward(RADIUS)  # draw heptagon centered at x, y
        t.left(90)

        turtle.begin_fill()
        t.circle(RADIUS, steps=7)
        turtle.end_fill()

        coins.append((x, y))

screen = Screen()
width, height = screen.window_width(), screen.window_height()

turtle = Turtle()
turtle.speed('fastest')  # because I have no patience
turtle.penup()

draw_heptagons(turtle, number)

turtle.hideturtle()
screen.exitonclick()

This does what you describe but the heptagons could actually be closer (fit more of them in the window) than circles, so you need to modify the test, and what information you store in positions, if you want to pack them tighter:

enter image description here

cdlane
  • 40,441
  • 5
  • 32
  • 81