P
P
PythonStudent2020-03-26 21:17:54
Python
PythonStudent, 2020-03-26 21:17:54

Does not work out the method of drawing a segment, what's wrong?

Hello, I solve the problem of drawing a fractal, namely the Gosper curve, there are the following methods:

class turtle:
    def __init__(self):
        self._direction = np.array([1, 0]) # 2D direction vector
        self._position = np.array([0, 0]) # 2D position vector
    def forward(self):
        pos = self._position
        dirn = self._direction
        self._position = np.add(pos, dirn)
    def rotate(self, theta):
        (x, y) = self._direction
        current_angle = atan2(y, x)
        new_angle = current_angle + radians(theta)
        self._direction = [cos(new_angle), sin(new_angle)]

forward() - move forward, rotate() - rotate by 60 degrees, respectively.
The algorithm for constructing a fractal -
commands = {
    'A': 't.forward()',
    'B': 't.forward()',
    '+': 't.rotate(-theta)',
    '-': 't.rotate(theta)',
    }

axiom = 'A'
production_rules = {
    'A': 'A-B--B+A++AA+B-',
    'B': '+A-BB--B-A++A+B'
    }
theta = 60
theta_second = 0

style = {'description_width': 'initial'}
n_iterations = widgets.IntSlider(style=style, min=1, max=7, step=1, description='Number of iterations:', value=1)
display(n_iterations)


So I noticed the following problem, that in rule A -
production_rules = {
    'A': 'A-B--B+A++AA+B-',
, in the first case, when there is no sign + or -, that is, turning by an angle, the segment is not drawn (Figure 1), if you put + or - before this, then the desired segment is drawn (Figure 2), but according to the conditions of the fractal, it is necessary straight cut, not at an angle.
5e7cf18d364b4912448462.png
5e7cf19bc7081412189816.png
I think it's the forward() but I don't understand what exactly is wrong.
def forward(self):
        pos = self._position
        dirn = self._direction
        self._position = np.add(pos, dirn)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vast Nectarine, 2020-03-27
@PythonStudent

I posted an example here, but using turtule, and everything works for me.
Compare the axiom after the substitution. Maybe you don't put it that way.

The code:

import turtle

rules = {
    "A": "A-B--B+A++AA+B-",
    "B": "+A-BB--B-A++A+B",
    '+': '+',
    '-': '-'
}

axiom = ['A']

level = 5

for i in range(level):
    p = []
    for j in range(len(axiom)):
        s = list(rules[axiom[j]])
        p.extend(s)
    axiom = p

print(axiom)
t = turtle.Turtle()

for l in axiom:
    if l in ['A', 'B']:
        t.forward(10)
    elif l == '+':
        t.left(60)
    elif l == '-':
        t.right(60)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question