Problem with variable assignment.

edited February 2018 in Python Mode

Hello Guys,

I ran into a Problem when i tried to convert a Program from JS to Python.

My Problem: I assign a variable count = 0 before the setup() In draw() i want to increase this variable by a given amount but i get a "local variable 'count' referenced before assignment" Error. Maybe i am blind to a Bug in my code.

Thanks for the help.

from branch import Branch

tree = []
leaves = []
count = 0

def setup():
    size(400,400)
    a = PVector(width/2, height)
    b = PVector(width/2, height - 100)
    global root
    root = Branch(a,b)
    tree.append(root) 

def draw():
    background(51)

    if (keyPressed == True):        
        for i in range(len(tree)):
            if (tree[i].finished == False):
                tree.append(tree[i].branchA())
                tree.append(tree[i].branchB())
            tree[i].finished = True
        count += 1

    # if (count == 6):
    #     for i in range(len(tree)):
    #         if (tree[i].finished == False):
    #             leaf = tree[i].end.copy()
    #             leaves.append(leaf)
    #     for i in range(len(leaves)):
    #         fill(255,0,100)
    #         ellipse(leafes[i].x,leafes[i].y, 8 ,8)


    print(count)
    for i in tree:
        i.show()

class Branch(object):
    def __init__(self, startpos,endpos):
        self.startpos = startpos
        self.endpos = endpos
        self.finished = False


    def show(self):
        stroke(255)
        line(self.startpos.x,self.startpos.y, self.endpos.x, self.endpos.y)

    def branchA(self):
        dir = PVector.sub(self.endpos, self.startpos)
        dir.rotate(PI/4)
        dir.mult(0.67)
        newEnd = PVector.add(self.endpos, dir)

        right = Branch(self.endpos, newEnd)
        return right

    def branchB(self):
        dir = PVector.sub(self.endpos, self.startpos)
        dir.rotate((PI/4) * (-1))
        dir.mult(0.67)
        newEnd = PVector.add(self.endpos, dir)

        left = Branch(self.endpos, newEnd)
        return left

Edit found the right way to format the codeblock

Answers

  • Answer ✓

    Not super up to date on the Python Mode myself, but I suspect that you need to mention global count in your draw() function to use the global count variable...?

  • Ah thanks a lot. That worked.

Sign In or Register to comment.